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 index 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 cfi_directive;
469 # CFI directives annotate instructions that are significant for
470 # stack unwinding procedure compliant with DWARF specification,
471 # see http://dwarfstd.org/. Besides naturally expected for this
472 # script platform-specific filtering function, this module adds
473 # three auxiliary synthetic directives not recognized by [GNU]
476 # - .cfi_push to annotate push instructions in prologue, which
477 # translates to .cfi_adjust_cfa_offset (if needed) and
479 # - .cfi_pop to annotate pop instructions in epilogue, which
480 # translates to .cfi_adjust_cfa_offset (if needed) and
482 # - [and most notably] .cfi_cfa_expression which encodes
483 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as
486 # CFA expressions were introduced in DWARF specification version
487 # 3 and describe how to deduce CFA, Canonical Frame Address. This
488 # becomes handy if your stack frame is variable and you can't
489 # spare register for [previous] frame pointer. Suggested directive
490 # syntax is made-up mix of DWARF operator suffixes [subset of]
491 # and references to registers with optional bias. Following example
492 # describes offloaded *original* stack pointer at specific offset
493 # from *current* stack pointer:
495 # .cfi_cfa_expression %rsp+40,deref,+8
497 # Final +8 has everything to do with the fact that CFA is defined
498 # as reference to top of caller's stack, and on x86_64 call to
499 # subroutine pushes 8-byte return address. In other words original
500 # stack pointer upon entry to a subroutine is 8 bytes off from CFA.
502 # Below constants are taken from "DWARF Expressions" section of the
503 # DWARF specification, section is numbered 7.7 in versions 3 and 4.
504 my %DW_OP_simple = ( # no-arg operators, mapped directly
505 deref => 0x06, dup => 0x12,
506 drop => 0x13, over => 0x14,
507 pick => 0x15, swap => 0x16,
508 rot => 0x17, xderef => 0x18,
510 abs => 0x19, and => 0x1a,
511 div => 0x1b, minus => 0x1c,
512 mod => 0x1d, mul => 0x1e,
513 neg => 0x1f, not => 0x20,
514 or => 0x21, plus => 0x22,
515 shl => 0x24, shr => 0x25,
516 shra => 0x26, xor => 0x27,
519 my %DW_OP_complex = ( # used in specific subroutines
520 constu => 0x10, # uleb128
521 consts => 0x11, # sleb128
522 plus_uconst => 0x23, # uleb128
523 lit0 => 0x30, # add 0-31 to opcode
524 reg0 => 0x50, # add 0-31 to opcode
525 breg0 => 0x70, # add 0-31 to opcole, sleb128
526 regx => 0x90, # uleb28
527 fbreg => 0x91, # sleb128
528 bregx => 0x92, # uleb128, sleb128
529 piece => 0x93, # uleb128
532 # Following constants are defined in x86_64 ABI supplement, for
533 # example avaiable at https://www.uclibc.org/docs/psABI-x86_64.pdf,
534 # see section 3.7 "Stack Unwind Algorithm".
536 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3,
537 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7,
538 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11,
539 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15
542 my ($cfa_reg, $cfa_rsp);
544 # [us]leb128 format is variable-length integer representation base
545 # 2^128, with most significant bit of each byte being 0 denoting
546 # *last* most significat digit. See "Variable Length Data" in the
547 # DWARF specification, numbered 7.6 at least in versions 3 and 4.
549 use integer; # get right shift extend sign
552 my $sign = ($val < 0) ? -1 : 0;
556 push @ret, $val&0x7f;
558 # see if remaining bits are same and equal to most
559 # significant bit of the current digit, if so, it's
561 last if (($val>>6) == $sign);
574 push @ret, $val&0x7f;
576 # see if it's last significant digit...
577 last if (($val >>= 7) == 0);
587 if ($val >= 0 && $val < 32) {
588 return ($DW_OP_complex{lit0}+$val);
590 return ($DW_OP_complex{consts}, sleb128($val));
595 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/);
597 my $reg = $DW_reg_idx{$1};
598 my $off = eval ("0 $2 $3");
600 return (($DW_OP_complex{breg0} + $reg), sleb128($off));
601 # Yes, we use DW_OP_bregX+0 to push register value and not
602 # DW_OP_regX, because latter would require even DW_OP_piece,
603 # which would be a waste under the circumstances. If you have
604 # to use DWP_OP_reg, use "regx:N"...
610 foreach my $token (split(/,\s*/,$line)) {
611 if ($token =~ /^%r/) {
612 push @ret,reg($token);
613 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) {
614 push @ret,reg("$2+$1");
615 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) {
617 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i));
618 } elsif (my $i = 1*eval($token) or $token eq "0") {
619 if ($token =~ /^\+/) {
620 push @ret,$DW_OP_complex{plus_uconst},uleb128($i);
625 push @ret,$DW_OP_simple{$token};
629 # Finally we return DW_CFA_def_cfa_expression, 15, followed by
630 # length of the expression and of course the expression itself.
631 return (15,scalar(@ret),@ret);
634 my ($class, $line) = @_;
638 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) {
641 undef $self->{value};
645 # What is $cfa_rsp? Effectively it's difference between %rsp
646 # value and current CFA, Canonical Frame Address, which is
647 # why it starts with -8. Recall that CFA is top of caller's
649 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; };
650 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0); last; };
652 && do { $cfa_reg = $$line; last; };
654 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
658 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
661 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
663 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
667 /push/ && do { $dir = undef;
669 if ($cfa_reg eq "%rsp") {
670 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
672 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
675 /pop/ && do { $dir = undef;
677 if ($cfa_reg eq "%rsp") {
678 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
680 $self->{value} .= ".cfi_restore\t$$line";
684 && do { $dir = undef;
685 $self->{value} = ".cfi_escape\t" .
686 join(",", map(sprintf("0x%02x", $_),
687 cfa_expression($$line)));
692 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
701 return ($elf ? $self->{value} : undef);
704 { package directive; # pick up directives, which start with .
706 my ($class, $line) = @_;
711 # chain-call to cfi_directive
712 $ret = cfi_directive->re($line) and return $ret;
714 if ($$line =~ /^\s*(\.\w+)/) {
718 undef $self->{value};
719 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
722 /\.global|\.globl|\.extern/
723 && do { $globals{$$line} = $prefix . $$line;
724 $$line = $globals{$$line} if ($prefix);
727 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
728 if ($type eq "\@function") {
729 undef $current_function;
730 $current_function->{name} = $sym;
731 $current_function->{abi} = "svr4";
732 $current_function->{narg} = $narg;
733 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
734 } elsif ($type eq "\@abi-omnipotent") {
735 undef $current_function;
736 $current_function->{name} = $sym;
737 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
739 $$line =~ s/\@abi\-omnipotent/\@function/;
740 $$line =~ s/\@function.*/\@function/;
743 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
745 $$line = join(",",unpack("C*",$1),0);
749 /\.rva|\.long|\.quad/
750 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
751 $$line =~ s/\.L/$decor/g;
757 $self->{value} = $dir . "\t" . $$line;
759 if ($dir =~ /\.extern/) {
760 $self->{value} = ""; # swallow extern
761 } elsif (!$elf && $dir =~ /\.type/) {
763 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
764 (defined($globals{$1})?".scl 2;":".scl 3;") .
765 "\t.type 32;\t.endef"
766 if ($win64 && $$line =~ /([^,]+),\@function/);
767 } elsif (!$elf && $dir =~ /\.size/) {
769 if (defined($current_function)) {
770 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
771 if ($win64 && $current_function->{abi} eq "svr4");
772 undef $current_function;
774 } elsif (!$elf && $dir =~ /\.align/) {
775 $self->{value} = ".p2align\t" . (log($$line)/log(2));
776 } elsif ($dir eq ".section") {
777 $current_segment=$$line;
778 if (!$elf && $current_segment eq ".init") {
779 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
780 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
782 } elsif ($dir =~ /\.(text|data)/) {
783 $current_segment=".$1";
784 } elsif ($dir =~ /\.hidden/) {
785 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
786 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
787 } elsif ($dir =~ /\.comm/) {
788 $self->{value} = "$dir\t$prefix$$line";
789 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
795 # non-gas case or nasm/masm
797 /\.text/ && do { my $v=undef;
799 $v="section .text code align=64\n";
801 $v="$current_segment\tENDS\n" if ($current_segment);
802 $current_segment = ".text\$";
803 $v.="$current_segment\tSEGMENT ";
804 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
810 /\.data/ && do { my $v=undef;
812 $v="section .data data align=8\n";
814 $v="$current_segment\tENDS\n" if ($current_segment);
815 $current_segment = "_DATA";
816 $v.="$current_segment\tSEGMENT";
821 /\.section/ && do { my $v=undef;
822 $$line =~ s/([^,]*).*/$1/;
823 $$line = ".CRT\$XCU" if ($$line eq ".init");
826 if ($$line=~/\.([px])data/) {
828 $v.=$1 eq "p"? 4 : 8;
829 } elsif ($$line=~/\.CRT\$/i) {
830 $v.=" rdata align=8";
833 $v="$current_segment\tENDS\n" if ($current_segment);
834 $v.="$$line\tSEGMENT";
835 if ($$line=~/\.([px])data/) {
837 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
838 } elsif ($$line=~/\.CRT\$/i) {
840 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
843 $current_segment = $$line;
847 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
848 $self->{value} .= ":NEAR" if ($masm);
852 && do { $self->{value} = $masm?"PUBLIC":"global";
853 $self->{value} .= "\t".$$line;
856 /\.size/ && do { if (defined($current_function)) {
857 undef $self->{value};
858 if ($current_function->{abi} eq "svr4") {
859 $self->{value}="${decor}SEH_end_$current_function->{name}:";
860 $self->{value}.=":\n" if($masm);
862 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
863 undef $current_function;
867 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
868 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
871 /\.(value|long|rva|quad)/
872 && do { my $sz = substr($1,0,1);
873 my @arr = split(/,\s*/,$$line);
874 my $last = pop(@arr);
875 my $conv = sub { my $var=shift;
876 $var=~s/^(0b[0-1]+)/oct($1)/eig;
877 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
878 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
879 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
883 $sz =~ tr/bvlrq/BWDDQ/;
884 $self->{value} = "\tD$sz\t";
885 for (@arr) { $self->{value} .= &$conv($_).","; }
886 $self->{value} .= &$conv($last);
889 /\.byte/ && do { my @str=split(/,\s*/,$$line);
890 map(s/(0b[0-1]+)/oct($1)/eig,@str);
891 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
893 $self->{value}.="DB\t"
894 .join(",",@str[0..15])."\n";
895 foreach (0..15) { shift @str; }
897 $self->{value}.="DB\t"
898 .join(",",@str) if (@str);
901 /\.comm/ && do { my @str=split(/,\s*/,$$line);
904 $v.="common $prefix@str[0] @str[1]";
906 $v="$current_segment\tENDS\n" if ($current_segment);
907 $current_segment = "_DATA";
908 $v.="$current_segment\tSEGMENT\n";
909 $v.="COMM @str[0]:DWORD:".@str[1]/4;
926 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
927 # yet. In order not to be bothered by tracing exact assembler versions,
928 # but at the same time to provide a bare security minimum of AES-NI, we
929 # hard-code some instructions. Extensions past AES-NI on the other hand
930 # are traced by examining assembler version in individual perlasm
933 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
934 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
938 my ($dst,$src,$rex)=@_;
940 $rex|=0x04 if($dst>=8);
941 $rex|=0x01 if($src>=8);
942 push @$opcode,($rex|0x40) if ($rex);
945 my $movq = sub { # elderly gas can't handle inter-register movq
948 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
949 my ($src,$dst)=($1,$2);
950 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
951 rex(\@opcode,$src,$dst,0x8);
952 push @opcode,0x0f,0x7e;
953 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
955 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
956 my ($src,$dst)=($2,$1);
957 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
958 rex(\@opcode,$src,$dst,0x8);
959 push @opcode,0x0f,0x6e;
960 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
968 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
973 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
974 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
975 rex(\@opcode,$src,$dst);
976 push @opcode,0x0f,0x3a,0x16;
977 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
986 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
991 if ($src =~ /%r([0-9]+)/) { $src = $1; }
992 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
993 rex(\@opcode,$dst,$src);
994 push @opcode,0x0f,0x3a,0x22;
995 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1004 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1006 rex(\@opcode,$2,$1);
1007 push @opcode,0x0f,0x38,0x00;
1008 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1016 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1018 rex(\@opcode,$3,$2);
1019 push @opcode,0x0f,0x3a,0x0f;
1020 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1028 my $pclmulqdq = sub {
1029 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1031 rex(\@opcode,$3,$2);
1032 push @opcode,0x0f,0x3a,0x44;
1033 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1035 push @opcode,$c=~/^0/?oct($c):$c;
1043 if (shift =~ /%[er](\w+)/) {
1046 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1047 rex(\@opcode,0,$dst,8);
1048 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1056 if (shift =~ /%[er](\w+)/) {
1059 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1060 rex(\@opcode,0,$dst,8);
1061 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1068 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1069 # are using only two instructions hand-code them in order to be excused
1070 # from chasing assembler versions...
1074 my ($dst,$src1,$src2,$rxb)=@_;
1077 $rxb&=~(0x04<<5) if($dst>=8);
1078 $rxb&=~(0x01<<5) if($src1>=8);
1079 $rxb&=~(0x02<<5) if($src2>=8);
1084 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1086 rxb(\@opcode,$3,$2,-1,0x08);
1087 push @opcode,0x78,0xc2;
1088 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1090 push @opcode,$c=~/^0/?oct($c):$c;
1098 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1100 rxb(\@opcode,$3,$2,-1,0x08);
1101 push @opcode,0x78,0xc3;
1102 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1104 push @opcode,$c=~/^0/?oct($c):$c;
1111 # Intel Control-flow Enforcement Technology extension. All functions and
1112 # indirect branch targets will have to start with this instruction...
1114 my $endbranch = sub {
1115 (0xf3,0x0f,0x1e,0xfa);
1118 ########################################################################
1132 while(defined(my $line=<>)) {
1134 $line =~ s|\R$||; # Better chomp
1136 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1137 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1138 $line =~ s|^\s+||; # ... and skip white spaces in beginning
1139 $line =~ s|\s+$||; # ... and at the end
1141 if (my $label=label->re(\$line)) { print $label->out(); }
1143 if (my $directive=directive->re(\$line)) {
1144 printf "%s",$directive->out();
1145 } elsif (my $opcode=opcode->re(\$line)) {
1146 my $asm = eval("\$".$opcode->mnemonic());
1148 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1149 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1154 ARGUMENT: while (1) {
1157 ($arg=register->re(\$line, $opcode))||
1158 ($arg=const->re(\$line)) ||
1159 ($arg=ea->re(\$line, $opcode)) ||
1160 ($arg=expr->re(\$line, $opcode)) ||
1165 last ARGUMENT if ($line !~ /^,/);
1172 my $sz=$opcode->size();
1175 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1176 @args = map($_->out($sz),@args);
1177 printf "\t%s\t%s",$insn,join(",",@args);
1179 $insn = $opcode->out();
1181 my $arg = $_->out();
1182 # $insn.=$sz compensates for movq, pinsrw, ...
1183 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1184 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1185 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1186 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1188 @args = reverse(@args);
1189 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1190 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1193 printf "\t%s",$opcode->out();
1200 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1201 print "END\n" if ($masm);
1205 \f#################################################
1206 # Cross-reference x86_64 ABI "card"
1226 # (*) volatile register
1227 # (-) preserved by callee
1228 # (#) Nth argument, volatile
1230 # In Unix terms top of stack is argument transfer area for arguments
1231 # which could not be accommodated in registers. Or in other words 7th
1232 # [integer] argument resides at 8(%rsp) upon function entry point.
1233 # 128 bytes above %rsp constitute a "red zone" which is not touched
1234 # by signal handlers and can be used as temporal storage without
1235 # allocating a frame.
1237 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1238 # which belongs to/can be overwritten by callee. N is the number of
1239 # arguments passed to callee, *but* not less than 4! This means that
1240 # upon function entry point 5th argument resides at 40(%rsp), as well
1241 # as that 32 bytes from 8(%rsp) can always be used as temporal
1242 # storage [without allocating a frame]. One can actually argue that
1243 # one can assume a "red zone" above stack pointer under Win64 as well.
1244 # Point is that at apparently no occasion Windows kernel would alter
1245 # the area above user stack pointer in true asynchronous manner...
1247 # All the above means that if assembler programmer adheres to Unix
1248 # register and stack layout, but disregards the "red zone" existense,
1249 # it's possible to use following prologue and epilogue to "gear" from
1250 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1252 # omnipotent_function:
1255 # movq %rsi,16(%rsp)
1256 # movq %rcx,%rdi ; if 1st argument is actually present
1257 # movq %rdx,%rsi ; if 2nd argument is actually ...
1258 # movq %r8,%rdx ; if 3rd argument is ...
1259 # movq %r9,%rcx ; if 4th argument ...
1260 # movq 40(%rsp),%r8 ; if 5th ...
1261 # movq 48(%rsp),%r9 ; if 6th ...
1266 # movq 16(%rsp),%rsi
1270 \f#################################################
1271 # Win64 SEH, Structured Exception Handling.
1273 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1274 # has undesired side-effect at run-time: if an exception is raised in
1275 # assembler subroutine such as those in question (basically we're
1276 # referring to segmentation violations caused by malformed input
1277 # parameters), the application is briskly terminated without invoking
1278 # any exception handlers, most notably without generating memory dump
1279 # or any user notification whatsoever. This poses a problem. It's
1280 # possible to address it by registering custom language-specific
1281 # handler that would restore processor context to the state at
1282 # subroutine entry point and return "exception is not handled, keep
1283 # unwinding" code. Writing such handler can be a challenge... But it's
1284 # doable, though requires certain coding convention. Consider following
1287 # .type function,@function
1289 # movq %rsp,%rax # copy rsp to volatile register
1290 # pushq %r15 # save non-volatile registers
1294 # subq %rdi,%r11 # prepare [variable] stack frame
1296 # movq %rax,0(%r11) # check for exceptions
1297 # movq %r11,%rsp # allocate [variable] stack frame
1298 # movq %rax,0(%rsp) # save original rsp value
1301 # movq 0(%rsp),%rcx # pull original rsp value
1302 # movq -24(%rcx),%rbp # restore non-volatile registers
1303 # movq -16(%rcx),%rbx
1304 # movq -8(%rcx),%r15
1305 # movq %rcx,%rsp # restore original rsp
1308 # .size function,.-function
1310 # The key is that up to magic_point copy of original rsp value remains
1311 # in chosen volatile register and no non-volatile register, except for
1312 # rsp, is modified. While past magic_point rsp remains constant till
1313 # the very end of the function. In this case custom language-specific
1314 # exception handler would look like this:
1316 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1317 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1318 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1319 # ULONG64 rip = context->Rip;
1321 # if (rip >= magic_point)
1322 # { rsp = (ULONG64 *)context->Rsp;
1323 # if (rip < magic_epilogue)
1324 # { rsp = (ULONG64 *)rsp[0];
1325 # context->Rbp = rsp[-3];
1326 # context->Rbx = rsp[-2];
1327 # context->R15 = rsp[-1];
1330 # context->Rsp = (ULONG64)rsp;
1331 # context->Rdi = rsp[1];
1332 # context->Rsi = rsp[2];
1334 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1335 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1336 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1337 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1338 # return ExceptionContinueSearch;
1341 # It's appropriate to implement this handler in assembler, directly in
1342 # function's module. In order to do that one has to know members'
1343 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1344 # values. Here they are:
1364 # sizeof(CONTEXT) 1232
1365 # DISPATCHER_CONTEXT.ControlPc 0
1366 # DISPATCHER_CONTEXT.ImageBase 8
1367 # DISPATCHER_CONTEXT.FunctionEntry 16
1368 # DISPATCHER_CONTEXT.EstablisherFrame 24
1369 # DISPATCHER_CONTEXT.TargetIp 32
1370 # DISPATCHER_CONTEXT.ContextRecord 40
1371 # DISPATCHER_CONTEXT.LanguageHandler 48
1372 # DISPATCHER_CONTEXT.HandlerData 56
1373 # UNW_FLAG_NHANDLER 0
1374 # ExceptionContinueSearch 1
1376 # In order to tie the handler to the function one has to compose
1377 # couple of structures: one for .xdata segment and one for .pdata.
1379 # UNWIND_INFO structure for .xdata segment would be
1381 # function_unwind_info:
1385 # This structure designates exception handler for a function with
1386 # zero-length prologue, no stack frame or frame register.
1388 # To facilitate composing of .pdata structures, auto-generated "gear"
1389 # prologue copies rsp value to rax and denotes next instruction with
1390 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1391 # styling rule mentioned in the beginning. Position of this label is
1392 # chosen in such manner that possible exceptions raised in the "gear"
1393 # prologue would be accounted to caller and unwound from latter's frame.
1394 # End of function is marked with respective .LSEH_end_{function_name}
1395 # label. To summarize, .pdata segment would contain
1397 # .rva .LSEH_begin_function
1398 # .rva .LSEH_end_function
1399 # .rva function_unwind_info
1401 # Reference to function_unwind_info from .xdata segment is the anchor.
1402 # In case you wonder why references are 32-bit .rvas and not 64-bit
1403 # .quads. References put into these two segments are required to be
1404 # *relative* to the base address of the current binary module, a.k.a.
1405 # image base. No Win64 module, be it .exe or .dll, can be larger than
1406 # 2GB and thus such relative references can be and are accommodated in
1409 # Having reviewed the example function code, one can argue that "movq
1410 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1411 # rax would contain an undefined value. If this "offends" you, use
1412 # another register and refrain from modifying rax till magic_point is
1413 # reached, i.e. as if it was a non-volatile register. If more registers
1414 # are required prior [variable] frame setup is completed, note that
1415 # nobody says that you can have only one "magic point." You can
1416 # "liberate" non-volatile registers by denoting last stack off-load
1417 # instruction and reflecting it in finer grade unwind logic in handler.
1418 # After all, isn't it why it's called *language-specific* handler...
1420 # SE handlers are also involved in unwinding stack when executable is
1421 # profiled or debugged. Profiling implies additional limitations that
1422 # are too subtle to discuss here. For now it's sufficient to say that
1423 # in order to simplify handlers one should either a) offload original
1424 # %rsp to stack (like discussed above); or b) if you have a register to
1425 # spare for frame pointer, choose volatile one.
1427 # (*) Note that we're talking about run-time, not debug-time. Lack of
1428 # unwind information makes debugging hard on both Windows and
1429 # Unix. "Unlike" referes to the fact that on Unix signal handler
1430 # will always be invoked, core dumped and appropriate exit code
1431 # returned to parent (for user notification).