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} =~ /movq/ && $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 =~ /\.global|\.globl|\.extern/) {
525 if ($flavour eq "macosx") {
526 $self->{value} .= "\n.private_extern $line";
528 $self->{value} .= "\n.hidden $line";
530 } elsif ($dir =~ /\.hidden/) {
531 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$line"; }
532 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
533 } elsif ($dir =~ /\.comm/) {
534 $self->{value} = "$dir\t$prefix$line";
535 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
541 # non-gas case or nasm/masm
543 /\.text/ && do { my $v=undef;
545 $v="section .text code align=64\n";
547 $v="$current_segment\tENDS\n" if ($current_segment);
548 $current_segment = ".text\$";
549 $v.="$current_segment\tSEGMENT ";
550 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
556 /\.data/ && do { my $v=undef;
558 $v="section .data data align=8\n";
560 $v="$current_segment\tENDS\n" if ($current_segment);
561 $current_segment = "_DATA";
562 $v.="$current_segment\tSEGMENT";
567 /\.section/ && do { my $v=undef;
568 $line =~ s/([^,]*).*/$1/;
569 $line = ".CRT\$XCU" if ($line eq ".init");
572 if ($line=~/\.([px])data/) {
574 $v.=$1 eq "p"? 4 : 8;
575 } elsif ($line=~/\.CRT\$/i) {
576 $v.=" rdata align=8";
579 $v="$current_segment\tENDS\n" if ($current_segment);
580 $v.="$line\tSEGMENT";
581 if ($line=~/\.([px])data/) {
583 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
584 } elsif ($line=~/\.CRT\$/i) {
586 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
589 $current_segment = $line;
593 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
594 $self->{value} .= ":NEAR" if ($masm);
598 && do { $self->{value} = $masm?"PUBLIC":"global";
599 $self->{value} .= "\t".$line;
602 /\.size/ && do { if (defined($current_function)) {
603 undef $self->{value};
604 if ($current_function->{abi} eq "svr4") {
605 $self->{value}="${decor}SEH_end_$current_function->{name}:";
606 $self->{value}.=":\n" if($masm);
608 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
609 undef $current_function;
613 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
614 /\.(value|long|rva|quad)/
615 && do { my $sz = substr($1,0,1);
616 my @arr = split(/,\s*/,$line);
617 my $last = pop(@arr);
618 my $conv = sub { my $var=shift;
619 $var=~s/^(0b[0-1]+)/oct($1)/eig;
620 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
621 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
622 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
626 $sz =~ tr/bvlrq/BWDDQ/;
627 $self->{value} = "\tD$sz\t";
628 for (@arr) { $self->{value} .= &$conv($_).","; }
629 $self->{value} .= &$conv($last);
632 /\.byte/ && do { my @str=split(/,\s*/,$line);
633 map(s/(0b[0-1]+)/oct($1)/eig,@str);
634 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
636 $self->{value}.="DB\t"
637 .join(",",@str[0..15])."\n";
638 foreach (0..15) { shift @str; }
640 $self->{value}.="DB\t"
641 .join(",",@str) if (@str);
644 /\.comm/ && do { my @str=split(/,\s*/,$line);
647 $v.="common $prefix@str[0] @str[1]";
649 $v="$current_segment\tENDS\n" if ($current_segment);
650 $current_segment = "_DATA";
651 $v.="$current_segment\tSEGMENT\n";
652 $v.="COMM @str[0]:DWORD:".@str[1]/4;
671 my ($dst,$src,$rex)=@_;
673 $rex|=0x04 if($dst>=8);
674 $rex|=0x01 if($src>=8);
675 push @opcode,($rex|0x40) if ($rex);
678 # older gas and ml64 don't handle SSE>2 instructions
679 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
680 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
682 my $movq = sub { # elderly gas can't handle inter-register movq
685 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
686 my ($src,$dst)=($1,$2);
687 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
688 rex(\@opcode,$src,$dst,0x8);
689 push @opcode,0x0f,0x7e;
690 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
692 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
693 my ($src,$dst)=($2,$1);
694 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
695 rex(\@opcode,$src,$dst,0x8);
696 push @opcode,0x0f,0x6e;
697 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
705 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
710 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
711 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
712 rex(\@opcode,$src,$dst);
713 push @opcode,0x0f,0x3a,0x16;
714 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
723 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
728 if ($src =~ /%r([0-9]+)/) { $src = $1; }
729 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
730 rex(\@opcode,$dst,$src);
731 push @opcode,0x0f,0x3a,0x22;
732 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
741 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
744 push @opcode,0x0f,0x38,0x00;
745 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
753 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
756 push @opcode,0x0f,0x3a,0x0f;
757 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
765 my $pclmulqdq = sub {
766 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
769 push @opcode,0x0f,0x3a,0x44;
770 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
772 push @opcode,$c=~/^0/?oct($c):$c;
780 if (shift =~ /%[er](\w+)/) {
783 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
784 rex(\@opcode,0,$1,8);
785 push @opcode,0x0f,0xc7,0xf0|($dst&7);
793 if (shift =~ /%[er](\w+)/) {
796 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
797 rex(\@opcode,0,$1,8);
798 push @opcode,0x0f,0xc7,0xf8|($dst&7);
807 my ($dst,$src1,$src2,$rxb)=@_;
810 $rxb&=~(0x04<<5) if($dst>=8);
811 $rxb&=~(0x01<<5) if($src1>=8);
812 $rxb&=~(0x02<<5) if($src2>=8);
817 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
819 rxb(\@opcode,$3,$2,-1,0x08);
820 push @opcode,0x78,0xc2;
821 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
823 push @opcode,$c=~/^0/?oct($c):$c;
831 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
833 rxb(\@opcode,$3,$2,-1,0x08);
834 push @opcode,0x78,0xc3;
835 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
837 push @opcode,$c=~/^0/?oct($c):$c;
857 print STDOUT "#if defined(__x86_64__)\n" if ($gas);
863 $line =~ s|[#!].*$||; # get rid of asm-style comments...
864 $line =~ s|/\*.*\*/||; # ... and C-style comments...
865 $line =~ s|^\s+||; # ... and skip white spaces in beginning
866 $line =~ s|\s+$||; # ... and at the end
872 if ($label=label->re(\$line)) { print $label->out(); }
874 if (directive->re(\$line)) {
875 printf "%s",directive->out();
876 } elsif ($opcode=opcode->re(\$line)) {
877 my $asm = eval("\$".$opcode->mnemonic());
880 if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
881 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
885 ARGUMENT: while (1) {
888 if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
889 elsif ($arg=const->re(\$line)) { }
890 elsif ($arg=ea->re(\$line)) { }
891 elsif ($arg=expr->re(\$line)) { }
892 else { last ARGUMENT; }
896 last ARGUMENT if ($line !~ /^,/);
903 my $sz=opcode->size();
906 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
907 @args = map($_->out($sz),@args);
908 printf "\t%s\t%s",$insn,join(",",@args);
910 $insn = $opcode->out();
913 # $insn.=$sz compensates for movq, pinsrw, ...
914 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
915 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
916 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
917 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
919 @args = reverse(@args);
920 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
922 if ($insn eq "movq" && $#args == 1 && $args[0]->out($sz) eq "xmm0" && $args[1]->out($sz) eq "rax") {
923 # I have no clue why MASM can't parse this instruction.
924 printf "DB 66h, 48h, 0fh, 6eh, 0c0h";
926 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
930 printf "\t%s",$opcode->out();
937 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
938 print "END\n" if ($masm);
939 print "#endif\n" if ($gas);
944 \f#################################################
945 # Cross-reference x86_64 ABI "card"
965 # (*) volatile register
966 # (-) preserved by callee
967 # (#) Nth argument, volatile
969 # In Unix terms top of stack is argument transfer area for arguments
970 # which could not be accomodated in registers. Or in other words 7th
971 # [integer] argument resides at 8(%rsp) upon function entry point.
972 # 128 bytes above %rsp constitute a "red zone" which is not touched
973 # by signal handlers and can be used as temporal storage without
974 # allocating a frame.
976 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
977 # which belongs to/can be overwritten by callee. N is the number of
978 # arguments passed to callee, *but* not less than 4! This means that
979 # upon function entry point 5th argument resides at 40(%rsp), as well
980 # as that 32 bytes from 8(%rsp) can always be used as temporal
981 # storage [without allocating a frame]. One can actually argue that
982 # one can assume a "red zone" above stack pointer under Win64 as well.
983 # Point is that at apparently no occasion Windows kernel would alter
984 # the area above user stack pointer in true asynchronous manner...
986 # All the above means that if assembler programmer adheres to Unix
987 # register and stack layout, but disregards the "red zone" existense,
988 # it's possible to use following prologue and epilogue to "gear" from
989 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
991 # omnipotent_function:
995 # movq %rcx,%rdi ; if 1st argument is actually present
996 # movq %rdx,%rsi ; if 2nd argument is actually ...
997 # movq %r8,%rdx ; if 3rd argument is ...
998 # movq %r9,%rcx ; if 4th argument ...
999 # movq 40(%rsp),%r8 ; if 5th ...
1000 # movq 48(%rsp),%r9 ; if 6th ...
1005 # movq 16(%rsp),%rsi
1009 \f#################################################
1010 # Win64 SEH, Structured Exception Handling.
1012 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1013 # has undesired side-effect at run-time: if an exception is raised in
1014 # assembler subroutine such as those in question (basically we're
1015 # referring to segmentation violations caused by malformed input
1016 # parameters), the application is briskly terminated without invoking
1017 # any exception handlers, most notably without generating memory dump
1018 # or any user notification whatsoever. This poses a problem. It's
1019 # possible to address it by registering custom language-specific
1020 # handler that would restore processor context to the state at
1021 # subroutine entry point and return "exception is not handled, keep
1022 # unwinding" code. Writing such handler can be a challenge... But it's
1023 # doable, though requires certain coding convention. Consider following
1026 # .type function,@function
1028 # movq %rsp,%rax # copy rsp to volatile register
1029 # pushq %r15 # save non-volatile registers
1033 # subq %rdi,%r11 # prepare [variable] stack frame
1035 # movq %rax,0(%r11) # check for exceptions
1036 # movq %r11,%rsp # allocate [variable] stack frame
1037 # movq %rax,0(%rsp) # save original rsp value
1040 # movq 0(%rsp),%rcx # pull original rsp value
1041 # movq -24(%rcx),%rbp # restore non-volatile registers
1042 # movq -16(%rcx),%rbx
1043 # movq -8(%rcx),%r15
1044 # movq %rcx,%rsp # restore original rsp
1046 # .size function,.-function
1048 # The key is that up to magic_point copy of original rsp value remains
1049 # in chosen volatile register and no non-volatile register, except for
1050 # rsp, is modified. While past magic_point rsp remains constant till
1051 # the very end of the function. In this case custom language-specific
1052 # exception handler would look like this:
1054 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1055 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1056 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1057 # if (context->Rip >= magic_point)
1058 # { rsp = ((ULONG64 **)context->Rsp)[0];
1059 # context->Rbp = rsp[-3];
1060 # context->Rbx = rsp[-2];
1061 # context->R15 = rsp[-1];
1063 # context->Rsp = (ULONG64)rsp;
1064 # context->Rdi = rsp[1];
1065 # context->Rsi = rsp[2];
1067 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1068 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1069 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1070 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1071 # return ExceptionContinueSearch;
1074 # It's appropriate to implement this handler in assembler, directly in
1075 # function's module. In order to do that one has to know members'
1076 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1077 # values. Here they are:
1097 # sizeof(CONTEXT) 1232
1098 # DISPATCHER_CONTEXT.ControlPc 0
1099 # DISPATCHER_CONTEXT.ImageBase 8
1100 # DISPATCHER_CONTEXT.FunctionEntry 16
1101 # DISPATCHER_CONTEXT.EstablisherFrame 24
1102 # DISPATCHER_CONTEXT.TargetIp 32
1103 # DISPATCHER_CONTEXT.ContextRecord 40
1104 # DISPATCHER_CONTEXT.LanguageHandler 48
1105 # DISPATCHER_CONTEXT.HandlerData 56
1106 # UNW_FLAG_NHANDLER 0
1107 # ExceptionContinueSearch 1
1109 # In order to tie the handler to the function one has to compose
1110 # couple of structures: one for .xdata segment and one for .pdata.
1112 # UNWIND_INFO structure for .xdata segment would be
1114 # function_unwind_info:
1118 # This structure designates exception handler for a function with
1119 # zero-length prologue, no stack frame or frame register.
1121 # To facilitate composing of .pdata structures, auto-generated "gear"
1122 # prologue copies rsp value to rax and denotes next instruction with
1123 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1124 # styling rule mentioned in the beginning. Position of this label is
1125 # chosen in such manner that possible exceptions raised in the "gear"
1126 # prologue would be accounted to caller and unwound from latter's frame.
1127 # End of function is marked with respective .LSEH_end_{function_name}
1128 # label. To summarize, .pdata segment would contain
1130 # .rva .LSEH_begin_function
1131 # .rva .LSEH_end_function
1132 # .rva function_unwind_info
1134 # Reference to functon_unwind_info from .xdata segment is the anchor.
1135 # In case you wonder why references are 32-bit .rvas and not 64-bit
1136 # .quads. References put into these two segments are required to be
1137 # *relative* to the base address of the current binary module, a.k.a.
1138 # image base. No Win64 module, be it .exe or .dll, can be larger than
1139 # 2GB and thus such relative references can be and are accommodated in
1142 # Having reviewed the example function code, one can argue that "movq
1143 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1144 # rax would contain an undefined value. If this "offends" you, use
1145 # another register and refrain from modifying rax till magic_point is
1146 # reached, i.e. as if it was a non-volatile register. If more registers
1147 # are required prior [variable] frame setup is completed, note that
1148 # nobody says that you can have only one "magic point." You can
1149 # "liberate" non-volatile registers by denoting last stack off-load
1150 # instruction and reflecting it in finer grade unwind logic in handler.
1151 # After all, isn't it why it's called *language-specific* handler...
1153 # Attentive reader can notice that exceptions would be mishandled in
1154 # auto-generated "gear" epilogue. Well, exception effectively can't
1155 # occur there, because if memory area used by it was subject to
1156 # segmentation violation, then it would be raised upon call to the
1157 # function (and as already mentioned be accounted to caller, which is
1158 # not a problem). If you're still not comfortable, then define tail
1159 # "magic point" just prior ret instruction and have handler treat it...
1161 # (*) Note that we're talking about run-time, not debug-time. Lack of
1162 # unwind information makes debugging hard on both Windows and
1163 # Unix. "Unlike" referes to the fact that on Unix signal handler
1164 # will always be invoked, core dumped and appropriate exit code
1165 # returned to parent (for user notification).