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
56 # 8. In order to provide for structured exception handling unified
57 # Win64 prologue copies %rsp value to %rax. For further details
58 # see SEH paragraph at the end.
59 # 9. .init segment is allowed to contain calls to functions only.
60 # a. If function accepts more than 4 arguments *and* >4th argument
61 # is declared as non 64-bit value, do clear its upper part.
68 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
70 open STDOUT,">$output" || die "can't open $output: $!"
71 if (defined($output));
73 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
74 my $elf=1; $elf=0 if (!$gas);
79 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
86 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
87 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
88 $prefix =~ s|\R$||; # Better chomp
90 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
91 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
92 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
94 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
95 { $nasm = $1 + $2*0.01; $PTR=""; }
96 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
97 { $masm = $1 + $2*2**-16 + $4*2**-32; }
98 die "no assembler found on %PATH%" if (!($nasm || $masm));
105 my $current_function;
108 { package opcode; # pick up opcodes
110 my ($class, $line) = @_;
114 if ($$line =~ /^([a-z][a-z0-9]*)/i) {
118 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
121 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
124 } elsif ($self->{op} =~ /call|jmp/) {
126 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
128 } elsif ($self->{op} =~ /^[vk]/) { # VEX or k* such as kmov
130 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) {
132 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
140 my ($self, $sz) = @_;
141 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
147 if ($self->{op} eq "movz") { # movz is pain...
148 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
149 } elsif ($self->{op} =~ /^set/) {
151 } elsif ($self->{op} eq "ret") {
153 if ($win64 && $current_function->{abi} eq "svr4") {
154 $epilogue = "movq 8(%rsp),%rdi\n\t" .
155 "movq 16(%rsp),%rsi\n\t";
157 $epilogue . ".byte 0xf3,0xc3";
158 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
159 ".p2align\t3\n\t.quad";
161 "$self->{op}$self->{sz}";
164 $self->{op} =~ s/^movz/movzx/;
165 if ($self->{op} eq "ret") {
167 if ($win64 && $current_function->{abi} eq "svr4") {
168 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t".
169 "mov rsi,QWORD$PTR\[16+rsp\]\n\t";
171 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
172 } elsif ($self->{op} =~ /^(pop|push)f/) {
173 $self->{op} .= $self->{sz};
174 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
175 $self->{op} = "\tDQ";
181 my ($self, $op) = @_;
182 $self->{op}=$op if (defined($op));
186 { package const; # pick up constants, which start with $
188 my ($class, $line) = @_;
192 if ($$line =~ /^\$([^,]+)/) {
196 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
203 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
205 # Solaris /usr/ccs/bin/as can't handle multiplications
207 my $value = $self->{value};
208 no warnings; # oct might complain about overflow, ignore here...
209 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
210 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
211 $self->{value} = $value;
213 sprintf "\$%s",$self->{value};
215 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
216 sprintf "%s",$self->{value};
220 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
222 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
223 l=>"DWORD$PTR", d=>"DWORD$PTR",
224 q=>"QWORD$PTR", o=>"OWORD$PTR",
225 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR",
226 z=>"ZMMWORD$PTR" ) if (!$gas);
229 my ($class, $line, $opcode) = @_;
233 # optional * ----vvv--- appears in indirect jmp/call
234 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) {
236 $self->{asterisk} = $1;
238 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
239 $self->{scale} = 1 if (!defined($self->{scale}));
240 $self->{opmask} = $4;
242 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
244 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
245 die if ($opcode->mnemonic() ne "mov");
246 $opcode->mnemonic("lea");
248 $self->{base} =~ s/^%//;
249 $self->{index} =~ s/^%// if (defined($self->{index}));
250 $self->{opcode} = $opcode;
256 my ($self, $sz) = @_;
258 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
259 $self->{label} =~ s/\.L/$decor/g;
261 # Silently convert all EAs to 64-bit. This is required for
262 # elder GNU assembler and results in more compact code,
263 # *but* most importantly AES module depends on this feature!
264 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
265 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
267 # Solaris /usr/ccs/bin/as can't handle multiplications
268 # in $self->{label}...
270 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
271 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
273 # Some assemblers insist on signed presentation of 32-bit
274 # offsets, but sign extension is a tricky business in perl...
276 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
278 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
281 # if base register is %rbp or %r13, see if it's possible to
282 # flip base and ingex registers [for better performance]
283 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
284 $self->{base} =~ /(rbp|r13)/) {
285 $self->{base} = $self->{index}; $self->{index} = $1;
289 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
291 if (defined($self->{index})) {
292 sprintf "%s%s(%s,%%%s,%d)%s",
293 $self->{asterisk},$self->{label},
294 $self->{base}?"%$self->{base}":"",
295 $self->{index},$self->{scale},
298 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label},
299 $self->{base},$self->{opmask};
302 $self->{label} =~ s/\./\$/g;
303 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
304 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
306 my $mnemonic = $self->{opcode}->mnemonic();
307 ($self->{asterisk}) && ($sz="q") ||
308 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
309 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
310 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
311 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
313 $self->{opmask} =~ s/%(k[0-7])/$1/;
315 if (defined($self->{index})) {
316 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz},
317 $self->{label}?"$self->{label}+":"",
318 $self->{index},$self->{scale},
319 $self->{base}?"+$self->{base}":"",
321 } elsif ($self->{base} eq "rip") {
322 sprintf "%s[%s]",$szmap{$sz},$self->{label};
324 sprintf "%s[%s%s]%s", $szmap{$sz},
325 $self->{label}?"$self->{label}+":"",
326 $self->{base},$self->{opmask};
331 { package register; # pick up registers, which start with %.
333 my ($class, $line, $opcode) = @_;
337 # optional * ----vvv--- appears in indirect jmp/call
338 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) {
340 $self->{asterisk} = $1;
342 $self->{opmask} = $3;
343 $opcode->size($self->size());
345 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
353 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
354 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
355 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
356 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
357 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
358 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
359 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
360 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
366 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk},
369 else { $self->{opmask} =~ s/%(k[0-7])/$1/;
370 $self->{value}.$self->{opmask}; }
373 { package label; # pick up labels, which end with :
375 my ($class, $line) = @_;
379 if ($$line =~ /(^[\.\w]+)\:/) {
383 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
385 $self->{value} =~ s/^\.L/$decor/;
393 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
394 if ($win64 && $current_function->{name} eq $self->{value}
395 && $current_function->{abi} eq "svr4") {
397 $func .= " movq %rdi,8(%rsp)\n";
398 $func .= " movq %rsi,16(%rsp)\n";
399 $func .= " movq %rsp,%rax\n";
400 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
401 my $narg = $current_function->{narg};
402 $narg=6 if (!defined($narg));
403 $func .= " movq %rcx,%rdi\n" if ($narg>0);
404 $func .= " movq %rdx,%rsi\n" if ($narg>1);
405 $func .= " movq %r8,%rdx\n" if ($narg>2);
406 $func .= " movq %r9,%rcx\n" if ($narg>3);
407 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
408 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
411 } elsif ($self->{value} ne "$current_function->{name}") {
412 # Make all labels in masm global.
413 $self->{value} .= ":" if ($masm);
414 $self->{value} . ":";
415 } elsif ($win64 && $current_function->{abi} eq "svr4") {
416 my $func = "$current_function->{name}" .
417 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
419 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
420 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
421 $func .= " mov rax,rsp\n";
422 $func .= "${decor}SEH_begin_$current_function->{name}:";
423 $func .= ":" if ($masm);
425 my $narg = $current_function->{narg};
426 $narg=6 if (!defined($narg));
427 $func .= " mov rdi,rcx\n" if ($narg>0);
428 $func .= " mov rsi,rdx\n" if ($narg>1);
429 $func .= " mov rdx,r8\n" if ($narg>2);
430 $func .= " mov rcx,r9\n" if ($narg>3);
431 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
432 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
435 "$current_function->{name}".
436 ($nasm ? ":" : "\tPROC $current_function->{scope}");
440 { package expr; # pick up expressioins
442 my ($class, $line, $opcode) = @_;
446 if ($$line =~ /(^[^,]+)/) {
450 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
452 $self->{value} =~ s/\@PLT// if (!$elf);
453 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
454 $self->{value} =~ s/\.L/$decor/g;
455 $self->{opcode} = $opcode;
461 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
462 "NEAR ".$self->{value};
468 { package directive; # pick up directives, which start with .
470 my ($class, $line) = @_;
475 if ($$line =~ /^\s*(\.\w+)/) {
479 undef $self->{value};
480 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
483 /\.global|\.globl|\.extern/
484 && do { $globals{$$line} = $prefix . $$line;
485 $$line = $globals{$$line} if ($prefix);
488 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
489 if ($type eq "\@function") {
490 undef $current_function;
491 $current_function->{name} = $sym;
492 $current_function->{abi} = "svr4";
493 $current_function->{narg} = $narg;
494 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
495 } elsif ($type eq "\@abi-omnipotent") {
496 undef $current_function;
497 $current_function->{name} = $sym;
498 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
500 $$line =~ s/\@abi\-omnipotent/\@function/;
501 $$line =~ s/\@function.*/\@function/;
504 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
506 $$line = join(",",unpack("C*",$1),0);
510 /\.rva|\.long|\.quad/
511 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
512 $$line =~ s/\.L/$decor/g;
518 $self->{value} = $dir . "\t" . $$line;
520 if ($dir =~ /\.extern/) {
521 $self->{value} = ""; # swallow extern
522 } elsif (!$elf && $dir =~ /\.type/) {
524 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
525 (defined($globals{$1})?".scl 2;":".scl 3;") .
526 "\t.type 32;\t.endef"
527 if ($win64 && $$line =~ /([^,]+),\@function/);
528 } elsif (!$elf && $dir =~ /\.size/) {
530 if (defined($current_function)) {
531 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
532 if ($win64 && $current_function->{abi} eq "svr4");
533 undef $current_function;
535 } elsif (!$elf && $dir =~ /\.align/) {
536 $self->{value} = ".p2align\t" . (log($$line)/log(2));
537 } elsif ($dir eq ".section") {
538 $current_segment=$$line;
539 if (!$elf && $current_segment eq ".init") {
540 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
541 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
543 } elsif ($dir =~ /\.(text|data)/) {
544 $current_segment=".$1";
545 } elsif ($dir =~ /\.hidden/) {
546 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
547 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
548 } elsif ($dir =~ /\.comm/) {
549 $self->{value} = "$dir\t$prefix$$line";
550 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
556 # non-gas case or nasm/masm
558 /\.text/ && do { my $v=undef;
560 $v="section .text code align=64\n";
562 $v="$current_segment\tENDS\n" if ($current_segment);
563 $current_segment = ".text\$";
564 $v.="$current_segment\tSEGMENT ";
565 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
571 /\.data/ && do { my $v=undef;
573 $v="section .data data align=8\n";
575 $v="$current_segment\tENDS\n" if ($current_segment);
576 $current_segment = "_DATA";
577 $v.="$current_segment\tSEGMENT";
582 /\.section/ && do { my $v=undef;
583 $$line =~ s/([^,]*).*/$1/;
584 $$line = ".CRT\$XCU" if ($$line eq ".init");
587 if ($$line=~/\.([px])data/) {
589 $v.=$1 eq "p"? 4 : 8;
590 } elsif ($$line=~/\.CRT\$/i) {
591 $v.=" rdata align=8";
594 $v="$current_segment\tENDS\n" if ($current_segment);
595 $v.="$$line\tSEGMENT";
596 if ($$line=~/\.([px])data/) {
598 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
599 } elsif ($$line=~/\.CRT\$/i) {
601 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
604 $current_segment = $$line;
608 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
609 $self->{value} .= ":NEAR" if ($masm);
613 && do { $self->{value} = $masm?"PUBLIC":"global";
614 $self->{value} .= "\t".$$line;
617 /\.size/ && do { if (defined($current_function)) {
618 undef $self->{value};
619 if ($current_function->{abi} eq "svr4") {
620 $self->{value}="${decor}SEH_end_$current_function->{name}:";
621 $self->{value}.=":\n" if($masm);
623 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
624 undef $current_function;
628 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
629 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
632 /\.(value|long|rva|quad)/
633 && do { my $sz = substr($1,0,1);
634 my @arr = split(/,\s*/,$$line);
635 my $last = pop(@arr);
636 my $conv = sub { my $var=shift;
637 $var=~s/^(0b[0-1]+)/oct($1)/eig;
638 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
639 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
640 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
644 $sz =~ tr/bvlrq/BWDDQ/;
645 $self->{value} = "\tD$sz\t";
646 for (@arr) { $self->{value} .= &$conv($_).","; }
647 $self->{value} .= &$conv($last);
650 /\.byte/ && do { my @str=split(/,\s*/,$$line);
651 map(s/(0b[0-1]+)/oct($1)/eig,@str);
652 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
654 $self->{value}.="DB\t"
655 .join(",",@str[0..15])."\n";
656 foreach (0..15) { shift @str; }
658 $self->{value}.="DB\t"
659 .join(",",@str) if (@str);
662 /\.comm/ && do { my @str=split(/,\s*/,$$line);
665 $v.="common $prefix@str[0] @str[1]";
667 $v="$current_segment\tENDS\n" if ($current_segment);
668 $current_segment = "_DATA";
669 $v.="$current_segment\tSEGMENT\n";
670 $v.="COMM @str[0]:DWORD:".@str[1]/4;
687 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
688 # yet. In order not to be bothered by tracing exact assembler versions,
689 # but at the same time to provide a bare security minimum of AES-NI, we
690 # hard-code some instructions. Extensions past AES-NI on the other hand
691 # are traced by examining assembler version in individual perlasm
694 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
695 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
699 my ($dst,$src,$rex)=@_;
701 $rex|=0x04 if($dst>=8);
702 $rex|=0x01 if($src>=8);
703 push @$opcode,($rex|0x40) if ($rex);
706 my $movq = sub { # elderly gas can't handle inter-register movq
709 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
710 my ($src,$dst)=($1,$2);
711 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
712 rex(\@opcode,$src,$dst,0x8);
713 push @opcode,0x0f,0x7e;
714 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
716 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
717 my ($src,$dst)=($2,$1);
718 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
719 rex(\@opcode,$src,$dst,0x8);
720 push @opcode,0x0f,0x6e;
721 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
729 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
734 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
735 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
736 rex(\@opcode,$src,$dst);
737 push @opcode,0x0f,0x3a,0x16;
738 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
747 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
752 if ($src =~ /%r([0-9]+)/) { $src = $1; }
753 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
754 rex(\@opcode,$dst,$src);
755 push @opcode,0x0f,0x3a,0x22;
756 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
765 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
768 push @opcode,0x0f,0x38,0x00;
769 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
777 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
780 push @opcode,0x0f,0x3a,0x0f;
781 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
789 my $pclmulqdq = sub {
790 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
793 push @opcode,0x0f,0x3a,0x44;
794 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
796 push @opcode,$c=~/^0/?oct($c):$c;
804 if (shift =~ /%[er](\w+)/) {
807 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
808 rex(\@opcode,0,$dst,8);
809 push @opcode,0x0f,0xc7,0xf0|($dst&7);
817 if (shift =~ /%[er](\w+)/) {
820 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
821 rex(\@opcode,0,$dst,8);
822 push @opcode,0x0f,0xc7,0xf8|($dst&7);
829 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
830 # are using only two instructions hand-code them in order to be excused
831 # from chasing assembler versions...
835 my ($dst,$src1,$src2,$rxb)=@_;
838 $rxb&=~(0x04<<5) if($dst>=8);
839 $rxb&=~(0x01<<5) if($src1>=8);
840 $rxb&=~(0x02<<5) if($src2>=8);
845 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
847 rxb(\@opcode,$3,$2,-1,0x08);
848 push @opcode,0x78,0xc2;
849 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
851 push @opcode,$c=~/^0/?oct($c):$c;
859 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
861 rxb(\@opcode,$3,$2,-1,0x08);
862 push @opcode,0x78,0xc3;
863 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
865 push @opcode,$c=~/^0/?oct($c):$c;
872 # Intel Control-flow Enforcement Technology extension. All functions and
873 # indirect branch targets will have to start with this instruction...
875 my $endbranch = sub {
876 (0xf3,0x0f,0x1e,0xfa);
879 ########################################################################
893 while(defined(my $line=<>)) {
895 $line =~ s|\R$||; # Better chomp
897 $line =~ s|[#!].*$||; # get rid of asm-style comments...
898 $line =~ s|/\*.*\*/||; # ... and C-style comments...
899 $line =~ s|^\s+||; # ... and skip white spaces in beginning
900 $line =~ s|\s+$||; # ... and at the end
902 if (my $label=label->re(\$line)) { print $label->out(); }
904 if (my $directive=directive->re(\$line)) {
905 printf "%s",$directive->out();
906 } elsif (my $opcode=opcode->re(\$line)) {
907 my $asm = eval("\$".$opcode->mnemonic());
909 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
910 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
915 ARGUMENT: while (1) {
918 ($arg=register->re(\$line, $opcode))||
919 ($arg=const->re(\$line)) ||
920 ($arg=ea->re(\$line, $opcode)) ||
921 ($arg=expr->re(\$line, $opcode)) ||
926 last ARGUMENT if ($line !~ /^,/);
933 my $sz=$opcode->size();
936 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
937 @args = map($_->out($sz),@args);
938 printf "\t%s\t%s",$insn,join(",",@args);
940 $insn = $opcode->out();
943 # $insn.=$sz compensates for movq, pinsrw, ...
944 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
945 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
946 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
947 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
949 @args = reverse(@args);
950 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
951 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
954 printf "\t%s",$opcode->out();
961 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
962 print "END\n" if ($masm);
966 \f#################################################
967 # Cross-reference x86_64 ABI "card"
987 # (*) volatile register
988 # (-) preserved by callee
989 # (#) Nth argument, volatile
991 # In Unix terms top of stack is argument transfer area for arguments
992 # which could not be accommodated in registers. Or in other words 7th
993 # [integer] argument resides at 8(%rsp) upon function entry point.
994 # 128 bytes above %rsp constitute a "red zone" which is not touched
995 # by signal handlers and can be used as temporal storage without
996 # allocating a frame.
998 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
999 # which belongs to/can be overwritten by callee. N is the number of
1000 # arguments passed to callee, *but* not less than 4! This means that
1001 # upon function entry point 5th argument resides at 40(%rsp), as well
1002 # as that 32 bytes from 8(%rsp) can always be used as temporal
1003 # storage [without allocating a frame]. One can actually argue that
1004 # one can assume a "red zone" above stack pointer under Win64 as well.
1005 # Point is that at apparently no occasion Windows kernel would alter
1006 # the area above user stack pointer in true asynchronous manner...
1008 # All the above means that if assembler programmer adheres to Unix
1009 # register and stack layout, but disregards the "red zone" existense,
1010 # it's possible to use following prologue and epilogue to "gear" from
1011 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1013 # omnipotent_function:
1016 # movq %rsi,16(%rsp)
1017 # movq %rcx,%rdi ; if 1st argument is actually present
1018 # movq %rdx,%rsi ; if 2nd argument is actually ...
1019 # movq %r8,%rdx ; if 3rd argument is ...
1020 # movq %r9,%rcx ; if 4th argument ...
1021 # movq 40(%rsp),%r8 ; if 5th ...
1022 # movq 48(%rsp),%r9 ; if 6th ...
1027 # movq 16(%rsp),%rsi
1031 \f#################################################
1032 # Win64 SEH, Structured Exception Handling.
1034 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1035 # has undesired side-effect at run-time: if an exception is raised in
1036 # assembler subroutine such as those in question (basically we're
1037 # referring to segmentation violations caused by malformed input
1038 # parameters), the application is briskly terminated without invoking
1039 # any exception handlers, most notably without generating memory dump
1040 # or any user notification whatsoever. This poses a problem. It's
1041 # possible to address it by registering custom language-specific
1042 # handler that would restore processor context to the state at
1043 # subroutine entry point and return "exception is not handled, keep
1044 # unwinding" code. Writing such handler can be a challenge... But it's
1045 # doable, though requires certain coding convention. Consider following
1048 # .type function,@function
1050 # movq %rsp,%rax # copy rsp to volatile register
1051 # pushq %r15 # save non-volatile registers
1055 # subq %rdi,%r11 # prepare [variable] stack frame
1057 # movq %rax,0(%r11) # check for exceptions
1058 # movq %r11,%rsp # allocate [variable] stack frame
1059 # movq %rax,0(%rsp) # save original rsp value
1062 # movq 0(%rsp),%rcx # pull original rsp value
1063 # movq -24(%rcx),%rbp # restore non-volatile registers
1064 # movq -16(%rcx),%rbx
1065 # movq -8(%rcx),%r15
1066 # movq %rcx,%rsp # restore original rsp
1069 # .size function,.-function
1071 # The key is that up to magic_point copy of original rsp value remains
1072 # in chosen volatile register and no non-volatile register, except for
1073 # rsp, is modified. While past magic_point rsp remains constant till
1074 # the very end of the function. In this case custom language-specific
1075 # exception handler would look like this:
1077 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1078 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1079 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1080 # ULONG64 rip = context->Rip;
1082 # if (rip >= magic_point)
1083 # { rsp = (ULONG64 *)context->Rsp;
1084 # if (rip < magic_epilogue)
1085 # { rsp = (ULONG64 *)rsp[0];
1086 # context->Rbp = rsp[-3];
1087 # context->Rbx = rsp[-2];
1088 # context->R15 = rsp[-1];
1091 # context->Rsp = (ULONG64)rsp;
1092 # context->Rdi = rsp[1];
1093 # context->Rsi = rsp[2];
1095 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1096 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1097 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1098 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1099 # return ExceptionContinueSearch;
1102 # It's appropriate to implement this handler in assembler, directly in
1103 # function's module. In order to do that one has to know members'
1104 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1105 # values. Here they are:
1125 # sizeof(CONTEXT) 1232
1126 # DISPATCHER_CONTEXT.ControlPc 0
1127 # DISPATCHER_CONTEXT.ImageBase 8
1128 # DISPATCHER_CONTEXT.FunctionEntry 16
1129 # DISPATCHER_CONTEXT.EstablisherFrame 24
1130 # DISPATCHER_CONTEXT.TargetIp 32
1131 # DISPATCHER_CONTEXT.ContextRecord 40
1132 # DISPATCHER_CONTEXT.LanguageHandler 48
1133 # DISPATCHER_CONTEXT.HandlerData 56
1134 # UNW_FLAG_NHANDLER 0
1135 # ExceptionContinueSearch 1
1137 # In order to tie the handler to the function one has to compose
1138 # couple of structures: one for .xdata segment and one for .pdata.
1140 # UNWIND_INFO structure for .xdata segment would be
1142 # function_unwind_info:
1146 # This structure designates exception handler for a function with
1147 # zero-length prologue, no stack frame or frame register.
1149 # To facilitate composing of .pdata structures, auto-generated "gear"
1150 # prologue copies rsp value to rax and denotes next instruction with
1151 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1152 # styling rule mentioned in the beginning. Position of this label is
1153 # chosen in such manner that possible exceptions raised in the "gear"
1154 # prologue would be accounted to caller and unwound from latter's frame.
1155 # End of function is marked with respective .LSEH_end_{function_name}
1156 # label. To summarize, .pdata segment would contain
1158 # .rva .LSEH_begin_function
1159 # .rva .LSEH_end_function
1160 # .rva function_unwind_info
1162 # Reference to function_unwind_info from .xdata segment is the anchor.
1163 # In case you wonder why references are 32-bit .rvas and not 64-bit
1164 # .quads. References put into these two segments are required to be
1165 # *relative* to the base address of the current binary module, a.k.a.
1166 # image base. No Win64 module, be it .exe or .dll, can be larger than
1167 # 2GB and thus such relative references can be and are accommodated in
1170 # Having reviewed the example function code, one can argue that "movq
1171 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1172 # rax would contain an undefined value. If this "offends" you, use
1173 # another register and refrain from modifying rax till magic_point is
1174 # reached, i.e. as if it was a non-volatile register. If more registers
1175 # are required prior [variable] frame setup is completed, note that
1176 # nobody says that you can have only one "magic point." You can
1177 # "liberate" non-volatile registers by denoting last stack off-load
1178 # instruction and reflecting it in finer grade unwind logic in handler.
1179 # After all, isn't it why it's called *language-specific* handler...
1181 # SE handlers are also involved in unwinding stack when executable is
1182 # profiled or debugged. Profiling implies additional limitations that
1183 # are too subtle to discuss here. For now it's sufficient to say that
1184 # in order to simplify handlers one should either a) offload original
1185 # %rsp to stack (like discussed above); or b) if you have a register to
1186 # spare for frame pointer, choose volatile one.
1188 # (*) Note that we're talking about run-time, not debug-time. Lack of
1189 # unwind information makes debugging hard on both Windows and
1190 # Unix. "Unlike" referes to the fact that on Unix signal handler
1191 # will always be invoked, core dumped and appropriate exit code
1192 # returned to parent (for user notification).