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 # GNU as indicator, as opposed to $gas, which indicates acceptable
90 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
91 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
92 $prefix =~ s|\R$||; # Better chomp
94 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
95 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
96 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
98 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
99 { $nasm = $1 + $2*0.01; $PTR=""; }
100 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
101 { $masm = $1 + $2*2**-16 + $4*2**-32; }
102 die "no assembler found on %PATH%" if (!($nasm || $masm));
107 # Find out if we're using GNU as
108 elsif (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1`
109 =~ /GNU assembler version ([2-9]\.[0-9]+)/)
115 if ($flavour =~ /elf/) {
116 # Always generate .note.gnu.property section for ELF outputs to
117 # mark Intel CET support since all input files must be marked
118 # with Intel CET support in order for linker to mark output with
120 my $p2align=3; $p2align=2 if ($flavour eq "elf32");
121 my $section='.note.gnu.property, #alloc';
122 $section='".note.gnu.property", "a"' if $gnuas;
123 $cet_property = <<_____;
130 # "GNU" encoded with .byte, since .asciz isn't supported
149 my $current_function;
152 { package opcode; # pick up opcodes
154 my ($class, $line) = @_;
158 if ($$line =~ /^([a-z][a-z0-9]*)/i) {
162 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
165 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
168 } elsif ($self->{op} =~ /call|jmp/) {
170 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
172 } elsif ($self->{op} =~ /^[vk]/) { # VEX or k* such as kmov
174 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) {
176 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
184 my ($self, $sz) = @_;
185 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
191 if ($self->{op} eq "movz") { # movz is pain...
192 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
193 } elsif ($self->{op} =~ /^set/) {
195 } elsif ($self->{op} eq "ret") {
197 if ($win64 && $current_function->{abi} eq "svr4") {
198 $epilogue = "movq 8(%rsp),%rdi\n\t" .
199 "movq 16(%rsp),%rsi\n\t";
201 $epilogue . ".byte 0xf3,0xc3";
202 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
203 ".p2align\t3\n\t.quad";
205 "$self->{op}$self->{sz}";
208 $self->{op} =~ s/^movz/movzx/;
209 if ($self->{op} eq "ret") {
211 if ($win64 && $current_function->{abi} eq "svr4") {
212 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t".
213 "mov rsi,QWORD$PTR\[16+rsp\]\n\t";
215 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
216 } elsif ($self->{op} =~ /^(pop|push)f/) {
217 $self->{op} .= $self->{sz};
218 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
219 $self->{op} = "\tDQ";
225 my ($self, $op) = @_;
226 $self->{op}=$op if (defined($op));
230 { package const; # pick up constants, which start with $
232 my ($class, $line) = @_;
236 if ($$line =~ /^\$([^,]+)/) {
240 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
247 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
249 # Solaris /usr/ccs/bin/as can't handle multiplications
251 my $value = $self->{value};
252 no warnings; # oct might complain about overflow, ignore here...
253 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
254 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
255 $self->{value} = $value;
257 sprintf "\$%s",$self->{value};
259 my $value = $self->{value};
260 $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
265 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
267 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
268 l=>"DWORD$PTR", d=>"DWORD$PTR",
269 q=>"QWORD$PTR", o=>"OWORD$PTR",
270 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR",
271 z=>"ZMMWORD$PTR" ) if (!$gas);
274 my ($class, $line, $opcode) = @_;
278 # optional * ----vvv--- appears in indirect jmp/call
279 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) {
281 $self->{asterisk} = $1;
283 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
284 $self->{scale} = 1 if (!defined($self->{scale}));
285 $self->{opmask} = $4;
287 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
289 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
290 die if ($opcode->mnemonic() ne "mov");
291 $opcode->mnemonic("lea");
293 $self->{base} =~ s/^%//;
294 $self->{index} =~ s/^%// if (defined($self->{index}));
295 $self->{opcode} = $opcode;
301 my ($self, $sz) = @_;
303 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
304 $self->{label} =~ s/\.L/$decor/g;
306 # Silently convert all EAs to 64-bit. This is required for
307 # elder GNU assembler and results in more compact code,
308 # *but* most importantly AES module depends on this feature!
309 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
310 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
312 # Solaris /usr/ccs/bin/as can't handle multiplications
313 # in $self->{label}...
315 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
316 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
318 # Some assemblers insist on signed presentation of 32-bit
319 # offsets, but sign extension is a tricky business in perl...
321 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
323 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
326 # if base register is %rbp or %r13, see if it's possible to
327 # flip base and index registers [for better performance]
328 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
329 $self->{base} =~ /(rbp|r13)/) {
330 $self->{base} = $self->{index}; $self->{index} = $1;
334 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
336 if (defined($self->{index})) {
337 sprintf "%s%s(%s,%%%s,%d)%s",
338 $self->{asterisk},$self->{label},
339 $self->{base}?"%$self->{base}":"",
340 $self->{index},$self->{scale},
343 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label},
344 $self->{base},$self->{opmask};
347 $self->{label} =~ s/\./\$/g;
348 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
349 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
351 my $mnemonic = $self->{opcode}->mnemonic();
352 ($self->{asterisk}) && ($sz="q") ||
353 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
354 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
355 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
356 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
358 $self->{opmask} =~ s/%(k[0-7])/$1/;
360 if (defined($self->{index})) {
361 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz},
362 $self->{label}?"$self->{label}+":"",
363 $self->{index},$self->{scale},
364 $self->{base}?"+$self->{base}":"",
366 } elsif ($self->{base} eq "rip") {
367 sprintf "%s[%s]",$szmap{$sz},$self->{label};
369 sprintf "%s[%s%s]%s", $szmap{$sz},
370 $self->{label}?"$self->{label}+":"",
371 $self->{base},$self->{opmask};
376 { package register; # pick up registers, which start with %.
378 my ($class, $line, $opcode) = @_;
382 # optional * ----vvv--- appears in indirect jmp/call
383 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) {
385 $self->{asterisk} = $1;
387 $self->{opmask} = $3;
388 $opcode->size($self->size());
390 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
398 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
399 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
400 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
401 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
402 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
403 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
404 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
405 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
411 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk},
414 else { $self->{opmask} =~ s/%(k[0-7])/$1/;
415 $self->{value}.$self->{opmask}; }
418 { package label; # pick up labels, which end with :
420 my ($class, $line) = @_;
424 if ($$line =~ /(^[\.\w]+)\:/) {
428 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
430 $self->{value} =~ s/^\.L/$decor/;
438 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
439 if ($win64 && $current_function->{name} eq $self->{value}
440 && $current_function->{abi} eq "svr4") {
442 $func .= " movq %rdi,8(%rsp)\n";
443 $func .= " movq %rsi,16(%rsp)\n";
444 $func .= " movq %rsp,%rax\n";
445 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
446 my $narg = $current_function->{narg};
447 $narg=6 if (!defined($narg));
448 $func .= " movq %rcx,%rdi\n" if ($narg>0);
449 $func .= " movq %rdx,%rsi\n" if ($narg>1);
450 $func .= " movq %r8,%rdx\n" if ($narg>2);
451 $func .= " movq %r9,%rcx\n" if ($narg>3);
452 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
453 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
456 } elsif ($self->{value} ne "$current_function->{name}") {
457 # Make all labels in masm global.
458 $self->{value} .= ":" if ($masm);
459 $self->{value} . ":";
460 } elsif ($win64 && $current_function->{abi} eq "svr4") {
461 my $func = "$current_function->{name}" .
462 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
464 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
465 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
466 $func .= " mov rax,rsp\n";
467 $func .= "${decor}SEH_begin_$current_function->{name}:";
468 $func .= ":" if ($masm);
470 my $narg = $current_function->{narg};
471 $narg=6 if (!defined($narg));
472 $func .= " mov rdi,rcx\n" if ($narg>0);
473 $func .= " mov rsi,rdx\n" if ($narg>1);
474 $func .= " mov rdx,r8\n" if ($narg>2);
475 $func .= " mov rcx,r9\n" if ($narg>3);
476 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
477 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
480 "$current_function->{name}".
481 ($nasm ? ":" : "\tPROC $current_function->{scope}");
485 { package expr; # pick up expressions
487 my ($class, $line, $opcode) = @_;
491 if ($$line =~ /(^[^,]+)/) {
495 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
497 $self->{value} =~ s/\@PLT// if (!$elf);
498 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
499 $self->{value} =~ s/\.L/$decor/g;
500 $self->{opcode} = $opcode;
506 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
507 "NEAR ".$self->{value};
513 { package cfi_directive;
514 # CFI directives annotate instructions that are significant for
515 # stack unwinding procedure compliant with DWARF specification,
516 # see http://dwarfstd.org/. Besides naturally expected for this
517 # script platform-specific filtering function, this module adds
518 # three auxiliary synthetic directives not recognized by [GNU]
521 # - .cfi_push to annotate push instructions in prologue, which
522 # translates to .cfi_adjust_cfa_offset (if needed) and
524 # - .cfi_pop to annotate pop instructions in epilogue, which
525 # translates to .cfi_adjust_cfa_offset (if needed) and
527 # - [and most notably] .cfi_cfa_expression which encodes
528 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as
531 # CFA expressions were introduced in DWARF specification version
532 # 3 and describe how to deduce CFA, Canonical Frame Address. This
533 # becomes handy if your stack frame is variable and you can't
534 # spare register for [previous] frame pointer. Suggested directive
535 # syntax is made-up mix of DWARF operator suffixes [subset of]
536 # and references to registers with optional bias. Following example
537 # describes offloaded *original* stack pointer at specific offset
538 # from *current* stack pointer:
540 # .cfi_cfa_expression %rsp+40,deref,+8
542 # Final +8 has everything to do with the fact that CFA is defined
543 # as reference to top of caller's stack, and on x86_64 call to
544 # subroutine pushes 8-byte return address. In other words original
545 # stack pointer upon entry to a subroutine is 8 bytes off from CFA.
547 # Below constants are taken from "DWARF Expressions" section of the
548 # DWARF specification, section is numbered 7.7 in versions 3 and 4.
549 my %DW_OP_simple = ( # no-arg operators, mapped directly
550 deref => 0x06, dup => 0x12,
551 drop => 0x13, over => 0x14,
552 pick => 0x15, swap => 0x16,
553 rot => 0x17, xderef => 0x18,
555 abs => 0x19, and => 0x1a,
556 div => 0x1b, minus => 0x1c,
557 mod => 0x1d, mul => 0x1e,
558 neg => 0x1f, not => 0x20,
559 or => 0x21, plus => 0x22,
560 shl => 0x24, shr => 0x25,
561 shra => 0x26, xor => 0x27,
564 my %DW_OP_complex = ( # used in specific subroutines
565 constu => 0x10, # uleb128
566 consts => 0x11, # sleb128
567 plus_uconst => 0x23, # uleb128
568 lit0 => 0x30, # add 0-31 to opcode
569 reg0 => 0x50, # add 0-31 to opcode
570 breg0 => 0x70, # add 0-31 to opcole, sleb128
571 regx => 0x90, # uleb28
572 fbreg => 0x91, # sleb128
573 bregx => 0x92, # uleb128, sleb128
574 piece => 0x93, # uleb128
577 # Following constants are defined in x86_64 ABI supplement, for
578 # example available at https://www.uclibc.org/docs/psABI-x86_64.pdf,
579 # see section 3.7 "Stack Unwind Algorithm".
581 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3,
582 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7,
583 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11,
584 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15
587 my ($cfa_reg, $cfa_rsp);
590 # [us]leb128 format is variable-length integer representation base
591 # 2^128, with most significant bit of each byte being 0 denoting
592 # *last* most significant digit. See "Variable Length Data" in the
593 # DWARF specification, numbered 7.6 at least in versions 3 and 4.
595 use integer; # get right shift extend sign
598 my $sign = ($val < 0) ? -1 : 0;
602 push @ret, $val&0x7f;
604 # see if remaining bits are same and equal to most
605 # significant bit of the current digit, if so, it's
607 last if (($val>>6) == $sign);
620 push @ret, $val&0x7f;
622 # see if it's last significant digit...
623 last if (($val >>= 7) == 0);
633 if ($val >= 0 && $val < 32) {
634 return ($DW_OP_complex{lit0}+$val);
636 return ($DW_OP_complex{consts}, sleb128($val));
641 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/);
643 my $reg = $DW_reg_idx{$1};
644 my $off = eval ("0 $2 $3");
646 return (($DW_OP_complex{breg0} + $reg), sleb128($off));
647 # Yes, we use DW_OP_bregX+0 to push register value and not
648 # DW_OP_regX, because latter would require even DW_OP_piece,
649 # which would be a waste under the circumstances. If you have
650 # to use DWP_OP_reg, use "regx:N"...
656 foreach my $token (split(/,\s*/,$line)) {
657 if ($token =~ /^%r/) {
658 push @ret,reg($token);
659 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) {
660 push @ret,reg("$2+$1");
661 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) {
663 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i));
664 } elsif (my $i = 1*eval($token) or $token eq "0") {
665 if ($token =~ /^\+/) {
666 push @ret,$DW_OP_complex{plus_uconst},uleb128($i);
671 push @ret,$DW_OP_simple{$token};
675 # Finally we return DW_CFA_def_cfa_expression, 15, followed by
676 # length of the expression and of course the expression itself.
677 return (15,scalar(@ret),@ret);
680 my ($class, $line) = @_;
684 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) {
687 undef $self->{value};
691 # What is $cfa_rsp? Effectively it's difference between %rsp
692 # value and current CFA, Canonical Frame Address, which is
693 # why it starts with -8. Recall that CFA is top of caller's
695 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; };
696 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0);
697 # .cfi_remember_state directives that are not
698 # matched with .cfi_restore_state are
700 die "unpaired .cfi_remember_state" if (@cfa_stack);
704 && do { $cfa_reg = $$line; last; };
706 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
710 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
713 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
715 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
719 /push/ && do { $dir = undef;
721 if ($cfa_reg eq "%rsp") {
722 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
724 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
727 /pop/ && do { $dir = undef;
729 if ($cfa_reg eq "%rsp") {
730 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
732 $self->{value} .= ".cfi_restore\t$$line";
736 && do { $dir = undef;
737 $self->{value} = ".cfi_escape\t" .
738 join(",", map(sprintf("0x%02x", $_),
739 cfa_expression($$line)));
743 && do { push @cfa_stack, [$cfa_reg, $cfa_rsp];
747 && do { ($cfa_reg, $cfa_rsp) = @{pop @cfa_stack};
752 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
761 return ($elf ? $self->{value} : undef);
764 { package directive; # pick up directives, which start with .
766 my ($class, $line) = @_;
771 # chain-call to cfi_directive
772 $ret = cfi_directive->re($line) and return $ret;
774 if ($$line =~ /^\s*(\.\w+)/) {
778 undef $self->{value};
779 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
782 /\.global|\.globl|\.extern/
783 && do { $globals{$$line} = $prefix . $$line;
784 $$line = $globals{$$line} if ($prefix);
787 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
788 if ($type eq "\@function") {
789 undef $current_function;
790 $current_function->{name} = $sym;
791 $current_function->{abi} = "svr4";
792 $current_function->{narg} = $narg;
793 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
794 } elsif ($type eq "\@abi-omnipotent") {
795 undef $current_function;
796 $current_function->{name} = $sym;
797 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
799 $$line =~ s/\@abi\-omnipotent/\@function/;
800 $$line =~ s/\@function.*/\@function/;
803 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
805 $$line = join(",",unpack("C*",$1),0);
809 /\.rva|\.long|\.quad/
810 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
811 $$line =~ s/\.L/$decor/g;
817 $self->{value} = $dir . "\t" . $$line;
819 if ($dir =~ /\.extern/) {
820 $self->{value} = ""; # swallow extern
821 } elsif (!$elf && $dir =~ /\.type/) {
823 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
824 (defined($globals{$1})?".scl 2;":".scl 3;") .
825 "\t.type 32;\t.endef"
826 if ($win64 && $$line =~ /([^,]+),\@function/);
827 } elsif (!$elf && $dir =~ /\.size/) {
829 if (defined($current_function)) {
830 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
831 if ($win64 && $current_function->{abi} eq "svr4");
832 undef $current_function;
834 } elsif (!$elf && $dir =~ /\.align/) {
835 $self->{value} = ".p2align\t" . (log($$line)/log(2));
836 } elsif ($dir eq ".section") {
837 $current_segment=$$line;
838 if (!$elf && $current_segment eq ".init") {
839 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
840 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
842 } elsif ($dir =~ /\.(text|data)/) {
843 $current_segment=".$1";
844 } elsif ($dir =~ /\.hidden/) {
845 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
846 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
847 } elsif ($dir =~ /\.comm/) {
848 $self->{value} = "$dir\t$prefix$$line";
849 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
855 # non-gas case or nasm/masm
857 /\.text/ && do { my $v=undef;
859 $v="section .text code align=64\n";
861 $v="$current_segment\tENDS\n" if ($current_segment);
862 $current_segment = ".text\$";
863 $v.="$current_segment\tSEGMENT ";
864 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
870 /\.data/ && do { my $v=undef;
872 $v="section .data data align=8\n";
874 $v="$current_segment\tENDS\n" if ($current_segment);
875 $current_segment = "_DATA";
876 $v.="$current_segment\tSEGMENT";
881 /\.section/ && do { my $v=undef;
882 $$line =~ s/([^,]*).*/$1/;
883 $$line = ".CRT\$XCU" if ($$line eq ".init");
886 if ($$line=~/\.([px])data/) {
888 $v.=$1 eq "p"? 4 : 8;
889 } elsif ($$line=~/\.CRT\$/i) {
890 $v.=" rdata align=8";
893 $v="$current_segment\tENDS\n" if ($current_segment);
894 $v.="$$line\tSEGMENT";
895 if ($$line=~/\.([px])data/) {
897 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
898 } elsif ($$line=~/\.CRT\$/i) {
900 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
903 $current_segment = $$line;
907 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
908 $self->{value} .= ":NEAR" if ($masm);
912 && do { $self->{value} = $masm?"PUBLIC":"global";
913 $self->{value} .= "\t".$$line;
916 /\.size/ && do { if (defined($current_function)) {
917 undef $self->{value};
918 if ($current_function->{abi} eq "svr4") {
919 $self->{value}="${decor}SEH_end_$current_function->{name}:";
920 $self->{value}.=":\n" if($masm);
922 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
923 undef $current_function;
927 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
928 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
931 /\.(value|long|rva|quad)/
932 && do { my $sz = substr($1,0,1);
933 my @arr = split(/,\s*/,$$line);
934 my $last = pop(@arr);
935 my $conv = sub { my $var=shift;
936 $var=~s/^(0b[0-1]+)/oct($1)/eig;
937 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
938 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
939 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
943 $sz =~ tr/bvlrq/BWDDQ/;
944 $self->{value} = "\tD$sz\t";
945 for (@arr) { $self->{value} .= &$conv($_).","; }
946 $self->{value} .= &$conv($last);
949 /\.byte/ && do { my @str=split(/,\s*/,$$line);
950 map(s/(0b[0-1]+)/oct($1)/eig,@str);
951 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
953 $self->{value}.="DB\t"
954 .join(",",@str[0..15])."\n";
955 foreach (0..15) { shift @str; }
957 $self->{value}.="DB\t"
958 .join(",",@str) if (@str);
961 /\.comm/ && do { my @str=split(/,\s*/,$$line);
964 $v.="common $prefix@str[0] @str[1]";
966 $v="$current_segment\tENDS\n" if ($current_segment);
967 $current_segment = "_DATA";
968 $v.="$current_segment\tSEGMENT\n";
969 $v.="COMM @str[0]:DWORD:".@str[1]/4;
986 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
987 # yet. In order not to be bothered by tracing exact assembler versions,
988 # but at the same time to provide a bare security minimum of AES-NI, we
989 # hard-code some instructions. Extensions past AES-NI on the other hand
990 # are traced by examining assembler version in individual perlasm
993 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
994 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
998 my ($dst,$src,$rex)=@_;
1000 $rex|=0x04 if($dst>=8);
1001 $rex|=0x01 if($src>=8);
1002 push @$opcode,($rex|0x40) if ($rex);
1005 my $movq = sub { # elderly gas can't handle inter-register movq
1008 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
1009 my ($src,$dst)=($1,$2);
1010 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1011 rex(\@opcode,$src,$dst,0x8);
1012 push @opcode,0x0f,0x7e;
1013 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1015 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
1016 my ($src,$dst)=($2,$1);
1017 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1018 rex(\@opcode,$src,$dst,0x8);
1019 push @opcode,0x0f,0x6e;
1020 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1028 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
1033 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
1034 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
1035 rex(\@opcode,$src,$dst);
1036 push @opcode,0x0f,0x3a,0x16;
1037 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1046 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
1051 if ($src =~ /%r([0-9]+)/) { $src = $1; }
1052 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
1053 rex(\@opcode,$dst,$src);
1054 push @opcode,0x0f,0x3a,0x22;
1055 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1064 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1066 rex(\@opcode,$2,$1);
1067 push @opcode,0x0f,0x38,0x00;
1068 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1076 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1078 rex(\@opcode,$3,$2);
1079 push @opcode,0x0f,0x3a,0x0f;
1080 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1088 my $pclmulqdq = sub {
1089 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1091 rex(\@opcode,$3,$2);
1092 push @opcode,0x0f,0x3a,0x44;
1093 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1095 push @opcode,$c=~/^0/?oct($c):$c;
1103 if (shift =~ /%[er](\w+)/) {
1106 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1107 rex(\@opcode,0,$dst,8);
1108 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1116 if (shift =~ /%[er](\w+)/) {
1119 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1120 rex(\@opcode,0,$dst,8);
1121 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1128 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1129 # are using only two instructions hand-code them in order to be excused
1130 # from chasing assembler versions...
1134 my ($dst,$src1,$src2,$rxb)=@_;
1137 $rxb&=~(0x04<<5) if($dst>=8);
1138 $rxb&=~(0x01<<5) if($src1>=8);
1139 $rxb&=~(0x02<<5) if($src2>=8);
1144 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1146 rxb(\@opcode,$3,$2,-1,0x08);
1147 push @opcode,0x78,0xc2;
1148 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1150 push @opcode,$c=~/^0/?oct($c):$c;
1158 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1160 rxb(\@opcode,$3,$2,-1,0x08);
1161 push @opcode,0x78,0xc3;
1162 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1164 push @opcode,$c=~/^0/?oct($c):$c;
1171 # Intel Control-flow Enforcement Technology extension. All functions and
1172 # indirect branch targets will have to start with this instruction...
1174 my $endbranch = sub {
1175 (0xf3,0x0f,0x1e,0xfa);
1178 ########################################################################
1192 while(defined(my $line=<>)) {
1194 $line =~ s|\R$||; # Better chomp
1196 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1197 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1198 $line =~ s|^\s+||; # ... and skip white spaces in beginning
1199 $line =~ s|\s+$||; # ... and at the end
1201 if (my $label=label->re(\$line)) { print $label->out(); }
1203 if (my $directive=directive->re(\$line)) {
1204 printf "%s",$directive->out();
1205 } elsif (my $opcode=opcode->re(\$line)) {
1206 my $asm = eval("\$".$opcode->mnemonic());
1208 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1209 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1214 ARGUMENT: while (1) {
1217 ($arg=register->re(\$line, $opcode))||
1218 ($arg=const->re(\$line)) ||
1219 ($arg=ea->re(\$line, $opcode)) ||
1220 ($arg=expr->re(\$line, $opcode)) ||
1225 last ARGUMENT if ($line !~ /^,/);
1232 my $sz=$opcode->size();
1235 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1236 @args = map($_->out($sz),@args);
1237 printf "\t%s\t%s",$insn,join(",",@args);
1239 $insn = $opcode->out();
1241 my $arg = $_->out();
1242 # $insn.=$sz compensates for movq, pinsrw, ...
1243 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1244 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1245 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1246 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1248 @args = reverse(@args);
1249 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1250 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1253 printf "\t%s",$opcode->out();
1260 print "$cet_property" if ($cet_property);
1261 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1262 print "END\n" if ($masm);
1264 close STDOUT or die "error closing STDOUT: $!;"
1266 \f#################################################
1267 # Cross-reference x86_64 ABI "card"
1287 # (*) volatile register
1288 # (-) preserved by callee
1289 # (#) Nth argument, volatile
1291 # In Unix terms top of stack is argument transfer area for arguments
1292 # which could not be accommodated in registers. Or in other words 7th
1293 # [integer] argument resides at 8(%rsp) upon function entry point.
1294 # 128 bytes above %rsp constitute a "red zone" which is not touched
1295 # by signal handlers and can be used as temporal storage without
1296 # allocating a frame.
1298 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1299 # which belongs to/can be overwritten by callee. N is the number of
1300 # arguments passed to callee, *but* not less than 4! This means that
1301 # upon function entry point 5th argument resides at 40(%rsp), as well
1302 # as that 32 bytes from 8(%rsp) can always be used as temporal
1303 # storage [without allocating a frame]. One can actually argue that
1304 # one can assume a "red zone" above stack pointer under Win64 as well.
1305 # Point is that at apparently no occasion Windows kernel would alter
1306 # the area above user stack pointer in true asynchronous manner...
1308 # All the above means that if assembler programmer adheres to Unix
1309 # register and stack layout, but disregards the "red zone" existence,
1310 # it's possible to use following prologue and epilogue to "gear" from
1311 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1313 # omnipotent_function:
1316 # movq %rsi,16(%rsp)
1317 # movq %rcx,%rdi ; if 1st argument is actually present
1318 # movq %rdx,%rsi ; if 2nd argument is actually ...
1319 # movq %r8,%rdx ; if 3rd argument is ...
1320 # movq %r9,%rcx ; if 4th argument ...
1321 # movq 40(%rsp),%r8 ; if 5th ...
1322 # movq 48(%rsp),%r9 ; if 6th ...
1327 # movq 16(%rsp),%rsi
1331 \f#################################################
1332 # Win64 SEH, Structured Exception Handling.
1334 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1335 # has undesired side-effect at run-time: if an exception is raised in
1336 # assembler subroutine such as those in question (basically we're
1337 # referring to segmentation violations caused by malformed input
1338 # parameters), the application is briskly terminated without invoking
1339 # any exception handlers, most notably without generating memory dump
1340 # or any user notification whatsoever. This poses a problem. It's
1341 # possible to address it by registering custom language-specific
1342 # handler that would restore processor context to the state at
1343 # subroutine entry point and return "exception is not handled, keep
1344 # unwinding" code. Writing such handler can be a challenge... But it's
1345 # doable, though requires certain coding convention. Consider following
1348 # .type function,@function
1350 # movq %rsp,%rax # copy rsp to volatile register
1351 # pushq %r15 # save non-volatile registers
1355 # subq %rdi,%r11 # prepare [variable] stack frame
1357 # movq %rax,0(%r11) # check for exceptions
1358 # movq %r11,%rsp # allocate [variable] stack frame
1359 # movq %rax,0(%rsp) # save original rsp value
1362 # movq 0(%rsp),%rcx # pull original rsp value
1363 # movq -24(%rcx),%rbp # restore non-volatile registers
1364 # movq -16(%rcx),%rbx
1365 # movq -8(%rcx),%r15
1366 # movq %rcx,%rsp # restore original rsp
1369 # .size function,.-function
1371 # The key is that up to magic_point copy of original rsp value remains
1372 # in chosen volatile register and no non-volatile register, except for
1373 # rsp, is modified. While past magic_point rsp remains constant till
1374 # the very end of the function. In this case custom language-specific
1375 # exception handler would look like this:
1377 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1378 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1379 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1380 # ULONG64 rip = context->Rip;
1382 # if (rip >= magic_point)
1383 # { rsp = (ULONG64 *)context->Rsp;
1384 # if (rip < magic_epilogue)
1385 # { rsp = (ULONG64 *)rsp[0];
1386 # context->Rbp = rsp[-3];
1387 # context->Rbx = rsp[-2];
1388 # context->R15 = rsp[-1];
1391 # context->Rsp = (ULONG64)rsp;
1392 # context->Rdi = rsp[1];
1393 # context->Rsi = rsp[2];
1395 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1396 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1397 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1398 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1399 # return ExceptionContinueSearch;
1402 # It's appropriate to implement this handler in assembler, directly in
1403 # function's module. In order to do that one has to know members'
1404 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1405 # values. Here they are:
1425 # sizeof(CONTEXT) 1232
1426 # DISPATCHER_CONTEXT.ControlPc 0
1427 # DISPATCHER_CONTEXT.ImageBase 8
1428 # DISPATCHER_CONTEXT.FunctionEntry 16
1429 # DISPATCHER_CONTEXT.EstablisherFrame 24
1430 # DISPATCHER_CONTEXT.TargetIp 32
1431 # DISPATCHER_CONTEXT.ContextRecord 40
1432 # DISPATCHER_CONTEXT.LanguageHandler 48
1433 # DISPATCHER_CONTEXT.HandlerData 56
1434 # UNW_FLAG_NHANDLER 0
1435 # ExceptionContinueSearch 1
1437 # In order to tie the handler to the function one has to compose
1438 # couple of structures: one for .xdata segment and one for .pdata.
1440 # UNWIND_INFO structure for .xdata segment would be
1442 # function_unwind_info:
1446 # This structure designates exception handler for a function with
1447 # zero-length prologue, no stack frame or frame register.
1449 # To facilitate composing of .pdata structures, auto-generated "gear"
1450 # prologue copies rsp value to rax and denotes next instruction with
1451 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1452 # styling rule mentioned in the beginning. Position of this label is
1453 # chosen in such manner that possible exceptions raised in the "gear"
1454 # prologue would be accounted to caller and unwound from latter's frame.
1455 # End of function is marked with respective .LSEH_end_{function_name}
1456 # label. To summarize, .pdata segment would contain
1458 # .rva .LSEH_begin_function
1459 # .rva .LSEH_end_function
1460 # .rva function_unwind_info
1462 # Reference to function_unwind_info from .xdata segment is the anchor.
1463 # In case you wonder why references are 32-bit .rvas and not 64-bit
1464 # .quads. References put into these two segments are required to be
1465 # *relative* to the base address of the current binary module, a.k.a.
1466 # image base. No Win64 module, be it .exe or .dll, can be larger than
1467 # 2GB and thus such relative references can be and are accommodated in
1470 # Having reviewed the example function code, one can argue that "movq
1471 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1472 # rax would contain an undefined value. If this "offends" you, use
1473 # another register and refrain from modifying rax till magic_point is
1474 # reached, i.e. as if it was a non-volatile register. If more registers
1475 # are required prior [variable] frame setup is completed, note that
1476 # nobody says that you can have only one "magic point." You can
1477 # "liberate" non-volatile registers by denoting last stack off-load
1478 # instruction and reflecting it in finer grade unwind logic in handler.
1479 # After all, isn't it why it's called *language-specific* handler...
1481 # SE handlers are also involved in unwinding stack when executable is
1482 # profiled or debugged. Profiling implies additional limitations that
1483 # are too subtle to discuss here. For now it's sufficient to say that
1484 # in order to simplify handlers one should either a) offload original
1485 # %rsp to stack (like discussed above); or b) if you have a register to
1486 # spare for frame pointer, choose volatile one.
1488 # (*) Note that we're talking about run-time, not debug-time. Lack of
1489 # unwind information makes debugging hard on both Windows and
1490 # Unix. "Unlike" refers to the fact that on Unix signal handler
1491 # will always be invoked, core dumped and appropriate exit code
1492 # returned to parent (for user notification).