3 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
5 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6 # format is way easier to parse. Because it's simpler to "gear" from
7 # Unix ABI to Windows one [see cross-reference "card" at the end of
8 # file]. Because Linux targets were available first...
10 # In addition the script also "distills" code suitable for GNU
11 # assembler, so that it can be compiled with more rigid assemblers,
12 # such as Solaris /usr/ccs/bin/as.
14 # This translator is not designed to convert *arbitrary* assembler
15 # code from AT&T format to MASM one. It's designed to convert just
16 # enough to provide for dual-ABI OpenSSL modules development...
17 # There *are* limitations and you might have to modify your assembler
18 # code or this script to achieve the desired result...
20 # Currently recognized limitations:
22 # - can't use multiple ops per line;
24 # Dual-ABI styling rules.
26 # 1. Adhere to Unix register and stack layout [see cross-reference
27 # ABI "card" at the end for explanation].
28 # 2. Forget about "red zone," stick to more traditional blended
29 # stack frame allocation. If volatile storage is actually required
30 # that is. If not, just leave the stack as is.
31 # 3. Functions tagged with ".type name,@function" get crafted with
32 # unified Win64 prologue and epilogue automatically. If you want
33 # to take care of ABI differences yourself, tag functions as
34 # ".type name,@abi-omnipotent" instead.
35 # 4. To optimize the Win64 prologue you can specify number of input
36 # arguments as ".type name,@function,N." Keep in mind that if N is
37 # larger than 6, then you *have to* write "abi-omnipotent" code,
38 # because >6 cases can't be addressed with unified prologue.
39 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
40 # (sorry about latter).
41 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
42 # required to identify the spots, where to inject Win64 epilogue!
43 # But on the pros, it's then prefixed with rep automatically:-)
44 # 7. Stick to explicit ip-relative addressing. If you have to use
45 # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
46 # Both are recognized and translated to proper Win64 addressing
47 # modes. To support legacy code a synthetic directive, .picmeup,
48 # is implemented. It puts address of the *next* instruction into
49 # target register, e.g.:
52 # lea .Label-.(%rax),%rax
54 # 8. In order to provide for structured exception handling unified
55 # Win64 prologue copies %rsp value to %rax. For further details
56 # see SEH paragraph at the end.
57 # 9. .init segment is allowed to contain calls to functions only.
58 # a. If function accepts more than 4 arguments *and* >4th argument
59 # is declared as non 64-bit value, do clear its upper part.
63 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
65 open STDOUT,">$output" || die "can't open $output: $!"
66 if (defined($output));
68 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
69 my $elf=1; $elf=0 if (!$gas);
74 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
81 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
82 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
85 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
86 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
87 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
89 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
90 { $nasm = $1 + $2*0.01; $PTR=""; }
91 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
92 { $masm = $1 + $2*2**-16 + $4*2**-32; }
93 die "no assembler found on %PATH" if (!($nasm || $masm));
100 my $current_function;
103 { package opcode; # pick up opcodes
105 my $self = shift; # single instance in enough...
109 if ($line =~ /^([a-z][a-z0-9]*)/i) {
112 $line = substr($line,@+[0]); $line =~ s/^\s+//;
115 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
118 } elsif ($self->{op} =~ /call|jmp/) {
120 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
122 } elsif ($self->{op} =~ /^v/) { # VEX
124 } elsif ($self->{op} =~ /mov[dq]/ && $line =~ /%xmm/) {
126 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
136 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
142 if ($self->{op} eq "movz") { # movz is pain...
143 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
144 } elsif ($self->{op} =~ /^set/) {
146 } elsif ($self->{op} eq "ret") {
148 if ($win64 && $current_function->{abi} eq "svr4") {
149 $epilogue = "movq 8(%rsp),%rdi\n\t" .
150 "movq 16(%rsp),%rsi\n\t";
152 $epilogue . ".byte 0xf3,0xc3";
153 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
154 ".p2align\t3\n\t.quad";
156 "$self->{op}$self->{sz}";
159 $self->{op} =~ s/^movz/movzx/;
160 if ($self->{op} eq "ret") {
162 if ($win64 && $current_function->{abi} eq "svr4") {
163 $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
164 "mov rsi,QWORD${PTR}[16+rsp]\n\t";
166 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
167 } elsif ($self->{op} =~ /^(pop|push)f/) {
168 $self->{op} .= $self->{sz};
169 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
170 $self->{op} = "\tDQ";
178 $self->{op}=$op if (defined($op));
182 { package const; # pick up constants, which start with $
184 my $self = shift; # single instance in enough...
188 if ($line =~ /^\$([^,]+)/) {
191 $line = substr($line,@+[0]); $line =~ s/^\s+//;
199 # Solaris /usr/ccs/bin/as can't handle multiplications
201 $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
202 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
203 sprintf "\$%s",$self->{value};
205 $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
206 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
207 sprintf "%s",$self->{value};
211 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
213 my $self = shift; # single instance in enough...
217 # optional * ---vvv--- appears in indirect jmp/call
218 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
219 $self->{asterisk} = $1;
221 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
222 $self->{scale} = 1 if (!defined($self->{scale}));
224 $line = substr($line,@+[0]); $line =~ s/^\s+//;
226 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
227 die if (opcode->mnemonic() ne "mov");
228 opcode->mnemonic("lea");
230 $self->{base} =~ s/^%//;
231 $self->{index} =~ s/^%// if (defined($self->{index}));
240 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
241 $self->{label} =~ s/\.L/$decor/g;
243 # Silently convert all EAs to 64-bit. This is required for
244 # elder GNU assembler and results in more compact code,
245 # *but* most importantly AES module depends on this feature!
246 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
247 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
249 # Solaris /usr/ccs/bin/as can't handle multiplications
250 # in $self->{label}, new gas requires sign extension...
252 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
253 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
254 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
256 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
257 $self->{base} =~ /(rbp|r13)/) {
258 $self->{base} = $self->{index}; $self->{index} = $1;
262 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
264 if (defined($self->{index})) {
265 sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
267 $self->{base}?"%$self->{base}":"",
268 $self->{index},$self->{scale};
270 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
273 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
274 l=>"DWORD$PTR", d=>"DWORD$PTR",
275 q=>"QWORD$PTR", o=>"OWORD$PTR",
276 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
278 $self->{label} =~ s/\./\$/g;
279 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
280 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
282 ($self->{asterisk}) && ($sz="q") ||
283 (opcode->mnemonic() =~ /^v?mov([qd])$/) && ($sz=$1) ||
284 (opcode->mnemonic() =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
285 (opcode->mnemonic() =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
286 (opcode->mnemonic() =~ /^vinsert[fi]128$/) && ($sz="x");
288 if (defined($self->{index})) {
289 sprintf "%s[%s%s*%d%s]",$szmap{$sz},
290 $self->{label}?"$self->{label}+":"",
291 $self->{index},$self->{scale},
292 $self->{base}?"+$self->{base}":"";
293 } elsif ($self->{base} eq "rip") {
294 sprintf "%s[%s]",$szmap{$sz},$self->{label};
296 sprintf "%s[%s%s]",$szmap{$sz},
297 $self->{label}?"$self->{label}+":"",
303 { package register; # pick up registers, which start with %.
305 my $class = shift; # muliple instances...
310 # optional * ---vvv--- appears in indirect jmp/call
311 if ($line =~ /^(\*?)%(\w+)/) {
313 $self->{asterisk} = $1;
316 $line = substr($line,@+[0]); $line =~ s/^\s+//;
324 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
325 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
326 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
327 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
328 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
329 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
330 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
331 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
337 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
338 else { $self->{value}; }
341 { package label; # pick up labels, which end with :
343 my $self = shift; # single instance is enough...
347 if ($line =~ /(^[\.\w]+)\:/) {
350 $line = substr($line,@+[0]); $line =~ s/^\s+//;
352 $self->{value} =~ s/^\.L/$decor/;
360 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
362 $current_function->{name} eq $self->{value} &&
363 $current_function->{abi} eq "svr4") {
365 $func .= " movq %rdi,8(%rsp)\n";
366 $func .= " movq %rsi,16(%rsp)\n";
367 $func .= " movq %rsp,%rax\n";
368 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
369 my $narg = $current_function->{narg};
370 $narg=6 if (!defined($narg));
371 $func .= " movq %rcx,%rdi\n" if ($narg>0);
372 $func .= " movq %rdx,%rsi\n" if ($narg>1);
373 $func .= " movq %r8,%rdx\n" if ($narg>2);
374 $func .= " movq %r9,%rcx\n" if ($narg>3);
375 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
376 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
379 } elsif ($self->{value} ne "$current_function->{name}") {
380 $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
381 $self->{value} . ":";
382 } elsif ($win64 && $current_function->{abi} eq "svr4") {
383 my $func = "$current_function->{name}" .
384 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
386 $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
387 $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
388 $func .= " mov rax,rsp\n";
389 $func .= "${decor}SEH_begin_$current_function->{name}:";
390 $func .= ":" if ($masm);
392 my $narg = $current_function->{narg};
393 $narg=6 if (!defined($narg));
394 $func .= " mov rdi,rcx\n" if ($narg>0);
395 $func .= " mov rsi,rdx\n" if ($narg>1);
396 $func .= " mov rdx,r8\n" if ($narg>2);
397 $func .= " mov rcx,r9\n" if ($narg>3);
398 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
399 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
402 "$current_function->{name}".
403 ($nasm ? ":" : "\tPROC $current_function->{scope}");
407 { package expr; # pick up expressioins
409 my $self = shift; # single instance is enough...
413 if ($line =~ /(^[^,]+)/) {
416 $line = substr($line,@+[0]); $line =~ s/^\s+//;
418 $self->{value} =~ s/\@PLT// if (!$elf);
419 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
420 $self->{value} =~ s/\.L/$decor/g;
426 if ($nasm && opcode->mnemonic()=~m/^j(?![re]cxz)/) {
427 "NEAR ".$self->{value};
433 { package directive; # pick up directives, which start with .
435 my $self = shift; # single instance is enough...
439 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
440 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
441 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
442 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
443 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
444 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
445 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
446 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
447 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
449 if ($line =~ /^\s*(\.\w+)/) {
452 undef $self->{value};
453 $line = substr($line,@+[0]); $line =~ s/^\s+//;
456 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
458 $line=sprintf "0x%x,0x90000000",$opcode{$1};
462 /\.global|\.globl|\.extern/
463 && do { $globals{$line} = $prefix . $line;
464 $line = $globals{$line} if ($prefix);
467 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
468 if ($type eq "\@function") {
469 undef $current_function;
470 $current_function->{name} = $sym;
471 $current_function->{abi} = "svr4";
472 $current_function->{narg} = $narg;
473 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
474 } elsif ($type eq "\@abi-omnipotent") {
475 undef $current_function;
476 $current_function->{name} = $sym;
477 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
479 $line =~ s/\@abi\-omnipotent/\@function/;
480 $line =~ s/\@function.*/\@function/;
483 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
485 $line = join(",",unpack("C*",$1),0);
489 /\.rva|\.long|\.quad/
490 && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
491 $line =~ s/\.L/$decor/g;
497 $self->{value} = $dir . "\t" . $line;
499 if ($dir =~ /\.extern/) {
500 $self->{value} = ""; # swallow extern
501 } elsif (!$elf && $dir =~ /\.type/) {
503 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
504 (defined($globals{$1})?".scl 2;":".scl 3;") .
505 "\t.type 32;\t.endef"
506 if ($win64 && $line =~ /([^,]+),\@function/);
507 } elsif (!$elf && $dir =~ /\.size/) {
509 if (defined($current_function)) {
510 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
511 if ($win64 && $current_function->{abi} eq "svr4");
512 undef $current_function;
514 } elsif (!$elf && $dir =~ /\.align/) {
515 $self->{value} = ".p2align\t" . (log($line)/log(2));
516 } elsif ($dir eq ".section") {
517 $current_segment=$line;
518 if (!$elf && $current_segment eq ".init") {
519 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
520 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
522 } elsif ($dir =~ /\.(text|data)/) {
523 $current_segment=".$1";
524 } elsif ($dir =~ /\.hidden/) {
525 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$line"; }
526 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
527 } elsif ($dir =~ /\.comm/) {
528 $self->{value} = "$dir\t$prefix$line";
529 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
535 # non-gas case or nasm/masm
537 /\.text/ && do { my $v=undef;
539 $v="section .text code align=64\n";
541 $v="$current_segment\tENDS\n" if ($current_segment);
542 $current_segment = ".text\$";
543 $v.="$current_segment\tSEGMENT ";
544 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
550 /\.data/ && do { my $v=undef;
552 $v="section .data data align=8\n";
554 $v="$current_segment\tENDS\n" if ($current_segment);
555 $current_segment = "_DATA";
556 $v.="$current_segment\tSEGMENT";
561 /\.section/ && do { my $v=undef;
562 $line =~ s/([^,]*).*/$1/;
563 $line = ".CRT\$XCU" if ($line eq ".init");
566 if ($line=~/\.([px])data/) {
568 $v.=$1 eq "p"? 4 : 8;
569 } elsif ($line=~/\.CRT\$/i) {
570 $v.=" rdata align=8";
573 $v="$current_segment\tENDS\n" if ($current_segment);
574 $v.="$line\tSEGMENT";
575 if ($line=~/\.([px])data/) {
577 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
578 } elsif ($line=~/\.CRT\$/i) {
580 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
583 $current_segment = $line;
587 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
588 $self->{value} .= ":NEAR" if ($masm);
592 && do { $self->{value} = $masm?"PUBLIC":"global";
593 $self->{value} .= "\t".$line;
596 /\.size/ && do { if (defined($current_function)) {
597 undef $self->{value};
598 if ($current_function->{abi} eq "svr4") {
599 $self->{value}="${decor}SEH_end_$current_function->{name}:";
600 $self->{value}.=":\n" if($masm);
602 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
603 undef $current_function;
607 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
608 /\.(value|long|rva|quad)/
609 && do { my $sz = substr($1,0,1);
610 my @arr = split(/,\s*/,$line);
611 my $last = pop(@arr);
612 my $conv = sub { my $var=shift;
613 $var=~s/^(0b[0-1]+)/oct($1)/eig;
614 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
615 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
616 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
620 $sz =~ tr/bvlrq/BWDDQ/;
621 $self->{value} = "\tD$sz\t";
622 for (@arr) { $self->{value} .= &$conv($_).","; }
623 $self->{value} .= &$conv($last);
626 /\.byte/ && do { my @str=split(/,\s*/,$line);
627 map(s/(0b[0-1]+)/oct($1)/eig,@str);
628 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
630 $self->{value}.="DB\t"
631 .join(",",@str[0..15])."\n";
632 foreach (0..15) { shift @str; }
634 $self->{value}.="DB\t"
635 .join(",",@str) if (@str);
638 /\.comm/ && do { my @str=split(/,\s*/,$line);
641 $v.="common $prefix@str[0] @str[1]";
643 $v="$current_segment\tENDS\n" if ($current_segment);
644 $current_segment = "_DATA";
645 $v.="$current_segment\tSEGMENT\n";
646 $v.="COMM @str[0]:DWORD:".@str[1]/4;
665 my ($dst,$src,$rex)=@_;
667 $rex|=0x04 if($dst>=8);
668 $rex|=0x01 if($src>=8);
669 push @opcode,($rex|0x40) if ($rex);
672 # older gas and ml64 don't handle SSE>2 instructions
673 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
674 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
676 my $movq = sub { # elderly gas can't handle inter-register movq
679 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
680 my ($src,$dst)=($1,$2);
681 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
682 rex(\@opcode,$src,$dst,0x8);
683 push @opcode,0x0f,0x7e;
684 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
686 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
687 my ($src,$dst)=($2,$1);
688 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
689 rex(\@opcode,$src,$dst,0x8);
690 push @opcode,0x0f,0x6e;
691 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
699 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
704 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
705 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
706 rex(\@opcode,$src,$dst);
707 push @opcode,0x0f,0x3a,0x16;
708 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
717 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
722 if ($src =~ /%r([0-9]+)/) { $src = $1; }
723 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
724 rex(\@opcode,$dst,$src);
725 push @opcode,0x0f,0x3a,0x22;
726 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
735 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
738 push @opcode,0x0f,0x38,0x00;
739 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
747 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
750 push @opcode,0x0f,0x3a,0x0f;
751 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
759 my $pclmulqdq = sub {
760 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
763 push @opcode,0x0f,0x3a,0x44;
764 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
766 push @opcode,$c=~/^0/?oct($c):$c;
774 if (shift =~ /%[er](\w+)/) {
777 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
778 rex(\@opcode,0,$1,8);
779 push @opcode,0x0f,0xc7,0xf0|($dst&7);
787 if (shift =~ /%[er](\w+)/) {
790 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
791 rex(\@opcode,0,$1,8);
792 push @opcode,0x0f,0xc7,0xf8|($dst&7);
801 my ($dst,$src1,$src2,$rxb)=@_;
804 $rxb&=~(0x04<<5) if($dst>=8);
805 $rxb&=~(0x01<<5) if($src1>=8);
806 $rxb&=~(0x02<<5) if($src2>=8);
811 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
813 rxb(\@opcode,$3,$2,-1,0x08);
814 push @opcode,0x78,0xc2;
815 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
817 push @opcode,$c=~/^0/?oct($c):$c;
825 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
827 rxb(\@opcode,$3,$2,-1,0x08);
828 push @opcode,0x78,0xc3;
829 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
831 push @opcode,$c=~/^0/?oct($c):$c;
854 $line =~ s|[#!].*$||; # get rid of asm-style comments...
855 $line =~ s|/\*.*\*/||; # ... and C-style comments...
856 $line =~ s|^\s+||; # ... and skip white spaces in beginning
857 $line =~ s|\s+$||; # ... and at the end
863 if ($label=label->re(\$line)) { print $label->out(); }
865 if (directive->re(\$line)) {
866 printf "%s",directive->out();
867 } elsif ($opcode=opcode->re(\$line)) {
868 my $asm = eval("\$".$opcode->mnemonic());
871 if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
872 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
876 ARGUMENT: while (1) {
879 if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
880 elsif ($arg=const->re(\$line)) { }
881 elsif ($arg=ea->re(\$line)) { }
882 elsif ($arg=expr->re(\$line)) { }
883 else { last ARGUMENT; }
887 last ARGUMENT if ($line !~ /^,/);
894 my $sz=opcode->size();
897 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
898 @args = map($_->out($sz),@args);
899 printf "\t%s\t%s",$insn,join(",",@args);
901 $insn = $opcode->out();
904 # $insn.=$sz compensates for movq, pinsrw, ...
905 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
906 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
907 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
908 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
910 @args = reverse(@args);
911 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
912 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
915 printf "\t%s",$opcode->out();
922 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
923 print "END\n" if ($masm);
927 \f#################################################
928 # Cross-reference x86_64 ABI "card"
948 # (*) volatile register
949 # (-) preserved by callee
950 # (#) Nth argument, volatile
952 # In Unix terms top of stack is argument transfer area for arguments
953 # which could not be accomodated in registers. Or in other words 7th
954 # [integer] argument resides at 8(%rsp) upon function entry point.
955 # 128 bytes above %rsp constitute a "red zone" which is not touched
956 # by signal handlers and can be used as temporal storage without
957 # allocating a frame.
959 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
960 # which belongs to/can be overwritten by callee. N is the number of
961 # arguments passed to callee, *but* not less than 4! This means that
962 # upon function entry point 5th argument resides at 40(%rsp), as well
963 # as that 32 bytes from 8(%rsp) can always be used as temporal
964 # storage [without allocating a frame]. One can actually argue that
965 # one can assume a "red zone" above stack pointer under Win64 as well.
966 # Point is that at apparently no occasion Windows kernel would alter
967 # the area above user stack pointer in true asynchronous manner...
969 # All the above means that if assembler programmer adheres to Unix
970 # register and stack layout, but disregards the "red zone" existense,
971 # it's possible to use following prologue and epilogue to "gear" from
972 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
974 # omnipotent_function:
978 # movq %rcx,%rdi ; if 1st argument is actually present
979 # movq %rdx,%rsi ; if 2nd argument is actually ...
980 # movq %r8,%rdx ; if 3rd argument is ...
981 # movq %r9,%rcx ; if 4th argument ...
982 # movq 40(%rsp),%r8 ; if 5th ...
983 # movq 48(%rsp),%r9 ; if 6th ...
992 \f#################################################
993 # Win64 SEH, Structured Exception Handling.
995 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
996 # has undesired side-effect at run-time: if an exception is raised in
997 # assembler subroutine such as those in question (basically we're
998 # referring to segmentation violations caused by malformed input
999 # parameters), the application is briskly terminated without invoking
1000 # any exception handlers, most notably without generating memory dump
1001 # or any user notification whatsoever. This poses a problem. It's
1002 # possible to address it by registering custom language-specific
1003 # handler that would restore processor context to the state at
1004 # subroutine entry point and return "exception is not handled, keep
1005 # unwinding" code. Writing such handler can be a challenge... But it's
1006 # doable, though requires certain coding convention. Consider following
1009 # .type function,@function
1011 # movq %rsp,%rax # copy rsp to volatile register
1012 # pushq %r15 # save non-volatile registers
1016 # subq %rdi,%r11 # prepare [variable] stack frame
1018 # movq %rax,0(%r11) # check for exceptions
1019 # movq %r11,%rsp # allocate [variable] stack frame
1020 # movq %rax,0(%rsp) # save original rsp value
1023 # movq 0(%rsp),%rcx # pull original rsp value
1024 # movq -24(%rcx),%rbp # restore non-volatile registers
1025 # movq -16(%rcx),%rbx
1026 # movq -8(%rcx),%r15
1027 # movq %rcx,%rsp # restore original rsp
1029 # .size function,.-function
1031 # The key is that up to magic_point copy of original rsp value remains
1032 # in chosen volatile register and no non-volatile register, except for
1033 # rsp, is modified. While past magic_point rsp remains constant till
1034 # the very end of the function. In this case custom language-specific
1035 # exception handler would look like this:
1037 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1038 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1039 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1040 # if (context->Rip >= magic_point)
1041 # { rsp = ((ULONG64 **)context->Rsp)[0];
1042 # context->Rbp = rsp[-3];
1043 # context->Rbx = rsp[-2];
1044 # context->R15 = rsp[-1];
1046 # context->Rsp = (ULONG64)rsp;
1047 # context->Rdi = rsp[1];
1048 # context->Rsi = rsp[2];
1050 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1051 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1052 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1053 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1054 # return ExceptionContinueSearch;
1057 # It's appropriate to implement this handler in assembler, directly in
1058 # function's module. In order to do that one has to know members'
1059 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1060 # values. Here they are:
1080 # sizeof(CONTEXT) 1232
1081 # DISPATCHER_CONTEXT.ControlPc 0
1082 # DISPATCHER_CONTEXT.ImageBase 8
1083 # DISPATCHER_CONTEXT.FunctionEntry 16
1084 # DISPATCHER_CONTEXT.EstablisherFrame 24
1085 # DISPATCHER_CONTEXT.TargetIp 32
1086 # DISPATCHER_CONTEXT.ContextRecord 40
1087 # DISPATCHER_CONTEXT.LanguageHandler 48
1088 # DISPATCHER_CONTEXT.HandlerData 56
1089 # UNW_FLAG_NHANDLER 0
1090 # ExceptionContinueSearch 1
1092 # In order to tie the handler to the function one has to compose
1093 # couple of structures: one for .xdata segment and one for .pdata.
1095 # UNWIND_INFO structure for .xdata segment would be
1097 # function_unwind_info:
1101 # This structure designates exception handler for a function with
1102 # zero-length prologue, no stack frame or frame register.
1104 # To facilitate composing of .pdata structures, auto-generated "gear"
1105 # prologue copies rsp value to rax and denotes next instruction with
1106 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1107 # styling rule mentioned in the beginning. Position of this label is
1108 # chosen in such manner that possible exceptions raised in the "gear"
1109 # prologue would be accounted to caller and unwound from latter's frame.
1110 # End of function is marked with respective .LSEH_end_{function_name}
1111 # label. To summarize, .pdata segment would contain
1113 # .rva .LSEH_begin_function
1114 # .rva .LSEH_end_function
1115 # .rva function_unwind_info
1117 # Reference to functon_unwind_info from .xdata segment is the anchor.
1118 # In case you wonder why references are 32-bit .rvas and not 64-bit
1119 # .quads. References put into these two segments are required to be
1120 # *relative* to the base address of the current binary module, a.k.a.
1121 # image base. No Win64 module, be it .exe or .dll, can be larger than
1122 # 2GB and thus such relative references can be and are accommodated in
1125 # Having reviewed the example function code, one can argue that "movq
1126 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1127 # rax would contain an undefined value. If this "offends" you, use
1128 # another register and refrain from modifying rax till magic_point is
1129 # reached, i.e. as if it was a non-volatile register. If more registers
1130 # are required prior [variable] frame setup is completed, note that
1131 # nobody says that you can have only one "magic point." You can
1132 # "liberate" non-volatile registers by denoting last stack off-load
1133 # instruction and reflecting it in finer grade unwind logic in handler.
1134 # After all, isn't it why it's called *language-specific* handler...
1136 # Attentive reader can notice that exceptions would be mishandled in
1137 # auto-generated "gear" epilogue. Well, exception effectively can't
1138 # occur there, because if memory area used by it was subject to
1139 # segmentation violation, then it would be raised upon call to the
1140 # function (and as already mentioned be accounted to caller, which is
1141 # not a problem). If you're still not comfortable, then define tail
1142 # "magic point" just prior ret instruction and have handler treat it...
1144 # (*) Note that we're talking about run-time, not debug-time. Lack of
1145 # unwind information makes debugging hard on both Windows and
1146 # Unix. "Unlike" referes to the fact that on Unix signal handler
1147 # will always be invoked, core dumped and appropriate exit code
1148 # returned to parent (for user notification).