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 -`;
83 $prefix =~ s|\R$||; # Better chomp
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 my $value = $self->{value};
202 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
203 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
204 $self->{value} = $value;
206 sprintf "\$%s",$self->{value};
208 $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
209 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
210 sprintf "%s",$self->{value};
214 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
216 my $self = shift; # single instance in enough...
220 # optional * ---vvv--- appears in indirect jmp/call
221 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
222 $self->{asterisk} = $1;
224 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
225 $self->{scale} = 1 if (!defined($self->{scale}));
227 $line = substr($line,@+[0]); $line =~ s/^\s+//;
229 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
230 die if (opcode->mnemonic() ne "mov");
231 opcode->mnemonic("lea");
233 $self->{base} =~ s/^%//;
234 $self->{index} =~ s/^%// if (defined($self->{index}));
243 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
244 $self->{label} =~ s/\.L/$decor/g;
246 # Silently convert all EAs to 64-bit. This is required for
247 # elder GNU assembler and results in more compact code,
248 # *but* most importantly AES module depends on this feature!
249 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
250 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
252 # Solaris /usr/ccs/bin/as can't handle multiplications
253 # in $self->{label}, new gas requires sign extension...
255 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
256 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
257 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
259 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
260 $self->{base} =~ /(rbp|r13)/) {
261 $self->{base} = $self->{index}; $self->{index} = $1;
265 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
267 if (defined($self->{index})) {
268 sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
270 $self->{base}?"%$self->{base}":"",
271 $self->{index},$self->{scale};
273 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
276 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
277 l=>"DWORD$PTR", d=>"DWORD$PTR",
278 q=>"QWORD$PTR", o=>"OWORD$PTR",
279 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
281 $self->{label} =~ s/\./\$/g;
282 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
283 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
285 ($self->{asterisk}) && ($sz="q") ||
286 (opcode->mnemonic() =~ /^v?mov([qd])$/) && ($sz=$1) ||
287 (opcode->mnemonic() =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
288 (opcode->mnemonic() =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
289 (opcode->mnemonic() =~ /^vinsert[fi]128$/) && ($sz="x");
291 if (defined($self->{index})) {
292 sprintf "%s[%s%s*%d%s]",$szmap{$sz},
293 $self->{label}?"$self->{label}+":"",
294 $self->{index},$self->{scale},
295 $self->{base}?"+$self->{base}":"";
296 } elsif ($self->{base} eq "rip") {
297 sprintf "%s[%s]",$szmap{$sz},$self->{label};
299 sprintf "%s[%s%s]",$szmap{$sz},
300 $self->{label}?"$self->{label}+":"",
306 { package register; # pick up registers, which start with %.
308 my $class = shift; # multiple instances...
313 # optional * ---vvv--- appears in indirect jmp/call
314 if ($line =~ /^(\*?)%(\w+)/) {
316 $self->{asterisk} = $1;
319 $line = substr($line,@+[0]); $line =~ s/^\s+//;
327 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
328 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
329 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
330 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
331 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
332 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
333 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
334 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
340 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
341 else { $self->{value}; }
344 { package label; # pick up labels, which end with :
346 my $self = shift; # single instance is enough...
350 if ($line =~ /(^[\.\w]+)\:/) {
353 $line = substr($line,@+[0]); $line =~ s/^\s+//;
355 $self->{value} =~ s/^\.L/$decor/;
363 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
365 $current_function->{name} eq $self->{value} &&
366 $current_function->{abi} eq "svr4") {
368 $func .= " movq %rdi,8(%rsp)\n";
369 $func .= " movq %rsi,16(%rsp)\n";
370 $func .= " movq %rsp,%rax\n";
371 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
372 my $narg = $current_function->{narg};
373 $narg=6 if (!defined($narg));
374 $func .= " movq %rcx,%rdi\n" if ($narg>0);
375 $func .= " movq %rdx,%rsi\n" if ($narg>1);
376 $func .= " movq %r8,%rdx\n" if ($narg>2);
377 $func .= " movq %r9,%rcx\n" if ($narg>3);
378 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
379 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
382 } elsif ($self->{value} ne "$current_function->{name}") {
383 $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
384 $self->{value} . ":";
385 } elsif ($win64 && $current_function->{abi} eq "svr4") {
386 my $func = "$current_function->{name}" .
387 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
389 $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
390 $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
391 $func .= " mov rax,rsp\n";
392 $func .= "${decor}SEH_begin_$current_function->{name}:";
393 $func .= ":" if ($masm);
395 my $narg = $current_function->{narg};
396 $narg=6 if (!defined($narg));
397 $func .= " mov rdi,rcx\n" if ($narg>0);
398 $func .= " mov rsi,rdx\n" if ($narg>1);
399 $func .= " mov rdx,r8\n" if ($narg>2);
400 $func .= " mov rcx,r9\n" if ($narg>3);
401 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
402 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
405 "$current_function->{name}".
406 ($nasm ? ":" : "\tPROC $current_function->{scope}");
410 { package expr; # pick up expressioins
412 my $self = shift; # single instance is enough...
416 if ($line =~ /(^[^,]+)/) {
419 $line = substr($line,@+[0]); $line =~ s/^\s+//;
421 $self->{value} =~ s/\@PLT// if (!$elf);
422 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
423 $self->{value} =~ s/\.L/$decor/g;
429 if ($nasm && opcode->mnemonic()=~m/^j(?![re]cxz)/) {
430 "NEAR ".$self->{value};
436 { package directive; # pick up directives, which start with .
438 my $self = shift; # single instance is enough...
442 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
443 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
444 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
445 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
446 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
447 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
448 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
449 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
450 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
452 if ($line =~ /^\s*(\.\w+)/) {
455 undef $self->{value};
456 $line = substr($line,@+[0]); $line =~ s/^\s+//;
459 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
461 $line=sprintf "0x%x,0x90000000",$opcode{$1};
465 /\.global|\.globl|\.extern/
466 && do { $globals{$line} = $prefix . $line;
467 $line = $globals{$line} if ($prefix);
470 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
471 if ($type eq "\@function") {
472 undef $current_function;
473 $current_function->{name} = $sym;
474 $current_function->{abi} = "svr4";
475 $current_function->{narg} = $narg;
476 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
477 } elsif ($type eq "\@abi-omnipotent") {
478 undef $current_function;
479 $current_function->{name} = $sym;
480 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
482 $line =~ s/\@abi\-omnipotent/\@function/;
483 $line =~ s/\@function.*/\@function/;
486 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
488 $line = join(",",unpack("C*",$1),0);
492 /\.rva|\.long|\.quad/
493 && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
494 $line =~ s/\.L/$decor/g;
500 $self->{value} = $dir . "\t" . $line;
502 if ($dir =~ /\.extern/) {
503 $self->{value} = ""; # swallow extern
504 } elsif (!$elf && $dir =~ /\.type/) {
506 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
507 (defined($globals{$1})?".scl 2;":".scl 3;") .
508 "\t.type 32;\t.endef"
509 if ($win64 && $line =~ /([^,]+),\@function/);
510 } elsif (!$elf && $dir =~ /\.size/) {
512 if (defined($current_function)) {
513 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
514 if ($win64 && $current_function->{abi} eq "svr4");
515 undef $current_function;
517 } elsif (!$elf && $dir =~ /\.align/) {
518 $self->{value} = ".p2align\t" . (log($line)/log(2));
519 } elsif ($dir eq ".section") {
520 $current_segment=$line;
521 if (!$elf && $current_segment eq ".init") {
522 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
523 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
525 } elsif ($dir =~ /\.(text|data)/) {
526 $current_segment=".$1";
527 } elsif ($dir =~ /\.hidden/) {
528 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$line"; }
529 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
530 } elsif ($dir =~ /\.comm/) {
531 $self->{value} = "$dir\t$prefix$line";
532 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
538 # non-gas case or nasm/masm
540 /\.text/ && do { my $v=undef;
542 $v="section .text code align=64\n";
544 $v="$current_segment\tENDS\n" if ($current_segment);
545 $current_segment = ".text\$";
546 $v.="$current_segment\tSEGMENT ";
547 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
553 /\.data/ && do { my $v=undef;
555 $v="section .data data align=8\n";
557 $v="$current_segment\tENDS\n" if ($current_segment);
558 $current_segment = "_DATA";
559 $v.="$current_segment\tSEGMENT";
564 /\.section/ && do { my $v=undef;
565 $line =~ s/([^,]*).*/$1/;
566 $line = ".CRT\$XCU" if ($line eq ".init");
569 if ($line=~/\.([px])data/) {
571 $v.=$1 eq "p"? 4 : 8;
572 } elsif ($line=~/\.CRT\$/i) {
573 $v.=" rdata align=8";
576 $v="$current_segment\tENDS\n" if ($current_segment);
577 $v.="$line\tSEGMENT";
578 if ($line=~/\.([px])data/) {
580 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
581 } elsif ($line=~/\.CRT\$/i) {
583 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
586 $current_segment = $line;
590 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
591 $self->{value} .= ":NEAR" if ($masm);
595 && do { $self->{value} = $masm?"PUBLIC":"global";
596 $self->{value} .= "\t".$line;
599 /\.size/ && do { if (defined($current_function)) {
600 undef $self->{value};
601 if ($current_function->{abi} eq "svr4") {
602 $self->{value}="${decor}SEH_end_$current_function->{name}:";
603 $self->{value}.=":\n" if($masm);
605 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
606 undef $current_function;
610 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
611 /\.(value|long|rva|quad)/
612 && do { my $sz = substr($1,0,1);
613 my @arr = split(/,\s*/,$line);
614 my $last = pop(@arr);
615 my $conv = sub { my $var=shift;
616 $var=~s/^(0b[0-1]+)/oct($1)/eig;
617 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
618 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
619 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
623 $sz =~ tr/bvlrq/BWDDQ/;
624 $self->{value} = "\tD$sz\t";
625 for (@arr) { $self->{value} .= &$conv($_).","; }
626 $self->{value} .= &$conv($last);
629 /\.byte/ && do { my @str=split(/,\s*/,$line);
630 map(s/(0b[0-1]+)/oct($1)/eig,@str);
631 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
633 $self->{value}.="DB\t"
634 .join(",",@str[0..15])."\n";
635 foreach (0..15) { shift @str; }
637 $self->{value}.="DB\t"
638 .join(",",@str) if (@str);
641 /\.comm/ && do { my @str=split(/,\s*/,$line);
644 $v.="common $prefix@str[0] @str[1]";
646 $v="$current_segment\tENDS\n" if ($current_segment);
647 $current_segment = "_DATA";
648 $v.="$current_segment\tSEGMENT\n";
649 $v.="COMM @str[0]:DWORD:".@str[1]/4;
668 my ($dst,$src,$rex)=@_;
670 $rex|=0x04 if($dst>=8);
671 $rex|=0x01 if($src>=8);
672 push @opcode,($rex|0x40) if ($rex);
675 # older gas and ml64 don't handle SSE>2 instructions
676 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
677 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
679 my $movq = sub { # elderly gas can't handle inter-register movq
682 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
683 my ($src,$dst)=($1,$2);
684 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
685 rex(\@opcode,$src,$dst,0x8);
686 push @opcode,0x0f,0x7e;
687 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
689 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
690 my ($src,$dst)=($2,$1);
691 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
692 rex(\@opcode,$src,$dst,0x8);
693 push @opcode,0x0f,0x6e;
694 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
702 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
707 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
708 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
709 rex(\@opcode,$src,$dst);
710 push @opcode,0x0f,0x3a,0x16;
711 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
720 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
725 if ($src =~ /%r([0-9]+)/) { $src = $1; }
726 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
727 rex(\@opcode,$dst,$src);
728 push @opcode,0x0f,0x3a,0x22;
729 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
738 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
741 push @opcode,0x0f,0x38,0x00;
742 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
750 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
753 push @opcode,0x0f,0x3a,0x0f;
754 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
762 my $pclmulqdq = sub {
763 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
766 push @opcode,0x0f,0x3a,0x44;
767 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
769 push @opcode,$c=~/^0/?oct($c):$c;
777 if (shift =~ /%[er](\w+)/) {
780 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
781 rex(\@opcode,0,$1,8);
782 push @opcode,0x0f,0xc7,0xf0|($dst&7);
790 if (shift =~ /%[er](\w+)/) {
793 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
794 rex(\@opcode,0,$1,8);
795 push @opcode,0x0f,0xc7,0xf8|($dst&7);
804 my ($dst,$src1,$src2,$rxb)=@_;
807 $rxb&=~(0x04<<5) if($dst>=8);
808 $rxb&=~(0x01<<5) if($src1>=8);
809 $rxb&=~(0x02<<5) if($src2>=8);
814 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
816 rxb(\@opcode,$3,$2,-1,0x08);
817 push @opcode,0x78,0xc2;
818 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
820 push @opcode,$c=~/^0/?oct($c):$c;
828 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
830 rxb(\@opcode,$3,$2,-1,0x08);
831 push @opcode,0x78,0xc3;
832 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
834 push @opcode,$c=~/^0/?oct($c):$c;
853 while(defined($line=<>)) {
855 $line =~ s|\R$||; # Better chomp
857 $line =~ s|[#!].*$||; # get rid of asm-style comments...
858 $line =~ s|/\*.*\*/||; # ... and C-style comments...
859 $line =~ s|^\s+||; # ... and skip white spaces in beginning
860 $line =~ s|\s+$||; # ... and at the end
866 if ($label=label->re(\$line)) { print $label->out(); }
868 if (directive->re(\$line)) {
869 printf "%s",directive->out();
870 } elsif ($opcode=opcode->re(\$line)) {
871 my $asm = eval("\$".$opcode->mnemonic());
874 if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
875 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
879 ARGUMENT: while (1) {
882 if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
883 elsif ($arg=const->re(\$line)) { }
884 elsif ($arg=ea->re(\$line)) { }
885 elsif ($arg=expr->re(\$line)) { }
886 else { last ARGUMENT; }
890 last ARGUMENT if ($line !~ /^,/);
897 my $sz=opcode->size();
900 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
901 @args = map($_->out($sz),@args);
902 printf "\t%s\t%s",$insn,join(",",@args);
904 $insn = $opcode->out();
907 # $insn.=$sz compensates for movq, pinsrw, ...
908 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
909 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
910 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
911 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
913 @args = reverse(@args);
914 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
915 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
918 printf "\t%s",$opcode->out();
925 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
926 print "END\n" if ($masm);
930 \f#################################################
931 # Cross-reference x86_64 ABI "card"
951 # (*) volatile register
952 # (-) preserved by callee
953 # (#) Nth argument, volatile
955 # In Unix terms top of stack is argument transfer area for arguments
956 # which could not be accommodated in registers. Or in other words 7th
957 # [integer] argument resides at 8(%rsp) upon function entry point.
958 # 128 bytes above %rsp constitute a "red zone" which is not touched
959 # by signal handlers and can be used as temporal storage without
960 # allocating a frame.
962 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
963 # which belongs to/can be overwritten by callee. N is the number of
964 # arguments passed to callee, *but* not less than 4! This means that
965 # upon function entry point 5th argument resides at 40(%rsp), as well
966 # as that 32 bytes from 8(%rsp) can always be used as temporal
967 # storage [without allocating a frame]. One can actually argue that
968 # one can assume a "red zone" above stack pointer under Win64 as well.
969 # Point is that at apparently no occasion Windows kernel would alter
970 # the area above user stack pointer in true asynchronous manner...
972 # All the above means that if assembler programmer adheres to Unix
973 # register and stack layout, but disregards the "red zone" existense,
974 # it's possible to use following prologue and epilogue to "gear" from
975 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
977 # omnipotent_function:
981 # movq %rcx,%rdi ; if 1st argument is actually present
982 # movq %rdx,%rsi ; if 2nd argument is actually ...
983 # movq %r8,%rdx ; if 3rd argument is ...
984 # movq %r9,%rcx ; if 4th argument ...
985 # movq 40(%rsp),%r8 ; if 5th ...
986 # movq 48(%rsp),%r9 ; if 6th ...
995 \f#################################################
996 # Win64 SEH, Structured Exception Handling.
998 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
999 # has undesired side-effect at run-time: if an exception is raised in
1000 # assembler subroutine such as those in question (basically we're
1001 # referring to segmentation violations caused by malformed input
1002 # parameters), the application is briskly terminated without invoking
1003 # any exception handlers, most notably without generating memory dump
1004 # or any user notification whatsoever. This poses a problem. It's
1005 # possible to address it by registering custom language-specific
1006 # handler that would restore processor context to the state at
1007 # subroutine entry point and return "exception is not handled, keep
1008 # unwinding" code. Writing such handler can be a challenge... But it's
1009 # doable, though requires certain coding convention. Consider following
1012 # .type function,@function
1014 # movq %rsp,%rax # copy rsp to volatile register
1015 # pushq %r15 # save non-volatile registers
1019 # subq %rdi,%r11 # prepare [variable] stack frame
1021 # movq %rax,0(%r11) # check for exceptions
1022 # movq %r11,%rsp # allocate [variable] stack frame
1023 # movq %rax,0(%rsp) # save original rsp value
1026 # movq 0(%rsp),%rcx # pull original rsp value
1027 # movq -24(%rcx),%rbp # restore non-volatile registers
1028 # movq -16(%rcx),%rbx
1029 # movq -8(%rcx),%r15
1030 # movq %rcx,%rsp # restore original rsp
1032 # .size function,.-function
1034 # The key is that up to magic_point copy of original rsp value remains
1035 # in chosen volatile register and no non-volatile register, except for
1036 # rsp, is modified. While past magic_point rsp remains constant till
1037 # the very end of the function. In this case custom language-specific
1038 # exception handler would look like this:
1040 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1041 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1042 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1043 # if (context->Rip >= magic_point)
1044 # { rsp = ((ULONG64 **)context->Rsp)[0];
1045 # context->Rbp = rsp[-3];
1046 # context->Rbx = rsp[-2];
1047 # context->R15 = rsp[-1];
1049 # context->Rsp = (ULONG64)rsp;
1050 # context->Rdi = rsp[1];
1051 # context->Rsi = rsp[2];
1053 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1054 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1055 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1056 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1057 # return ExceptionContinueSearch;
1060 # It's appropriate to implement this handler in assembler, directly in
1061 # function's module. In order to do that one has to know members'
1062 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1063 # values. Here they are:
1083 # sizeof(CONTEXT) 1232
1084 # DISPATCHER_CONTEXT.ControlPc 0
1085 # DISPATCHER_CONTEXT.ImageBase 8
1086 # DISPATCHER_CONTEXT.FunctionEntry 16
1087 # DISPATCHER_CONTEXT.EstablisherFrame 24
1088 # DISPATCHER_CONTEXT.TargetIp 32
1089 # DISPATCHER_CONTEXT.ContextRecord 40
1090 # DISPATCHER_CONTEXT.LanguageHandler 48
1091 # DISPATCHER_CONTEXT.HandlerData 56
1092 # UNW_FLAG_NHANDLER 0
1093 # ExceptionContinueSearch 1
1095 # In order to tie the handler to the function one has to compose
1096 # couple of structures: one for .xdata segment and one for .pdata.
1098 # UNWIND_INFO structure for .xdata segment would be
1100 # function_unwind_info:
1104 # This structure designates exception handler for a function with
1105 # zero-length prologue, no stack frame or frame register.
1107 # To facilitate composing of .pdata structures, auto-generated "gear"
1108 # prologue copies rsp value to rax and denotes next instruction with
1109 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1110 # styling rule mentioned in the beginning. Position of this label is
1111 # chosen in such manner that possible exceptions raised in the "gear"
1112 # prologue would be accounted to caller and unwound from latter's frame.
1113 # End of function is marked with respective .LSEH_end_{function_name}
1114 # label. To summarize, .pdata segment would contain
1116 # .rva .LSEH_begin_function
1117 # .rva .LSEH_end_function
1118 # .rva function_unwind_info
1120 # Reference to function_unwind_info from .xdata segment is the anchor.
1121 # In case you wonder why references are 32-bit .rvas and not 64-bit
1122 # .quads. References put into these two segments are required to be
1123 # *relative* to the base address of the current binary module, a.k.a.
1124 # image base. No Win64 module, be it .exe or .dll, can be larger than
1125 # 2GB and thus such relative references can be and are accommodated in
1128 # Having reviewed the example function code, one can argue that "movq
1129 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1130 # rax would contain an undefined value. If this "offends" you, use
1131 # another register and refrain from modifying rax till magic_point is
1132 # reached, i.e. as if it was a non-volatile register. If more registers
1133 # are required prior [variable] frame setup is completed, note that
1134 # nobody says that you can have only one "magic point." You can
1135 # "liberate" non-volatile registers by denoting last stack off-load
1136 # instruction and reflecting it in finer grade unwind logic in handler.
1137 # After all, isn't it why it's called *language-specific* handler...
1139 # Attentive reader can notice that exceptions would be mishandled in
1140 # auto-generated "gear" epilogue. Well, exception effectively can't
1141 # occur there, because if memory area used by it was subject to
1142 # segmentation violation, then it would be raised upon call to the
1143 # function (and as already mentioned be accounted to caller, which is
1144 # not a problem). If you're still not comfortable, then define tail
1145 # "magic point" just prior ret instruction and have handler treat it...
1147 # (*) Note that we're talking about run-time, not debug-time. Lack of
1148 # unwind information makes debugging hard on both Windows and
1149 # Unix. "Unlike" referes to the fact that on Unix signal handler
1150 # will always be invoked, core dumped and appropriate exit code
1151 # returned to parent (for user notification).