2 # Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved.
4 # Licensed under the Apache License 2.0 (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 if ($flavour =~ /elf/) {
106 # Always generate .note.gnu.property section for ELF outputs to
107 # mark Intel CET support since all input files must be marked
108 # with Intel CET support in order for linker to mark output with
110 my $p2align=3; $p2align=2 if ($flavour eq "elf32");
111 $cet_property = <<_____;
112 .section ".note.gnu.property", "a"
118 # "GNU" encoded with .byte, since .asciz isn't supported
137 my $current_function;
140 { package opcode; # pick up opcodes
142 my ($class, $line) = @_;
146 if ($$line =~ /^([a-z][a-z0-9]*)/i) {
150 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
153 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
156 } elsif ($self->{op} =~ /call|jmp/) {
158 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
160 } elsif ($self->{op} =~ /^[vk]/) { # VEX or k* such as kmov
162 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) {
164 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
172 my ($self, $sz) = @_;
173 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
179 if ($self->{op} eq "movz") { # movz is pain...
180 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
181 } elsif ($self->{op} =~ /^set/) {
183 } elsif ($self->{op} eq "ret") {
185 if ($win64 && $current_function->{abi} eq "svr4") {
186 $epilogue = "movq 8(%rsp),%rdi\n\t" .
187 "movq 16(%rsp),%rsi\n\t";
189 $epilogue . ".byte 0xf3,0xc3";
190 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
191 ".p2align\t3\n\t.quad";
193 "$self->{op}$self->{sz}";
196 $self->{op} =~ s/^movz/movzx/;
197 if ($self->{op} eq "ret") {
199 if ($win64 && $current_function->{abi} eq "svr4") {
200 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t".
201 "mov rsi,QWORD$PTR\[16+rsp\]\n\t";
203 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
204 } elsif ($self->{op} =~ /^(pop|push)f/) {
205 $self->{op} .= $self->{sz};
206 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
207 $self->{op} = "\tDQ";
213 my ($self, $op) = @_;
214 $self->{op}=$op if (defined($op));
218 { package const; # pick up constants, which start with $
220 my ($class, $line) = @_;
224 if ($$line =~ /^\$([^,]+)/) {
228 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
235 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
237 # Solaris /usr/ccs/bin/as can't handle multiplications
239 my $value = $self->{value};
240 no warnings; # oct might complain about overflow, ignore here...
241 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
242 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
243 $self->{value} = $value;
245 sprintf "\$%s",$self->{value};
247 my $value = $self->{value};
248 $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
253 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
255 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
256 l=>"DWORD$PTR", d=>"DWORD$PTR",
257 q=>"QWORD$PTR", o=>"OWORD$PTR",
258 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR",
259 z=>"ZMMWORD$PTR" ) if (!$gas);
262 my ($class, $line, $opcode) = @_;
266 # optional * ----vvv--- appears in indirect jmp/call
267 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) {
269 $self->{asterisk} = $1;
271 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
272 $self->{scale} = 1 if (!defined($self->{scale}));
273 $self->{opmask} = $4;
275 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
277 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
278 die if ($opcode->mnemonic() ne "mov");
279 $opcode->mnemonic("lea");
281 $self->{base} =~ s/^%//;
282 $self->{index} =~ s/^%// if (defined($self->{index}));
283 $self->{opcode} = $opcode;
289 my ($self, $sz) = @_;
291 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
292 $self->{label} =~ s/\.L/$decor/g;
294 # Silently convert all EAs to 64-bit. This is required for
295 # elder GNU assembler and results in more compact code,
296 # *but* most importantly AES module depends on this feature!
297 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
298 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
300 # Solaris /usr/ccs/bin/as can't handle multiplications
301 # in $self->{label}...
303 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
304 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
306 # Some assemblers insist on signed presentation of 32-bit
307 # offsets, but sign extension is a tricky business in perl...
309 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
311 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
314 # if base register is %rbp or %r13, see if it's possible to
315 # flip base and index registers [for better performance]
316 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
317 $self->{base} =~ /(rbp|r13)/) {
318 $self->{base} = $self->{index}; $self->{index} = $1;
322 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
324 if (defined($self->{index})) {
325 sprintf "%s%s(%s,%%%s,%d)%s",
326 $self->{asterisk},$self->{label},
327 $self->{base}?"%$self->{base}":"",
328 $self->{index},$self->{scale},
331 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label},
332 $self->{base},$self->{opmask};
335 $self->{label} =~ s/\./\$/g;
336 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
337 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
339 my $mnemonic = $self->{opcode}->mnemonic();
340 ($self->{asterisk}) && ($sz="q") ||
341 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
342 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
343 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
344 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
346 $self->{opmask} =~ s/%(k[0-7])/$1/;
348 if (defined($self->{index})) {
349 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz},
350 $self->{label}?"$self->{label}+":"",
351 $self->{index},$self->{scale},
352 $self->{base}?"+$self->{base}":"",
354 } elsif ($self->{base} eq "rip") {
355 sprintf "%s[%s]",$szmap{$sz},$self->{label};
357 sprintf "%s[%s%s]%s", $szmap{$sz},
358 $self->{label}?"$self->{label}+":"",
359 $self->{base},$self->{opmask};
364 { package register; # pick up registers, which start with %.
366 my ($class, $line, $opcode) = @_;
370 # optional * ----vvv--- appears in indirect jmp/call
371 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) {
373 $self->{asterisk} = $1;
375 $self->{opmask} = $3;
376 $opcode->size($self->size());
378 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
386 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
387 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
388 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
389 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
390 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
391 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
392 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
393 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
399 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk},
402 else { $self->{opmask} =~ s/%(k[0-7])/$1/;
403 $self->{value}.$self->{opmask}; }
406 { package label; # pick up labels, which end with :
408 my ($class, $line) = @_;
412 if ($$line =~ /(^[\.\w]+)\:/) {
416 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
418 $self->{value} =~ s/^\.L/$decor/;
426 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
427 if ($win64 && $current_function->{name} eq $self->{value}
428 && $current_function->{abi} eq "svr4") {
430 $func .= " movq %rdi,8(%rsp)\n";
431 $func .= " movq %rsi,16(%rsp)\n";
432 $func .= " movq %rsp,%rax\n";
433 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
434 my $narg = $current_function->{narg};
435 $narg=6 if (!defined($narg));
436 $func .= " movq %rcx,%rdi\n" if ($narg>0);
437 $func .= " movq %rdx,%rsi\n" if ($narg>1);
438 $func .= " movq %r8,%rdx\n" if ($narg>2);
439 $func .= " movq %r9,%rcx\n" if ($narg>3);
440 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
441 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
444 } elsif ($self->{value} ne "$current_function->{name}") {
445 # Make all labels in masm global.
446 $self->{value} .= ":" if ($masm);
447 $self->{value} . ":";
448 } elsif ($win64 && $current_function->{abi} eq "svr4") {
449 my $func = "$current_function->{name}" .
450 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
452 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
453 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
454 $func .= " mov rax,rsp\n";
455 $func .= "${decor}SEH_begin_$current_function->{name}:";
456 $func .= ":" if ($masm);
458 my $narg = $current_function->{narg};
459 $narg=6 if (!defined($narg));
460 $func .= " mov rdi,rcx\n" if ($narg>0);
461 $func .= " mov rsi,rdx\n" if ($narg>1);
462 $func .= " mov rdx,r8\n" if ($narg>2);
463 $func .= " mov rcx,r9\n" if ($narg>3);
464 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
465 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
468 "$current_function->{name}".
469 ($nasm ? ":" : "\tPROC $current_function->{scope}");
473 { package expr; # pick up expressions
475 my ($class, $line, $opcode) = @_;
479 if ($$line =~ /(^[^,]+)/) {
483 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
485 $self->{value} =~ s/\@PLT// if (!$elf);
486 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
487 $self->{value} =~ s/\.L/$decor/g;
488 $self->{opcode} = $opcode;
494 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
495 "NEAR ".$self->{value};
501 { package cfi_directive;
502 # CFI directives annotate instructions that are significant for
503 # stack unwinding procedure compliant with DWARF specification,
504 # see http://dwarfstd.org/. Besides naturally expected for this
505 # script platform-specific filtering function, this module adds
506 # three auxiliary synthetic directives not recognized by [GNU]
509 # - .cfi_push to annotate push instructions in prologue, which
510 # translates to .cfi_adjust_cfa_offset (if needed) and
512 # - .cfi_pop to annotate pop instructions in epilogue, which
513 # translates to .cfi_adjust_cfa_offset (if needed) and
515 # - [and most notably] .cfi_cfa_expression which encodes
516 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as
519 # CFA expressions were introduced in DWARF specification version
520 # 3 and describe how to deduce CFA, Canonical Frame Address. This
521 # becomes handy if your stack frame is variable and you can't
522 # spare register for [previous] frame pointer. Suggested directive
523 # syntax is made-up mix of DWARF operator suffixes [subset of]
524 # and references to registers with optional bias. Following example
525 # describes offloaded *original* stack pointer at specific offset
526 # from *current* stack pointer:
528 # .cfi_cfa_expression %rsp+40,deref,+8
530 # Final +8 has everything to do with the fact that CFA is defined
531 # as reference to top of caller's stack, and on x86_64 call to
532 # subroutine pushes 8-byte return address. In other words original
533 # stack pointer upon entry to a subroutine is 8 bytes off from CFA.
535 # Below constants are taken from "DWARF Expressions" section of the
536 # DWARF specification, section is numbered 7.7 in versions 3 and 4.
537 my %DW_OP_simple = ( # no-arg operators, mapped directly
538 deref => 0x06, dup => 0x12,
539 drop => 0x13, over => 0x14,
540 pick => 0x15, swap => 0x16,
541 rot => 0x17, xderef => 0x18,
543 abs => 0x19, and => 0x1a,
544 div => 0x1b, minus => 0x1c,
545 mod => 0x1d, mul => 0x1e,
546 neg => 0x1f, not => 0x20,
547 or => 0x21, plus => 0x22,
548 shl => 0x24, shr => 0x25,
549 shra => 0x26, xor => 0x27,
552 my %DW_OP_complex = ( # used in specific subroutines
553 constu => 0x10, # uleb128
554 consts => 0x11, # sleb128
555 plus_uconst => 0x23, # uleb128
556 lit0 => 0x30, # add 0-31 to opcode
557 reg0 => 0x50, # add 0-31 to opcode
558 breg0 => 0x70, # add 0-31 to opcole, sleb128
559 regx => 0x90, # uleb28
560 fbreg => 0x91, # sleb128
561 bregx => 0x92, # uleb128, sleb128
562 piece => 0x93, # uleb128
565 # Following constants are defined in x86_64 ABI supplement, for
566 # example available at https://www.uclibc.org/docs/psABI-x86_64.pdf,
567 # see section 3.7 "Stack Unwind Algorithm".
569 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3,
570 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7,
571 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11,
572 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15
575 my ($cfa_reg, $cfa_rsp);
578 # [us]leb128 format is variable-length integer representation base
579 # 2^128, with most significant bit of each byte being 0 denoting
580 # *last* most significant digit. See "Variable Length Data" in the
581 # DWARF specification, numbered 7.6 at least in versions 3 and 4.
583 use integer; # get right shift extend sign
586 my $sign = ($val < 0) ? -1 : 0;
590 push @ret, $val&0x7f;
592 # see if remaining bits are same and equal to most
593 # significant bit of the current digit, if so, it's
595 last if (($val>>6) == $sign);
608 push @ret, $val&0x7f;
610 # see if it's last significant digit...
611 last if (($val >>= 7) == 0);
621 if ($val >= 0 && $val < 32) {
622 return ($DW_OP_complex{lit0}+$val);
624 return ($DW_OP_complex{consts}, sleb128($val));
629 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/);
631 my $reg = $DW_reg_idx{$1};
632 my $off = eval ("0 $2 $3");
634 return (($DW_OP_complex{breg0} + $reg), sleb128($off));
635 # Yes, we use DW_OP_bregX+0 to push register value and not
636 # DW_OP_regX, because latter would require even DW_OP_piece,
637 # which would be a waste under the circumstances. If you have
638 # to use DWP_OP_reg, use "regx:N"...
644 foreach my $token (split(/,\s*/,$line)) {
645 if ($token =~ /^%r/) {
646 push @ret,reg($token);
647 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) {
648 push @ret,reg("$2+$1");
649 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) {
651 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i));
652 } elsif (my $i = 1*eval($token) or $token eq "0") {
653 if ($token =~ /^\+/) {
654 push @ret,$DW_OP_complex{plus_uconst},uleb128($i);
659 push @ret,$DW_OP_simple{$token};
663 # Finally we return DW_CFA_def_cfa_expression, 15, followed by
664 # length of the expression and of course the expression itself.
665 return (15,scalar(@ret),@ret);
668 my ($class, $line) = @_;
672 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) {
675 undef $self->{value};
679 # What is $cfa_rsp? Effectively it's difference between %rsp
680 # value and current CFA, Canonical Frame Address, which is
681 # why it starts with -8. Recall that CFA is top of caller's
683 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; };
684 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0);
685 # .cfi_remember_state directives that are not
686 # matched with .cfi_restore_state are
688 die "unpaired .cfi_remember_state" if (@cfa_stack);
692 && do { $cfa_reg = $$line; last; };
694 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
698 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
701 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
703 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
707 /push/ && do { $dir = undef;
709 if ($cfa_reg eq "%rsp") {
710 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
712 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
715 /pop/ && do { $dir = undef;
717 if ($cfa_reg eq "%rsp") {
718 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
720 $self->{value} .= ".cfi_restore\t$$line";
724 && do { $dir = undef;
725 $self->{value} = ".cfi_escape\t" .
726 join(",", map(sprintf("0x%02x", $_),
727 cfa_expression($$line)));
731 && do { push @cfa_stack, [$cfa_reg, $cfa_rsp];
735 && do { ($cfa_reg, $cfa_rsp) = @{pop @cfa_stack};
740 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
749 return ($elf ? $self->{value} : undef);
752 { package directive; # pick up directives, which start with .
754 my ($class, $line) = @_;
759 # chain-call to cfi_directive
760 $ret = cfi_directive->re($line) and return $ret;
762 if ($$line =~ /^\s*(\.\w+)/) {
766 undef $self->{value};
767 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
770 /\.global|\.globl|\.extern/
771 && do { $globals{$$line} = $prefix . $$line;
772 $$line = $globals{$$line} if ($prefix);
775 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
776 if ($type eq "\@function") {
777 undef $current_function;
778 $current_function->{name} = $sym;
779 $current_function->{abi} = "svr4";
780 $current_function->{narg} = $narg;
781 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
782 } elsif ($type eq "\@abi-omnipotent") {
783 undef $current_function;
784 $current_function->{name} = $sym;
785 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
787 $$line =~ s/\@abi\-omnipotent/\@function/;
788 $$line =~ s/\@function.*/\@function/;
791 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
793 $$line = join(",",unpack("C*",$1),0);
797 /\.rva|\.long|\.quad/
798 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
799 $$line =~ s/\.L/$decor/g;
805 $self->{value} = $dir . "\t" . $$line;
807 if ($dir =~ /\.extern/) {
808 $self->{value} = ""; # swallow extern
809 } elsif (!$elf && $dir =~ /\.type/) {
811 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
812 (defined($globals{$1})?".scl 2;":".scl 3;") .
813 "\t.type 32;\t.endef"
814 if ($win64 && $$line =~ /([^,]+),\@function/);
815 } elsif (!$elf && $dir =~ /\.size/) {
817 if (defined($current_function)) {
818 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
819 if ($win64 && $current_function->{abi} eq "svr4");
820 undef $current_function;
822 } elsif (!$elf && $dir =~ /\.align/) {
823 $self->{value} = ".p2align\t" . (log($$line)/log(2));
824 } elsif ($dir eq ".section") {
825 $current_segment=$$line;
826 if (!$elf && $current_segment eq ".init") {
827 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
828 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
830 } elsif ($dir =~ /\.(text|data)/) {
831 $current_segment=".$1";
832 } elsif ($dir =~ /\.hidden/) {
833 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
834 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
835 } elsif ($dir =~ /\.comm/) {
836 $self->{value} = "$dir\t$prefix$$line";
837 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
843 # non-gas case or nasm/masm
845 /\.text/ && do { my $v=undef;
847 $v="section .text code align=64\n";
849 $v="$current_segment\tENDS\n" if ($current_segment);
850 $current_segment = ".text\$";
851 $v.="$current_segment\tSEGMENT ";
852 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
858 /\.data/ && do { my $v=undef;
860 $v="section .data data align=8\n";
862 $v="$current_segment\tENDS\n" if ($current_segment);
863 $current_segment = "_DATA";
864 $v.="$current_segment\tSEGMENT";
869 /\.section/ && do { my $v=undef;
870 $$line =~ s/([^,]*).*/$1/;
871 $$line = ".CRT\$XCU" if ($$line eq ".init");
874 if ($$line=~/\.([px])data/) {
876 $v.=$1 eq "p"? 4 : 8;
877 } elsif ($$line=~/\.CRT\$/i) {
878 $v.=" rdata align=8";
881 $v="$current_segment\tENDS\n" if ($current_segment);
882 $v.="$$line\tSEGMENT";
883 if ($$line=~/\.([px])data/) {
885 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
886 } elsif ($$line=~/\.CRT\$/i) {
888 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
891 $current_segment = $$line;
895 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
896 $self->{value} .= ":NEAR" if ($masm);
900 && do { $self->{value} = $masm?"PUBLIC":"global";
901 $self->{value} .= "\t".$$line;
904 /\.size/ && do { if (defined($current_function)) {
905 undef $self->{value};
906 if ($current_function->{abi} eq "svr4") {
907 $self->{value}="${decor}SEH_end_$current_function->{name}:";
908 $self->{value}.=":\n" if($masm);
910 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
911 undef $current_function;
915 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
916 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
919 /\.(value|long|rva|quad)/
920 && do { my $sz = substr($1,0,1);
921 my @arr = split(/,\s*/,$$line);
922 my $last = pop(@arr);
923 my $conv = sub { my $var=shift;
924 $var=~s/^(0b[0-1]+)/oct($1)/eig;
925 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
926 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
927 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
931 $sz =~ tr/bvlrq/BWDDQ/;
932 $self->{value} = "\tD$sz\t";
933 for (@arr) { $self->{value} .= &$conv($_).","; }
934 $self->{value} .= &$conv($last);
937 /\.byte/ && do { my @str=split(/,\s*/,$$line);
938 map(s/(0b[0-1]+)/oct($1)/eig,@str);
939 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
941 $self->{value}.="DB\t"
942 .join(",",@str[0..15])."\n";
943 foreach (0..15) { shift @str; }
945 $self->{value}.="DB\t"
946 .join(",",@str) if (@str);
949 /\.comm/ && do { my @str=split(/,\s*/,$$line);
952 $v.="common $prefix@str[0] @str[1]";
954 $v="$current_segment\tENDS\n" if ($current_segment);
955 $current_segment = "_DATA";
956 $v.="$current_segment\tSEGMENT\n";
957 $v.="COMM @str[0]:DWORD:".@str[1]/4;
974 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
975 # yet. In order not to be bothered by tracing exact assembler versions,
976 # but at the same time to provide a bare security minimum of AES-NI, we
977 # hard-code some instructions. Extensions past AES-NI on the other hand
978 # are traced by examining assembler version in individual perlasm
981 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
982 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
986 my ($dst,$src,$rex)=@_;
988 $rex|=0x04 if($dst>=8);
989 $rex|=0x01 if($src>=8);
990 push @$opcode,($rex|0x40) if ($rex);
993 my $movq = sub { # elderly gas can't handle inter-register movq
996 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
997 my ($src,$dst)=($1,$2);
998 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
999 rex(\@opcode,$src,$dst,0x8);
1000 push @opcode,0x0f,0x7e;
1001 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1003 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
1004 my ($src,$dst)=($2,$1);
1005 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1006 rex(\@opcode,$src,$dst,0x8);
1007 push @opcode,0x0f,0x6e;
1008 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1016 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
1021 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
1022 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
1023 rex(\@opcode,$src,$dst);
1024 push @opcode,0x0f,0x3a,0x16;
1025 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1034 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
1039 if ($src =~ /%r([0-9]+)/) { $src = $1; }
1040 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
1041 rex(\@opcode,$dst,$src);
1042 push @opcode,0x0f,0x3a,0x22;
1043 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1052 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1054 rex(\@opcode,$2,$1);
1055 push @opcode,0x0f,0x38,0x00;
1056 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1064 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1066 rex(\@opcode,$3,$2);
1067 push @opcode,0x0f,0x3a,0x0f;
1068 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1076 my $pclmulqdq = sub {
1077 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1079 rex(\@opcode,$3,$2);
1080 push @opcode,0x0f,0x3a,0x44;
1081 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1083 push @opcode,$c=~/^0/?oct($c):$c;
1091 if (shift =~ /%[er](\w+)/) {
1094 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1095 rex(\@opcode,0,$dst,8);
1096 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1104 if (shift =~ /%[er](\w+)/) {
1107 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1108 rex(\@opcode,0,$dst,8);
1109 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1116 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1117 # are using only two instructions hand-code them in order to be excused
1118 # from chasing assembler versions...
1122 my ($dst,$src1,$src2,$rxb)=@_;
1125 $rxb&=~(0x04<<5) if($dst>=8);
1126 $rxb&=~(0x01<<5) if($src1>=8);
1127 $rxb&=~(0x02<<5) if($src2>=8);
1132 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1134 rxb(\@opcode,$3,$2,-1,0x08);
1135 push @opcode,0x78,0xc2;
1136 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1138 push @opcode,$c=~/^0/?oct($c):$c;
1146 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1148 rxb(\@opcode,$3,$2,-1,0x08);
1149 push @opcode,0x78,0xc3;
1150 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1152 push @opcode,$c=~/^0/?oct($c):$c;
1159 # Intel Control-flow Enforcement Technology extension. All functions and
1160 # indirect branch targets will have to start with this instruction...
1162 my $endbranch = sub {
1163 (0xf3,0x0f,0x1e,0xfa);
1166 ########################################################################
1180 while(defined(my $line=<>)) {
1182 $line =~ s|\R$||; # Better chomp
1184 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1185 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1186 $line =~ s|^\s+||; # ... and skip white spaces in beginning
1187 $line =~ s|\s+$||; # ... and at the end
1189 if (my $label=label->re(\$line)) { print $label->out(); }
1191 if (my $directive=directive->re(\$line)) {
1192 printf "%s",$directive->out();
1193 } elsif (my $opcode=opcode->re(\$line)) {
1194 my $asm = eval("\$".$opcode->mnemonic());
1196 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1197 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1202 ARGUMENT: while (1) {
1205 ($arg=register->re(\$line, $opcode))||
1206 ($arg=const->re(\$line)) ||
1207 ($arg=ea->re(\$line, $opcode)) ||
1208 ($arg=expr->re(\$line, $opcode)) ||
1213 last ARGUMENT if ($line !~ /^,/);
1220 my $sz=$opcode->size();
1223 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1224 @args = map($_->out($sz),@args);
1225 printf "\t%s\t%s",$insn,join(",",@args);
1227 $insn = $opcode->out();
1229 my $arg = $_->out();
1230 # $insn.=$sz compensates for movq, pinsrw, ...
1231 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1232 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1233 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1234 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1236 @args = reverse(@args);
1237 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1238 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1241 printf "\t%s",$opcode->out();
1248 print "$cet_property" if ($cet_property);
1249 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1250 print "END\n" if ($masm);
1252 close STDOUT or die "error closing STDOUT: $!;"
1254 \f#################################################
1255 # Cross-reference x86_64 ABI "card"
1275 # (*) volatile register
1276 # (-) preserved by callee
1277 # (#) Nth argument, volatile
1279 # In Unix terms top of stack is argument transfer area for arguments
1280 # which could not be accommodated in registers. Or in other words 7th
1281 # [integer] argument resides at 8(%rsp) upon function entry point.
1282 # 128 bytes above %rsp constitute a "red zone" which is not touched
1283 # by signal handlers and can be used as temporal storage without
1284 # allocating a frame.
1286 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1287 # which belongs to/can be overwritten by callee. N is the number of
1288 # arguments passed to callee, *but* not less than 4! This means that
1289 # upon function entry point 5th argument resides at 40(%rsp), as well
1290 # as that 32 bytes from 8(%rsp) can always be used as temporal
1291 # storage [without allocating a frame]. One can actually argue that
1292 # one can assume a "red zone" above stack pointer under Win64 as well.
1293 # Point is that at apparently no occasion Windows kernel would alter
1294 # the area above user stack pointer in true asynchronous manner...
1296 # All the above means that if assembler programmer adheres to Unix
1297 # register and stack layout, but disregards the "red zone" existence,
1298 # it's possible to use following prologue and epilogue to "gear" from
1299 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1301 # omnipotent_function:
1304 # movq %rsi,16(%rsp)
1305 # movq %rcx,%rdi ; if 1st argument is actually present
1306 # movq %rdx,%rsi ; if 2nd argument is actually ...
1307 # movq %r8,%rdx ; if 3rd argument is ...
1308 # movq %r9,%rcx ; if 4th argument ...
1309 # movq 40(%rsp),%r8 ; if 5th ...
1310 # movq 48(%rsp),%r9 ; if 6th ...
1315 # movq 16(%rsp),%rsi
1319 \f#################################################
1320 # Win64 SEH, Structured Exception Handling.
1322 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1323 # has undesired side-effect at run-time: if an exception is raised in
1324 # assembler subroutine such as those in question (basically we're
1325 # referring to segmentation violations caused by malformed input
1326 # parameters), the application is briskly terminated without invoking
1327 # any exception handlers, most notably without generating memory dump
1328 # or any user notification whatsoever. This poses a problem. It's
1329 # possible to address it by registering custom language-specific
1330 # handler that would restore processor context to the state at
1331 # subroutine entry point and return "exception is not handled, keep
1332 # unwinding" code. Writing such handler can be a challenge... But it's
1333 # doable, though requires certain coding convention. Consider following
1336 # .type function,@function
1338 # movq %rsp,%rax # copy rsp to volatile register
1339 # pushq %r15 # save non-volatile registers
1343 # subq %rdi,%r11 # prepare [variable] stack frame
1345 # movq %rax,0(%r11) # check for exceptions
1346 # movq %r11,%rsp # allocate [variable] stack frame
1347 # movq %rax,0(%rsp) # save original rsp value
1350 # movq 0(%rsp),%rcx # pull original rsp value
1351 # movq -24(%rcx),%rbp # restore non-volatile registers
1352 # movq -16(%rcx),%rbx
1353 # movq -8(%rcx),%r15
1354 # movq %rcx,%rsp # restore original rsp
1357 # .size function,.-function
1359 # The key is that up to magic_point copy of original rsp value remains
1360 # in chosen volatile register and no non-volatile register, except for
1361 # rsp, is modified. While past magic_point rsp remains constant till
1362 # the very end of the function. In this case custom language-specific
1363 # exception handler would look like this:
1365 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1366 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1367 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1368 # ULONG64 rip = context->Rip;
1370 # if (rip >= magic_point)
1371 # { rsp = (ULONG64 *)context->Rsp;
1372 # if (rip < magic_epilogue)
1373 # { rsp = (ULONG64 *)rsp[0];
1374 # context->Rbp = rsp[-3];
1375 # context->Rbx = rsp[-2];
1376 # context->R15 = rsp[-1];
1379 # context->Rsp = (ULONG64)rsp;
1380 # context->Rdi = rsp[1];
1381 # context->Rsi = rsp[2];
1383 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1384 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1385 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1386 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1387 # return ExceptionContinueSearch;
1390 # It's appropriate to implement this handler in assembler, directly in
1391 # function's module. In order to do that one has to know members'
1392 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1393 # values. Here they are:
1413 # sizeof(CONTEXT) 1232
1414 # DISPATCHER_CONTEXT.ControlPc 0
1415 # DISPATCHER_CONTEXT.ImageBase 8
1416 # DISPATCHER_CONTEXT.FunctionEntry 16
1417 # DISPATCHER_CONTEXT.EstablisherFrame 24
1418 # DISPATCHER_CONTEXT.TargetIp 32
1419 # DISPATCHER_CONTEXT.ContextRecord 40
1420 # DISPATCHER_CONTEXT.LanguageHandler 48
1421 # DISPATCHER_CONTEXT.HandlerData 56
1422 # UNW_FLAG_NHANDLER 0
1423 # ExceptionContinueSearch 1
1425 # In order to tie the handler to the function one has to compose
1426 # couple of structures: one for .xdata segment and one for .pdata.
1428 # UNWIND_INFO structure for .xdata segment would be
1430 # function_unwind_info:
1434 # This structure designates exception handler for a function with
1435 # zero-length prologue, no stack frame or frame register.
1437 # To facilitate composing of .pdata structures, auto-generated "gear"
1438 # prologue copies rsp value to rax and denotes next instruction with
1439 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1440 # styling rule mentioned in the beginning. Position of this label is
1441 # chosen in such manner that possible exceptions raised in the "gear"
1442 # prologue would be accounted to caller and unwound from latter's frame.
1443 # End of function is marked with respective .LSEH_end_{function_name}
1444 # label. To summarize, .pdata segment would contain
1446 # .rva .LSEH_begin_function
1447 # .rva .LSEH_end_function
1448 # .rva function_unwind_info
1450 # Reference to function_unwind_info from .xdata segment is the anchor.
1451 # In case you wonder why references are 32-bit .rvas and not 64-bit
1452 # .quads. References put into these two segments are required to be
1453 # *relative* to the base address of the current binary module, a.k.a.
1454 # image base. No Win64 module, be it .exe or .dll, can be larger than
1455 # 2GB and thus such relative references can be and are accommodated in
1458 # Having reviewed the example function code, one can argue that "movq
1459 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1460 # rax would contain an undefined value. If this "offends" you, use
1461 # another register and refrain from modifying rax till magic_point is
1462 # reached, i.e. as if it was a non-volatile register. If more registers
1463 # are required prior [variable] frame setup is completed, note that
1464 # nobody says that you can have only one "magic point." You can
1465 # "liberate" non-volatile registers by denoting last stack off-load
1466 # instruction and reflecting it in finer grade unwind logic in handler.
1467 # After all, isn't it why it's called *language-specific* handler...
1469 # SE handlers are also involved in unwinding stack when executable is
1470 # profiled or debugged. Profiling implies additional limitations that
1471 # are too subtle to discuss here. For now it's sufficient to say that
1472 # in order to simplify handlers one should either a) offload original
1473 # %rsp to stack (like discussed above); or b) if you have a register to
1474 # spare for frame pointer, choose volatile one.
1476 # (*) Note that we're talking about run-time, not debug-time. Lack of
1477 # unwind information makes debugging hard on both Windows and
1478 # Unix. "Unlike" refers to the fact that on Unix signal handler
1479 # will always be invoked, core dumped and appropriate exit code
1480 # returned to parent (for user notification).