2 # Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
4 # Licensed under the OpenSSL license (the "License"). You may not use
5 # this file except in compliance with the License. You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
10 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
12 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
13 # format is way easier to parse. Because it's simpler to "gear" from
14 # Unix ABI to Windows one [see cross-reference "card" at the end of
15 # file]. Because Linux targets were available first...
17 # In addition the script also "distills" code suitable for GNU
18 # assembler, so that it can be compiled with more rigid assemblers,
19 # such as Solaris /usr/ccs/bin/as.
21 # This translator is not designed to convert *arbitrary* assembler
22 # code from AT&T format to MASM one. It's designed to convert just
23 # enough to provide for dual-ABI OpenSSL modules development...
24 # There *are* limitations and you might have to modify your assembler
25 # code or this script to achieve the desired result...
27 # Currently recognized limitations:
29 # - can't use multiple ops per line;
31 # Dual-ABI styling rules.
33 # 1. Adhere to Unix register and stack layout [see cross-reference
34 # ABI "card" at the end for explanation].
35 # 2. Forget about "red zone," stick to more traditional blended
36 # stack frame allocation. If volatile storage is actually required
37 # that is. If not, just leave the stack as is.
38 # 3. Functions tagged with ".type name,@function" get crafted with
39 # unified Win64 prologue and epilogue automatically. If you want
40 # to take care of ABI differences yourself, tag functions as
41 # ".type name,@abi-omnipotent" instead.
42 # 4. To optimize the Win64 prologue you can specify number of input
43 # arguments as ".type name,@function,N." Keep in mind that if N is
44 # larger than 6, then you *have to* write "abi-omnipotent" code,
45 # because >6 cases can't be addressed with unified prologue.
46 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
47 # (sorry about latter).
48 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
49 # required to identify the spots, where to inject Win64 epilogue!
50 # But on the pros, it's then prefixed with rep automatically:-)
51 # 7. Stick to explicit ip-relative addressing. If you have to use
52 # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
53 # Both are recognized and translated to proper Win64 addressing
54 # modes. To support legacy code a synthetic directive, .picmeup,
55 # is implemented. It puts address of the *next* instruction into
56 # target register, e.g.:
59 # lea .Label-.(%rax),%rax
61 # 8. In order to provide for structured exception handling unified
62 # Win64 prologue copies %rsp value to %rax. For further details
63 # see SEH paragraph at the end.
64 # 9. .init segment is allowed to contain calls to functions only.
65 # a. If function accepts more than 4 arguments *and* >4th argument
66 # is declared as non 64-bit value, do clear its upper part.
73 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
75 open STDOUT,">$output" || die "can't open $output: $!"
76 if (defined($output));
78 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
79 my $elf=1; $elf=0 if (!$gas);
84 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
91 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
92 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
93 $prefix =~ s|\R$||; # Better chomp
95 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
96 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
97 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
99 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
100 { $nasm = $1 + $2*0.01; $PTR=""; }
101 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
102 { $masm = $1 + $2*2**-16 + $4*2**-32; }
103 die "no assembler found on %PATH" if (!($nasm || $masm));
110 my $current_function;
113 { package opcode; # pick up opcodes
115 my ($class, $line) = @_;
119 if ($$line =~ /^([a-z][a-z0-9]*)/i) {
123 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
126 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
129 } elsif ($self->{op} =~ /call|jmp/) {
131 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
133 } elsif ($self->{op} =~ /^v/) { # VEX
135 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) {
137 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
145 my ($self, $sz) = @_;
146 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
152 if ($self->{op} eq "movz") { # movz is pain...
153 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
154 } elsif ($self->{op} =~ /^set/) {
156 } elsif ($self->{op} eq "ret") {
158 if ($win64 && $current_function->{abi} eq "svr4") {
159 $epilogue = "movq 8(%rsp),%rdi\n\t" .
160 "movq 16(%rsp),%rsi\n\t";
162 $epilogue . ".byte 0xf3,0xc3";
163 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
164 ".p2align\t3\n\t.quad";
166 "$self->{op}$self->{sz}";
169 $self->{op} =~ s/^movz/movzx/;
170 if ($self->{op} eq "ret") {
172 if ($win64 && $current_function->{abi} eq "svr4") {
173 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t".
174 "mov rsi,QWORD$PTR\[16+rsp\]\n\t";
176 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
177 } elsif ($self->{op} =~ /^(pop|push)f/) {
178 $self->{op} .= $self->{sz};
179 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
180 $self->{op} = "\tDQ";
186 my ($self, $op) = @_;
187 $self->{op}=$op if (defined($op));
191 { package const; # pick up constants, which start with $
193 my ($class, $line) = @_;
197 if ($$line =~ /^\$([^,]+)/) {
201 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
208 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
210 # Solaris /usr/ccs/bin/as can't handle multiplications
212 my $value = $self->{value};
213 no warnings; # oct might complain about overflow, ignore here...
214 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
215 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
216 $self->{value} = $value;
218 sprintf "\$%s",$self->{value};
220 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
221 sprintf "%s",$self->{value};
225 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
227 my ($class, $line, $opcode) = @_;
231 # optional * ----vvv--- appears in indirect jmp/call
232 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
234 $self->{asterisk} = $1;
236 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
237 $self->{scale} = 1 if (!defined($self->{scale}));
239 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
241 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
242 die if ($opcode->mnemonic() ne "mov");
243 $opcode->mnemonic("lea");
245 $self->{base} =~ s/^%//;
246 $self->{index} =~ s/^%// if (defined($self->{index}));
247 $self->{opcode} = $opcode;
253 my ($self, $sz) = @_;
255 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
256 $self->{label} =~ s/\.L/$decor/g;
258 # Silently convert all EAs to 64-bit. This is required for
259 # elder GNU assembler and results in more compact code,
260 # *but* most importantly AES module depends on this feature!
261 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
262 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
264 # Solaris /usr/ccs/bin/as can't handle multiplications
265 # in $self->{label}...
267 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
268 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
270 # Some assemblers insist on signed presentation of 32-bit
271 # offsets, but sign extension is a tricky business in perl...
273 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
275 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
278 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
279 $self->{base} =~ /(rbp|r13)/) {
280 $self->{base} = $self->{index}; $self->{index} = $1;
284 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
286 if (defined($self->{index})) {
287 sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
289 $self->{base}?"%$self->{base}":"",
290 $self->{index},$self->{scale};
292 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
295 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
296 l=>"DWORD$PTR", d=>"DWORD$PTR",
297 q=>"QWORD$PTR", o=>"OWORD$PTR",
298 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
300 $self->{label} =~ s/\./\$/g;
301 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
302 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
304 my $mnemonic = $self->{opcode}->mnemonic();
305 ($self->{asterisk}) && ($sz="q") ||
306 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
307 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
308 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
309 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
311 if (defined($self->{index})) {
312 sprintf "%s[%s%s*%d%s]",$szmap{$sz},
313 $self->{label}?"$self->{label}+":"",
314 $self->{index},$self->{scale},
315 $self->{base}?"+$self->{base}":"";
316 } elsif ($self->{base} eq "rip") {
317 sprintf "%s[%s]",$szmap{$sz},$self->{label};
319 sprintf "%s[%s%s]",$szmap{$sz},
320 $self->{label}?"$self->{label}+":"",
326 { package register; # pick up registers, which start with %.
328 my ($class, $line, $opcode) = @_;
332 # optional * ----vvv--- appears in indirect jmp/call
333 if ($$line =~ /^(\*?)%(\w+)/) {
335 $self->{asterisk} = $1;
337 $opcode->size($self->size());
339 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
347 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
348 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
349 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
350 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
351 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
352 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
353 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
354 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
360 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
361 else { $self->{value}; }
364 { package label; # pick up labels, which end with :
366 my ($class, $line) = @_;
370 if ($$line =~ /(^[\.\w]+)\:/) {
374 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
376 $self->{value} =~ s/^\.L/$decor/;
384 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
386 $current_function->{name} eq $self->{value} &&
387 $current_function->{abi} eq "svr4") {
389 $func .= " movq %rdi,8(%rsp)\n";
390 $func .= " movq %rsi,16(%rsp)\n";
391 $func .= " movq %rsp,%rax\n";
392 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
393 my $narg = $current_function->{narg};
394 $narg=6 if (!defined($narg));
395 $func .= " movq %rcx,%rdi\n" if ($narg>0);
396 $func .= " movq %rdx,%rsi\n" if ($narg>1);
397 $func .= " movq %r8,%rdx\n" if ($narg>2);
398 $func .= " movq %r9,%rcx\n" if ($narg>3);
399 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
400 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
403 } elsif ($self->{value} ne "$current_function->{name}") {
404 # Make all labels in masm global.
405 $self->{value} .= ":" if ($masm);
406 $self->{value} . ":";
407 } elsif ($win64 && $current_function->{abi} eq "svr4") {
408 my $func = "$current_function->{name}" .
409 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
411 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
412 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
413 $func .= " mov rax,rsp\n";
414 $func .= "${decor}SEH_begin_$current_function->{name}:";
415 $func .= ":" if ($masm);
417 my $narg = $current_function->{narg};
418 $narg=6 if (!defined($narg));
419 $func .= " mov rdi,rcx\n" if ($narg>0);
420 $func .= " mov rsi,rdx\n" if ($narg>1);
421 $func .= " mov rdx,r8\n" if ($narg>2);
422 $func .= " mov rcx,r9\n" if ($narg>3);
423 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
424 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
427 "$current_function->{name}".
428 ($nasm ? ":" : "\tPROC $current_function->{scope}");
432 { package expr; # pick up expressions
434 my ($class, $line, $opcode) = @_;
438 if ($$line =~ /(^[^,]+)/) {
442 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
444 $self->{value} =~ s/\@PLT// if (!$elf);
445 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
446 $self->{value} =~ s/\.L/$decor/g;
447 $self->{opcode} = $opcode;
453 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
454 "NEAR ".$self->{value};
460 { package directive; # pick up directives, which start with .
462 my ($class, $line) = @_;
466 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
467 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
468 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
469 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
470 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
471 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
472 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
473 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
474 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
476 if ($$line =~ /^\s*(\.\w+)/) {
480 undef $self->{value};
481 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
484 /\.picmeup/ && do { if ($$line =~ /(%r[\w]+)/i) {
486 $$line=sprintf "0x%x,0x90000000",$opcode{$1};
490 /\.global|\.globl|\.extern/
491 && do { $globals{$$line} = $prefix . $$line;
492 $$line = $globals{$$line} if ($prefix);
495 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
496 if ($type eq "\@function") {
497 undef $current_function;
498 $current_function->{name} = $sym;
499 $current_function->{abi} = "svr4";
500 $current_function->{narg} = $narg;
501 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
502 } elsif ($type eq "\@abi-omnipotent") {
503 undef $current_function;
504 $current_function->{name} = $sym;
505 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
507 $$line =~ s/\@abi\-omnipotent/\@function/;
508 $$line =~ s/\@function.*/\@function/;
511 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
513 $$line = join(",",unpack("C*",$1),0);
517 /\.rva|\.long|\.quad/
518 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
519 $$line =~ s/\.L/$decor/g;
525 $self->{value} = $dir . "\t" . $$line;
527 if ($dir =~ /\.extern/) {
528 $self->{value} = ""; # swallow extern
529 } elsif (!$elf && $dir =~ /\.type/) {
531 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
532 (defined($globals{$1})?".scl 2;":".scl 3;") .
533 "\t.type 32;\t.endef"
534 if ($win64 && $$line =~ /([^,]+),\@function/);
535 } elsif (!$elf && $dir =~ /\.size/) {
537 if (defined($current_function)) {
538 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
539 if ($win64 && $current_function->{abi} eq "svr4");
540 undef $current_function;
542 } elsif (!$elf && $dir =~ /\.align/) {
543 $self->{value} = ".p2align\t" . (log($$line)/log(2));
544 } elsif ($dir eq ".section") {
545 $current_segment=$$line;
546 if (!$elf && $current_segment eq ".init") {
547 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
548 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
550 } elsif ($dir =~ /\.(text|data)/) {
551 $current_segment=".$1";
552 } elsif ($dir =~ /\.hidden/) {
553 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
554 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
555 } elsif ($dir =~ /\.comm/) {
556 $self->{value} = "$dir\t$prefix$$line";
557 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
563 # non-gas case or nasm/masm
565 /\.text/ && do { my $v=undef;
567 $v="section .text code align=64\n";
569 $v="$current_segment\tENDS\n" if ($current_segment);
570 $current_segment = ".text\$";
571 $v.="$current_segment\tSEGMENT ";
572 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
578 /\.data/ && do { my $v=undef;
580 $v="section .data data align=8\n";
582 $v="$current_segment\tENDS\n" if ($current_segment);
583 $current_segment = "_DATA";
584 $v.="$current_segment\tSEGMENT";
589 /\.section/ && do { my $v=undef;
590 $$line =~ s/([^,]*).*/$1/;
591 $$line = ".CRT\$XCU" if ($$line eq ".init");
594 if ($$line=~/\.([px])data/) {
596 $v.=$1 eq "p"? 4 : 8;
597 } elsif ($$line=~/\.CRT\$/i) {
598 $v.=" rdata align=8";
601 $v="$current_segment\tENDS\n" if ($current_segment);
602 $v.="$$line\tSEGMENT";
603 if ($$line=~/\.([px])data/) {
605 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
606 } elsif ($$line=~/\.CRT\$/i) {
608 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
611 $current_segment = $$line;
615 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
616 $self->{value} .= ":NEAR" if ($masm);
620 && do { $self->{value} = $masm?"PUBLIC":"global";
621 $self->{value} .= "\t".$$line;
624 /\.size/ && do { if (defined($current_function)) {
625 undef $self->{value};
626 if ($current_function->{abi} eq "svr4") {
627 $self->{value}="${decor}SEH_end_$current_function->{name}:";
628 $self->{value}.=":\n" if($masm);
630 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
631 undef $current_function;
635 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
636 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
639 /\.(value|long|rva|quad)/
640 && do { my $sz = substr($1,0,1);
641 my @arr = split(/,\s*/,$$line);
642 my $last = pop(@arr);
643 my $conv = sub { my $var=shift;
644 $var=~s/^(0b[0-1]+)/oct($1)/eig;
645 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
646 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
647 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
651 $sz =~ tr/bvlrq/BWDDQ/;
652 $self->{value} = "\tD$sz\t";
653 for (@arr) { $self->{value} .= &$conv($_).","; }
654 $self->{value} .= &$conv($last);
657 /\.byte/ && do { my @str=split(/,\s*/,$$line);
658 map(s/(0b[0-1]+)/oct($1)/eig,@str);
659 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
661 $self->{value}.="DB\t"
662 .join(",",@str[0..15])."\n";
663 foreach (0..15) { shift @str; }
665 $self->{value}.="DB\t"
666 .join(",",@str) if (@str);
669 /\.comm/ && do { my @str=split(/,\s*/,$$line);
672 $v.="common $prefix@str[0] @str[1]";
674 $v="$current_segment\tENDS\n" if ($current_segment);
675 $current_segment = "_DATA";
676 $v.="$current_segment\tSEGMENT\n";
677 $v.="COMM @str[0]:DWORD:".@str[1]/4;
696 my ($dst,$src,$rex)=@_;
698 $rex|=0x04 if($dst>=8);
699 $rex|=0x01 if($src>=8);
700 push @$opcode,($rex|0x40) if ($rex);
703 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
704 # yet. In order not to be bothered by tracing exact assembler versions,
705 # but at the same time to provide a bare security minimum of AES-NI, we
706 # hard-code some instructions. Extensions past AES-NI on the other hand
707 # are traced by examining assembler version in individual perlasm
710 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
711 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
713 my $movq = sub { # elderly gas can't handle inter-register movq
716 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
717 my ($src,$dst)=($1,$2);
718 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
719 rex(\@opcode,$src,$dst,0x8);
720 push @opcode,0x0f,0x7e;
721 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
723 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
724 my ($src,$dst)=($2,$1);
725 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
726 rex(\@opcode,$src,$dst,0x8);
727 push @opcode,0x0f,0x6e;
728 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
736 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
741 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
742 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
743 rex(\@opcode,$src,$dst);
744 push @opcode,0x0f,0x3a,0x16;
745 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
754 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
759 if ($src =~ /%r([0-9]+)/) { $src = $1; }
760 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
761 rex(\@opcode,$dst,$src);
762 push @opcode,0x0f,0x3a,0x22;
763 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
772 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
775 push @opcode,0x0f,0x38,0x00;
776 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
784 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
787 push @opcode,0x0f,0x3a,0x0f;
788 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
796 my $pclmulqdq = sub {
797 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
800 push @opcode,0x0f,0x3a,0x44;
801 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
803 push @opcode,$c=~/^0/?oct($c):$c;
811 if (shift =~ /%[er](\w+)/) {
814 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
815 rex(\@opcode,0,$dst,8);
816 push @opcode,0x0f,0xc7,0xf0|($dst&7);
824 if (shift =~ /%[er](\w+)/) {
827 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
828 rex(\@opcode,0,$dst,8);
829 push @opcode,0x0f,0xc7,0xf8|($dst&7);
838 my ($dst,$src1,$src2,$rxb)=@_;
841 $rxb&=~(0x04<<5) if($dst>=8);
842 $rxb&=~(0x01<<5) if($src1>=8);
843 $rxb&=~(0x02<<5) if($src2>=8);
848 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
850 rxb(\@opcode,$3,$2,-1,0x08);
851 push @opcode,0x78,0xc2;
852 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
854 push @opcode,$c=~/^0/?oct($c):$c;
862 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
864 rxb(\@opcode,$3,$2,-1,0x08);
865 push @opcode,0x78,0xc3;
866 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
868 push @opcode,$c=~/^0/?oct($c):$c;
875 my $endbranch = sub {
876 (0xf3,0x0f,0x1e,0xfa);
891 while(defined(my $line=<>)) {
893 $line =~ s|\R$||; # Better chomp
895 $line =~ s|[#!].*$||; # get rid of asm-style comments...
896 $line =~ s|/\*.*\*/||; # ... and C-style comments...
897 $line =~ s|^\s+||; # ... and skip white spaces in beginning
898 $line =~ s|\s+$||; # ... and at the end
900 if (my $label=label->re(\$line)) { print $label->out(); }
902 if (my $directive=directive->re(\$line)) {
903 printf "%s",$directive->out();
904 } elsif (my $opcode=opcode->re(\$line)) {
905 my $asm = eval("\$".$opcode->mnemonic());
907 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
908 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
913 ARGUMENT: while (1) {
916 ($arg=register->re(\$line, $opcode))||
917 ($arg=const->re(\$line)) ||
918 ($arg=ea->re(\$line, $opcode)) ||
919 ($arg=expr->re(\$line, $opcode)) ||
924 last ARGUMENT if ($line !~ /^,/);
931 my $sz=$opcode->size();
934 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
935 @args = map($_->out($sz),@args);
936 printf "\t%s\t%s",$insn,join(",",@args);
938 $insn = $opcode->out();
941 # $insn.=$sz compensates for movq, pinsrw, ...
942 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
943 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
944 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
945 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
947 @args = reverse(@args);
948 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
949 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
952 printf "\t%s",$opcode->out();
959 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
960 print "END\n" if ($masm);
964 \f#################################################
965 # Cross-reference x86_64 ABI "card"
985 # (*) volatile register
986 # (-) preserved by callee
987 # (#) Nth argument, volatile
989 # In Unix terms top of stack is argument transfer area for arguments
990 # which could not be accommodated in registers. Or in other words 7th
991 # [integer] argument resides at 8(%rsp) upon function entry point.
992 # 128 bytes above %rsp constitute a "red zone" which is not touched
993 # by signal handlers and can be used as temporal storage without
994 # allocating a frame.
996 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
997 # which belongs to/can be overwritten by callee. N is the number of
998 # arguments passed to callee, *but* not less than 4! This means that
999 # upon function entry point 5th argument resides at 40(%rsp), as well
1000 # as that 32 bytes from 8(%rsp) can always be used as temporal
1001 # storage [without allocating a frame]. One can actually argue that
1002 # one can assume a "red zone" above stack pointer under Win64 as well.
1003 # Point is that at apparently no occasion Windows kernel would alter
1004 # the area above user stack pointer in true asynchronous manner...
1006 # All the above means that if assembler programmer adheres to Unix
1007 # register and stack layout, but disregards the "red zone" existence,
1008 # it's possible to use following prologue and epilogue to "gear" from
1009 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1011 # omnipotent_function:
1014 # movq %rsi,16(%rsp)
1015 # movq %rcx,%rdi ; if 1st argument is actually present
1016 # movq %rdx,%rsi ; if 2nd argument is actually ...
1017 # movq %r8,%rdx ; if 3rd argument is ...
1018 # movq %r9,%rcx ; if 4th argument ...
1019 # movq 40(%rsp),%r8 ; if 5th ...
1020 # movq 48(%rsp),%r9 ; if 6th ...
1025 # movq 16(%rsp),%rsi
1029 \f#################################################
1030 # Win64 SEH, Structured Exception Handling.
1032 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1033 # has undesired side-effect at run-time: if an exception is raised in
1034 # assembler subroutine such as those in question (basically we're
1035 # referring to segmentation violations caused by malformed input
1036 # parameters), the application is briskly terminated without invoking
1037 # any exception handlers, most notably without generating memory dump
1038 # or any user notification whatsoever. This poses a problem. It's
1039 # possible to address it by registering custom language-specific
1040 # handler that would restore processor context to the state at
1041 # subroutine entry point and return "exception is not handled, keep
1042 # unwinding" code. Writing such handler can be a challenge... But it's
1043 # doable, though requires certain coding convention. Consider following
1046 # .type function,@function
1048 # movq %rsp,%rax # copy rsp to volatile register
1049 # pushq %r15 # save non-volatile registers
1053 # subq %rdi,%r11 # prepare [variable] stack frame
1055 # movq %rax,0(%r11) # check for exceptions
1056 # movq %r11,%rsp # allocate [variable] stack frame
1057 # movq %rax,0(%rsp) # save original rsp value
1060 # movq 0(%rsp),%rcx # pull original rsp value
1061 # movq -24(%rcx),%rbp # restore non-volatile registers
1062 # movq -16(%rcx),%rbx
1063 # movq -8(%rcx),%r15
1064 # movq %rcx,%rsp # restore original rsp
1066 # .size function,.-function
1068 # The key is that up to magic_point copy of original rsp value remains
1069 # in chosen volatile register and no non-volatile register, except for
1070 # rsp, is modified. While past magic_point rsp remains constant till
1071 # the very end of the function. In this case custom language-specific
1072 # exception handler would look like this:
1074 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1075 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1076 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1077 # if (context->Rip >= magic_point)
1078 # { rsp = ((ULONG64 **)context->Rsp)[0];
1079 # context->Rbp = rsp[-3];
1080 # context->Rbx = rsp[-2];
1081 # context->R15 = rsp[-1];
1083 # context->Rsp = (ULONG64)rsp;
1084 # context->Rdi = rsp[1];
1085 # context->Rsi = rsp[2];
1087 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1088 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1089 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1090 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1091 # return ExceptionContinueSearch;
1094 # It's appropriate to implement this handler in assembler, directly in
1095 # function's module. In order to do that one has to know members'
1096 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1097 # values. Here they are:
1117 # sizeof(CONTEXT) 1232
1118 # DISPATCHER_CONTEXT.ControlPc 0
1119 # DISPATCHER_CONTEXT.ImageBase 8
1120 # DISPATCHER_CONTEXT.FunctionEntry 16
1121 # DISPATCHER_CONTEXT.EstablisherFrame 24
1122 # DISPATCHER_CONTEXT.TargetIp 32
1123 # DISPATCHER_CONTEXT.ContextRecord 40
1124 # DISPATCHER_CONTEXT.LanguageHandler 48
1125 # DISPATCHER_CONTEXT.HandlerData 56
1126 # UNW_FLAG_NHANDLER 0
1127 # ExceptionContinueSearch 1
1129 # In order to tie the handler to the function one has to compose
1130 # couple of structures: one for .xdata segment and one for .pdata.
1132 # UNWIND_INFO structure for .xdata segment would be
1134 # function_unwind_info:
1138 # This structure designates exception handler for a function with
1139 # zero-length prologue, no stack frame or frame register.
1141 # To facilitate composing of .pdata structures, auto-generated "gear"
1142 # prologue copies rsp value to rax and denotes next instruction with
1143 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1144 # styling rule mentioned in the beginning. Position of this label is
1145 # chosen in such manner that possible exceptions raised in the "gear"
1146 # prologue would be accounted to caller and unwound from latter's frame.
1147 # End of function is marked with respective .LSEH_end_{function_name}
1148 # label. To summarize, .pdata segment would contain
1150 # .rva .LSEH_begin_function
1151 # .rva .LSEH_end_function
1152 # .rva function_unwind_info
1154 # Reference to function_unwind_info from .xdata segment is the anchor.
1155 # In case you wonder why references are 32-bit .rvas and not 64-bit
1156 # .quads. References put into these two segments are required to be
1157 # *relative* to the base address of the current binary module, a.k.a.
1158 # image base. No Win64 module, be it .exe or .dll, can be larger than
1159 # 2GB and thus such relative references can be and are accommodated in
1162 # Having reviewed the example function code, one can argue that "movq
1163 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1164 # rax would contain an undefined value. If this "offends" you, use
1165 # another register and refrain from modifying rax till magic_point is
1166 # reached, i.e. as if it was a non-volatile register. If more registers
1167 # are required prior [variable] frame setup is completed, note that
1168 # nobody says that you can have only one "magic point." You can
1169 # "liberate" non-volatile registers by denoting last stack off-load
1170 # instruction and reflecting it in finer grade unwind logic in handler.
1171 # After all, isn't it why it's called *language-specific* handler...
1173 # Attentive reader can notice that exceptions would be mishandled in
1174 # auto-generated "gear" epilogue. Well, exception effectively can't
1175 # occur there, because if memory area used by it was subject to
1176 # segmentation violation, then it would be raised upon call to the
1177 # function (and as already mentioned be accounted to caller, which is
1178 # not a problem). If you're still not comfortable, then define tail
1179 # "magic point" just prior ret instruction and have handler treat it...
1181 # (*) Note that we're talking about run-time, not debug-time. Lack of
1182 # unwind information makes debugging hard on both Windows and
1183 # Unix. "Unlike" referes to the fact that on Unix signal handler
1184 # will always be invoked, core dumped and appropriate exit code
1185 # returned to parent (for user notification).