2 # Copyright 2005-2018 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 my $value = $self->{value};
216 $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
221 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
223 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
224 l=>"DWORD$PTR", d=>"DWORD$PTR",
225 q=>"QWORD$PTR", o=>"OWORD$PTR",
226 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR",
227 z=>"ZMMWORD$PTR" ) if (!$gas);
230 my ($class, $line, $opcode) = @_;
234 # optional * ----vvv--- appears in indirect jmp/call
235 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) {
237 $self->{asterisk} = $1;
239 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
240 $self->{scale} = 1 if (!defined($self->{scale}));
241 $self->{opmask} = $4;
243 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
245 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
246 die if ($opcode->mnemonic() ne "mov");
247 $opcode->mnemonic("lea");
249 $self->{base} =~ s/^%//;
250 $self->{index} =~ s/^%// if (defined($self->{index}));
251 $self->{opcode} = $opcode;
257 my ($self, $sz) = @_;
259 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
260 $self->{label} =~ s/\.L/$decor/g;
262 # Silently convert all EAs to 64-bit. This is required for
263 # elder GNU assembler and results in more compact code,
264 # *but* most importantly AES module depends on this feature!
265 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
266 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
268 # Solaris /usr/ccs/bin/as can't handle multiplications
269 # in $self->{label}...
271 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
272 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
274 # Some assemblers insist on signed presentation of 32-bit
275 # offsets, but sign extension is a tricky business in perl...
277 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
279 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
282 # if base register is %rbp or %r13, see if it's possible to
283 # flip base and index registers [for better performance]
284 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
285 $self->{base} =~ /(rbp|r13)/) {
286 $self->{base} = $self->{index}; $self->{index} = $1;
290 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
292 if (defined($self->{index})) {
293 sprintf "%s%s(%s,%%%s,%d)%s",
294 $self->{asterisk},$self->{label},
295 $self->{base}?"%$self->{base}":"",
296 $self->{index},$self->{scale},
299 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label},
300 $self->{base},$self->{opmask};
303 $self->{label} =~ s/\./\$/g;
304 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
305 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
307 my $mnemonic = $self->{opcode}->mnemonic();
308 ($self->{asterisk}) && ($sz="q") ||
309 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
310 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
311 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
312 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
314 $self->{opmask} =~ s/%(k[0-7])/$1/;
316 if (defined($self->{index})) {
317 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz},
318 $self->{label}?"$self->{label}+":"",
319 $self->{index},$self->{scale},
320 $self->{base}?"+$self->{base}":"",
322 } elsif ($self->{base} eq "rip") {
323 sprintf "%s[%s]",$szmap{$sz},$self->{label};
325 sprintf "%s[%s%s]%s", $szmap{$sz},
326 $self->{label}?"$self->{label}+":"",
327 $self->{base},$self->{opmask};
332 { package register; # pick up registers, which start with %.
334 my ($class, $line, $opcode) = @_;
338 # optional * ----vvv--- appears in indirect jmp/call
339 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) {
341 $self->{asterisk} = $1;
343 $self->{opmask} = $3;
344 $opcode->size($self->size());
346 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
354 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
355 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
356 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
357 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
358 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
359 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
360 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
361 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
367 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk},
370 else { $self->{opmask} =~ s/%(k[0-7])/$1/;
371 $self->{value}.$self->{opmask}; }
374 { package label; # pick up labels, which end with :
376 my ($class, $line) = @_;
380 if ($$line =~ /(^[\.\w]+)\:/) {
384 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
386 $self->{value} =~ s/^\.L/$decor/;
394 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
395 if ($win64 && $current_function->{name} eq $self->{value}
396 && $current_function->{abi} eq "svr4") {
398 $func .= " movq %rdi,8(%rsp)\n";
399 $func .= " movq %rsi,16(%rsp)\n";
400 $func .= " movq %rsp,%rax\n";
401 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
402 my $narg = $current_function->{narg};
403 $narg=6 if (!defined($narg));
404 $func .= " movq %rcx,%rdi\n" if ($narg>0);
405 $func .= " movq %rdx,%rsi\n" if ($narg>1);
406 $func .= " movq %r8,%rdx\n" if ($narg>2);
407 $func .= " movq %r9,%rcx\n" if ($narg>3);
408 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
409 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
412 } elsif ($self->{value} ne "$current_function->{name}") {
413 # Make all labels in masm global.
414 $self->{value} .= ":" if ($masm);
415 $self->{value} . ":";
416 } elsif ($win64 && $current_function->{abi} eq "svr4") {
417 my $func = "$current_function->{name}" .
418 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
420 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
421 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
422 $func .= " mov rax,rsp\n";
423 $func .= "${decor}SEH_begin_$current_function->{name}:";
424 $func .= ":" if ($masm);
426 my $narg = $current_function->{narg};
427 $narg=6 if (!defined($narg));
428 $func .= " mov rdi,rcx\n" if ($narg>0);
429 $func .= " mov rsi,rdx\n" if ($narg>1);
430 $func .= " mov rdx,r8\n" if ($narg>2);
431 $func .= " mov rcx,r9\n" if ($narg>3);
432 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
433 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
436 "$current_function->{name}".
437 ($nasm ? ":" : "\tPROC $current_function->{scope}");
441 { package expr; # pick up expressions
443 my ($class, $line, $opcode) = @_;
447 if ($$line =~ /(^[^,]+)/) {
451 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
453 $self->{value} =~ s/\@PLT// if (!$elf);
454 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
455 $self->{value} =~ s/\.L/$decor/g;
456 $self->{opcode} = $opcode;
462 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
463 "NEAR ".$self->{value};
469 { package cfi_directive;
470 # CFI directives annotate instructions that are significant for
471 # stack unwinding procedure compliant with DWARF specification,
472 # see http://dwarfstd.org/. Besides naturally expected for this
473 # script platform-specific filtering function, this module adds
474 # three auxiliary synthetic directives not recognized by [GNU]
477 # - .cfi_push to annotate push instructions in prologue, which
478 # translates to .cfi_adjust_cfa_offset (if needed) and
480 # - .cfi_pop to annotate pop instructions in epilogue, which
481 # translates to .cfi_adjust_cfa_offset (if needed) and
483 # - [and most notably] .cfi_cfa_expression which encodes
484 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as
487 # CFA expressions were introduced in DWARF specification version
488 # 3 and describe how to deduce CFA, Canonical Frame Address. This
489 # becomes handy if your stack frame is variable and you can't
490 # spare register for [previous] frame pointer. Suggested directive
491 # syntax is made-up mix of DWARF operator suffixes [subset of]
492 # and references to registers with optional bias. Following example
493 # describes offloaded *original* stack pointer at specific offset
494 # from *current* stack pointer:
496 # .cfi_cfa_expression %rsp+40,deref,+8
498 # Final +8 has everything to do with the fact that CFA is defined
499 # as reference to top of caller's stack, and on x86_64 call to
500 # subroutine pushes 8-byte return address. In other words original
501 # stack pointer upon entry to a subroutine is 8 bytes off from CFA.
503 # Below constants are taken from "DWARF Expressions" section of the
504 # DWARF specification, section is numbered 7.7 in versions 3 and 4.
505 my %DW_OP_simple = ( # no-arg operators, mapped directly
506 deref => 0x06, dup => 0x12,
507 drop => 0x13, over => 0x14,
508 pick => 0x15, swap => 0x16,
509 rot => 0x17, xderef => 0x18,
511 abs => 0x19, and => 0x1a,
512 div => 0x1b, minus => 0x1c,
513 mod => 0x1d, mul => 0x1e,
514 neg => 0x1f, not => 0x20,
515 or => 0x21, plus => 0x22,
516 shl => 0x24, shr => 0x25,
517 shra => 0x26, xor => 0x27,
520 my %DW_OP_complex = ( # used in specific subroutines
521 constu => 0x10, # uleb128
522 consts => 0x11, # sleb128
523 plus_uconst => 0x23, # uleb128
524 lit0 => 0x30, # add 0-31 to opcode
525 reg0 => 0x50, # add 0-31 to opcode
526 breg0 => 0x70, # add 0-31 to opcole, sleb128
527 regx => 0x90, # uleb28
528 fbreg => 0x91, # sleb128
529 bregx => 0x92, # uleb128, sleb128
530 piece => 0x93, # uleb128
533 # Following constants are defined in x86_64 ABI supplement, for
534 # example available at https://www.uclibc.org/docs/psABI-x86_64.pdf,
535 # see section 3.7 "Stack Unwind Algorithm".
537 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3,
538 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7,
539 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11,
540 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15
543 my ($cfa_reg, $cfa_rsp);
546 # [us]leb128 format is variable-length integer representation base
547 # 2^128, with most significant bit of each byte being 0 denoting
548 # *last* most significant digit. See "Variable Length Data" in the
549 # DWARF specification, numbered 7.6 at least in versions 3 and 4.
551 use integer; # get right shift extend sign
554 my $sign = ($val < 0) ? -1 : 0;
558 push @ret, $val&0x7f;
560 # see if remaining bits are same and equal to most
561 # significant bit of the current digit, if so, it's
563 last if (($val>>6) == $sign);
576 push @ret, $val&0x7f;
578 # see if it's last significant digit...
579 last if (($val >>= 7) == 0);
589 if ($val >= 0 && $val < 32) {
590 return ($DW_OP_complex{lit0}+$val);
592 return ($DW_OP_complex{consts}, sleb128($val));
597 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/);
599 my $reg = $DW_reg_idx{$1};
600 my $off = eval ("0 $2 $3");
602 return (($DW_OP_complex{breg0} + $reg), sleb128($off));
603 # Yes, we use DW_OP_bregX+0 to push register value and not
604 # DW_OP_regX, because latter would require even DW_OP_piece,
605 # which would be a waste under the circumstances. If you have
606 # to use DWP_OP_reg, use "regx:N"...
612 foreach my $token (split(/,\s*/,$line)) {
613 if ($token =~ /^%r/) {
614 push @ret,reg($token);
615 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) {
616 push @ret,reg("$2+$1");
617 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) {
619 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i));
620 } elsif (my $i = 1*eval($token) or $token eq "0") {
621 if ($token =~ /^\+/) {
622 push @ret,$DW_OP_complex{plus_uconst},uleb128($i);
627 push @ret,$DW_OP_simple{$token};
631 # Finally we return DW_CFA_def_cfa_expression, 15, followed by
632 # length of the expression and of course the expression itself.
633 return (15,scalar(@ret),@ret);
636 my ($class, $line) = @_;
640 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) {
643 undef $self->{value};
647 # What is $cfa_rsp? Effectively it's difference between %rsp
648 # value and current CFA, Canonical Frame Address, which is
649 # why it starts with -8. Recall that CFA is top of caller's
651 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; };
652 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0);
653 # .cfi_remember_state directives that are not
654 # matched with .cfi_restore_state are
656 die "unpaired .cfi_remember_state" if (@cfa_stack);
660 && do { $cfa_reg = $$line; last; };
662 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
666 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
669 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
671 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
675 /push/ && do { $dir = undef;
677 if ($cfa_reg eq "%rsp") {
678 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
680 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
683 /pop/ && do { $dir = undef;
685 if ($cfa_reg eq "%rsp") {
686 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
688 $self->{value} .= ".cfi_restore\t$$line";
692 && do { $dir = undef;
693 $self->{value} = ".cfi_escape\t" .
694 join(",", map(sprintf("0x%02x", $_),
695 cfa_expression($$line)));
699 && do { push @cfa_stack, [$cfa_reg, $cfa_rsp];
703 && do { ($cfa_reg, $cfa_rsp) = @{pop @cfa_stack};
708 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
717 return ($elf ? $self->{value} : undef);
720 { package directive; # pick up directives, which start with .
722 my ($class, $line) = @_;
727 # chain-call to cfi_directive
728 $ret = cfi_directive->re($line) and return $ret;
730 if ($$line =~ /^\s*(\.\w+)/) {
734 undef $self->{value};
735 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
738 /\.global|\.globl|\.extern/
739 && do { $globals{$$line} = $prefix . $$line;
740 $$line = $globals{$$line} if ($prefix);
743 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
744 if ($type eq "\@function") {
745 undef $current_function;
746 $current_function->{name} = $sym;
747 $current_function->{abi} = "svr4";
748 $current_function->{narg} = $narg;
749 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
750 } elsif ($type eq "\@abi-omnipotent") {
751 undef $current_function;
752 $current_function->{name} = $sym;
753 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
755 $$line =~ s/\@abi\-omnipotent/\@function/;
756 $$line =~ s/\@function.*/\@function/;
759 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
761 $$line = join(",",unpack("C*",$1),0);
765 /\.rva|\.long|\.quad/
766 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
767 $$line =~ s/\.L/$decor/g;
773 $self->{value} = $dir . "\t" . $$line;
775 if ($dir =~ /\.extern/) {
776 $self->{value} = ""; # swallow extern
777 } elsif (!$elf && $dir =~ /\.type/) {
779 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
780 (defined($globals{$1})?".scl 2;":".scl 3;") .
781 "\t.type 32;\t.endef"
782 if ($win64 && $$line =~ /([^,]+),\@function/);
783 } elsif (!$elf && $dir =~ /\.size/) {
785 if (defined($current_function)) {
786 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
787 if ($win64 && $current_function->{abi} eq "svr4");
788 undef $current_function;
790 } elsif (!$elf && $dir =~ /\.align/) {
791 $self->{value} = ".p2align\t" . (log($$line)/log(2));
792 } elsif ($dir eq ".section") {
793 $current_segment=$$line;
794 if (!$elf && $current_segment eq ".init") {
795 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
796 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
798 } elsif ($dir =~ /\.(text|data)/) {
799 $current_segment=".$1";
800 } elsif ($dir =~ /\.hidden/) {
801 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
802 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
803 } elsif ($dir =~ /\.comm/) {
804 $self->{value} = "$dir\t$prefix$$line";
805 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
811 # non-gas case or nasm/masm
813 /\.text/ && do { my $v=undef;
815 $v="section .text code align=64\n";
817 $v="$current_segment\tENDS\n" if ($current_segment);
818 $current_segment = ".text\$";
819 $v.="$current_segment\tSEGMENT ";
820 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
826 /\.data/ && do { my $v=undef;
828 $v="section .data data align=8\n";
830 $v="$current_segment\tENDS\n" if ($current_segment);
831 $current_segment = "_DATA";
832 $v.="$current_segment\tSEGMENT";
837 /\.section/ && do { my $v=undef;
838 $$line =~ s/([^,]*).*/$1/;
839 $$line = ".CRT\$XCU" if ($$line eq ".init");
842 if ($$line=~/\.([px])data/) {
844 $v.=$1 eq "p"? 4 : 8;
845 } elsif ($$line=~/\.CRT\$/i) {
846 $v.=" rdata align=8";
849 $v="$current_segment\tENDS\n" if ($current_segment);
850 $v.="$$line\tSEGMENT";
851 if ($$line=~/\.([px])data/) {
853 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
854 } elsif ($$line=~/\.CRT\$/i) {
856 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
859 $current_segment = $$line;
863 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
864 $self->{value} .= ":NEAR" if ($masm);
868 && do { $self->{value} = $masm?"PUBLIC":"global";
869 $self->{value} .= "\t".$$line;
872 /\.size/ && do { if (defined($current_function)) {
873 undef $self->{value};
874 if ($current_function->{abi} eq "svr4") {
875 $self->{value}="${decor}SEH_end_$current_function->{name}:";
876 $self->{value}.=":\n" if($masm);
878 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
879 undef $current_function;
883 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
884 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
887 /\.(value|long|rva|quad)/
888 && do { my $sz = substr($1,0,1);
889 my @arr = split(/,\s*/,$$line);
890 my $last = pop(@arr);
891 my $conv = sub { my $var=shift;
892 $var=~s/^(0b[0-1]+)/oct($1)/eig;
893 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
894 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
895 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
899 $sz =~ tr/bvlrq/BWDDQ/;
900 $self->{value} = "\tD$sz\t";
901 for (@arr) { $self->{value} .= &$conv($_).","; }
902 $self->{value} .= &$conv($last);
905 /\.byte/ && do { my @str=split(/,\s*/,$$line);
906 map(s/(0b[0-1]+)/oct($1)/eig,@str);
907 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
909 $self->{value}.="DB\t"
910 .join(",",@str[0..15])."\n";
911 foreach (0..15) { shift @str; }
913 $self->{value}.="DB\t"
914 .join(",",@str) if (@str);
917 /\.comm/ && do { my @str=split(/,\s*/,$$line);
920 $v.="common $prefix@str[0] @str[1]";
922 $v="$current_segment\tENDS\n" if ($current_segment);
923 $current_segment = "_DATA";
924 $v.="$current_segment\tSEGMENT\n";
925 $v.="COMM @str[0]:DWORD:".@str[1]/4;
942 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
943 # yet. In order not to be bothered by tracing exact assembler versions,
944 # but at the same time to provide a bare security minimum of AES-NI, we
945 # hard-code some instructions. Extensions past AES-NI on the other hand
946 # are traced by examining assembler version in individual perlasm
949 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
950 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
954 my ($dst,$src,$rex)=@_;
956 $rex|=0x04 if($dst>=8);
957 $rex|=0x01 if($src>=8);
958 push @$opcode,($rex|0x40) if ($rex);
961 my $movq = sub { # elderly gas can't handle inter-register movq
964 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
965 my ($src,$dst)=($1,$2);
966 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
967 rex(\@opcode,$src,$dst,0x8);
968 push @opcode,0x0f,0x7e;
969 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
971 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
972 my ($src,$dst)=($2,$1);
973 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
974 rex(\@opcode,$src,$dst,0x8);
975 push @opcode,0x0f,0x6e;
976 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
984 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
989 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
990 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
991 rex(\@opcode,$src,$dst);
992 push @opcode,0x0f,0x3a,0x16;
993 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1002 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
1007 if ($src =~ /%r([0-9]+)/) { $src = $1; }
1008 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
1009 rex(\@opcode,$dst,$src);
1010 push @opcode,0x0f,0x3a,0x22;
1011 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1020 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1022 rex(\@opcode,$2,$1);
1023 push @opcode,0x0f,0x38,0x00;
1024 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1032 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1034 rex(\@opcode,$3,$2);
1035 push @opcode,0x0f,0x3a,0x0f;
1036 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1044 my $pclmulqdq = sub {
1045 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1047 rex(\@opcode,$3,$2);
1048 push @opcode,0x0f,0x3a,0x44;
1049 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1051 push @opcode,$c=~/^0/?oct($c):$c;
1059 if (shift =~ /%[er](\w+)/) {
1062 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1063 rex(\@opcode,0,$dst,8);
1064 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1072 if (shift =~ /%[er](\w+)/) {
1075 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1076 rex(\@opcode,0,$dst,8);
1077 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1084 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1085 # are using only two instructions hand-code them in order to be excused
1086 # from chasing assembler versions...
1090 my ($dst,$src1,$src2,$rxb)=@_;
1093 $rxb&=~(0x04<<5) if($dst>=8);
1094 $rxb&=~(0x01<<5) if($src1>=8);
1095 $rxb&=~(0x02<<5) if($src2>=8);
1100 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1102 rxb(\@opcode,$3,$2,-1,0x08);
1103 push @opcode,0x78,0xc2;
1104 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1106 push @opcode,$c=~/^0/?oct($c):$c;
1114 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1116 rxb(\@opcode,$3,$2,-1,0x08);
1117 push @opcode,0x78,0xc3;
1118 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1120 push @opcode,$c=~/^0/?oct($c):$c;
1127 # Intel Control-flow Enforcement Technology extension. All functions and
1128 # indirect branch targets will have to start with this instruction...
1130 my $endbranch = sub {
1131 (0xf3,0x0f,0x1e,0xfa);
1134 ########################################################################
1148 while(defined(my $line=<>)) {
1150 $line =~ s|\R$||; # Better chomp
1152 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1153 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1154 $line =~ s|^\s+||; # ... and skip white spaces in beginning
1155 $line =~ s|\s+$||; # ... and at the end
1157 if (my $label=label->re(\$line)) { print $label->out(); }
1159 if (my $directive=directive->re(\$line)) {
1160 printf "%s",$directive->out();
1161 } elsif (my $opcode=opcode->re(\$line)) {
1162 my $asm = eval("\$".$opcode->mnemonic());
1164 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1165 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1170 ARGUMENT: while (1) {
1173 ($arg=register->re(\$line, $opcode))||
1174 ($arg=const->re(\$line)) ||
1175 ($arg=ea->re(\$line, $opcode)) ||
1176 ($arg=expr->re(\$line, $opcode)) ||
1181 last ARGUMENT if ($line !~ /^,/);
1188 my $sz=$opcode->size();
1191 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1192 @args = map($_->out($sz),@args);
1193 printf "\t%s\t%s",$insn,join(",",@args);
1195 $insn = $opcode->out();
1197 my $arg = $_->out();
1198 # $insn.=$sz compensates for movq, pinsrw, ...
1199 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1200 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1201 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1202 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1204 @args = reverse(@args);
1205 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1206 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1209 printf "\t%s",$opcode->out();
1216 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1217 print "END\n" if ($masm);
1221 \f#################################################
1222 # Cross-reference x86_64 ABI "card"
1242 # (*) volatile register
1243 # (-) preserved by callee
1244 # (#) Nth argument, volatile
1246 # In Unix terms top of stack is argument transfer area for arguments
1247 # which could not be accommodated in registers. Or in other words 7th
1248 # [integer] argument resides at 8(%rsp) upon function entry point.
1249 # 128 bytes above %rsp constitute a "red zone" which is not touched
1250 # by signal handlers and can be used as temporal storage without
1251 # allocating a frame.
1253 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1254 # which belongs to/can be overwritten by callee. N is the number of
1255 # arguments passed to callee, *but* not less than 4! This means that
1256 # upon function entry point 5th argument resides at 40(%rsp), as well
1257 # as that 32 bytes from 8(%rsp) can always be used as temporal
1258 # storage [without allocating a frame]. One can actually argue that
1259 # one can assume a "red zone" above stack pointer under Win64 as well.
1260 # Point is that at apparently no occasion Windows kernel would alter
1261 # the area above user stack pointer in true asynchronous manner...
1263 # All the above means that if assembler programmer adheres to Unix
1264 # register and stack layout, but disregards the "red zone" existence,
1265 # it's possible to use following prologue and epilogue to "gear" from
1266 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1268 # omnipotent_function:
1271 # movq %rsi,16(%rsp)
1272 # movq %rcx,%rdi ; if 1st argument is actually present
1273 # movq %rdx,%rsi ; if 2nd argument is actually ...
1274 # movq %r8,%rdx ; if 3rd argument is ...
1275 # movq %r9,%rcx ; if 4th argument ...
1276 # movq 40(%rsp),%r8 ; if 5th ...
1277 # movq 48(%rsp),%r9 ; if 6th ...
1282 # movq 16(%rsp),%rsi
1286 \f#################################################
1287 # Win64 SEH, Structured Exception Handling.
1289 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1290 # has undesired side-effect at run-time: if an exception is raised in
1291 # assembler subroutine such as those in question (basically we're
1292 # referring to segmentation violations caused by malformed input
1293 # parameters), the application is briskly terminated without invoking
1294 # any exception handlers, most notably without generating memory dump
1295 # or any user notification whatsoever. This poses a problem. It's
1296 # possible to address it by registering custom language-specific
1297 # handler that would restore processor context to the state at
1298 # subroutine entry point and return "exception is not handled, keep
1299 # unwinding" code. Writing such handler can be a challenge... But it's
1300 # doable, though requires certain coding convention. Consider following
1303 # .type function,@function
1305 # movq %rsp,%rax # copy rsp to volatile register
1306 # pushq %r15 # save non-volatile registers
1310 # subq %rdi,%r11 # prepare [variable] stack frame
1312 # movq %rax,0(%r11) # check for exceptions
1313 # movq %r11,%rsp # allocate [variable] stack frame
1314 # movq %rax,0(%rsp) # save original rsp value
1317 # movq 0(%rsp),%rcx # pull original rsp value
1318 # movq -24(%rcx),%rbp # restore non-volatile registers
1319 # movq -16(%rcx),%rbx
1320 # movq -8(%rcx),%r15
1321 # movq %rcx,%rsp # restore original rsp
1324 # .size function,.-function
1326 # The key is that up to magic_point copy of original rsp value remains
1327 # in chosen volatile register and no non-volatile register, except for
1328 # rsp, is modified. While past magic_point rsp remains constant till
1329 # the very end of the function. In this case custom language-specific
1330 # exception handler would look like this:
1332 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1333 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1334 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1335 # ULONG64 rip = context->Rip;
1337 # if (rip >= magic_point)
1338 # { rsp = (ULONG64 *)context->Rsp;
1339 # if (rip < magic_epilogue)
1340 # { rsp = (ULONG64 *)rsp[0];
1341 # context->Rbp = rsp[-3];
1342 # context->Rbx = rsp[-2];
1343 # context->R15 = rsp[-1];
1346 # context->Rsp = (ULONG64)rsp;
1347 # context->Rdi = rsp[1];
1348 # context->Rsi = rsp[2];
1350 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1351 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1352 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1353 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1354 # return ExceptionContinueSearch;
1357 # It's appropriate to implement this handler in assembler, directly in
1358 # function's module. In order to do that one has to know members'
1359 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1360 # values. Here they are:
1380 # sizeof(CONTEXT) 1232
1381 # DISPATCHER_CONTEXT.ControlPc 0
1382 # DISPATCHER_CONTEXT.ImageBase 8
1383 # DISPATCHER_CONTEXT.FunctionEntry 16
1384 # DISPATCHER_CONTEXT.EstablisherFrame 24
1385 # DISPATCHER_CONTEXT.TargetIp 32
1386 # DISPATCHER_CONTEXT.ContextRecord 40
1387 # DISPATCHER_CONTEXT.LanguageHandler 48
1388 # DISPATCHER_CONTEXT.HandlerData 56
1389 # UNW_FLAG_NHANDLER 0
1390 # ExceptionContinueSearch 1
1392 # In order to tie the handler to the function one has to compose
1393 # couple of structures: one for .xdata segment and one for .pdata.
1395 # UNWIND_INFO structure for .xdata segment would be
1397 # function_unwind_info:
1401 # This structure designates exception handler for a function with
1402 # zero-length prologue, no stack frame or frame register.
1404 # To facilitate composing of .pdata structures, auto-generated "gear"
1405 # prologue copies rsp value to rax and denotes next instruction with
1406 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1407 # styling rule mentioned in the beginning. Position of this label is
1408 # chosen in such manner that possible exceptions raised in the "gear"
1409 # prologue would be accounted to caller and unwound from latter's frame.
1410 # End of function is marked with respective .LSEH_end_{function_name}
1411 # label. To summarize, .pdata segment would contain
1413 # .rva .LSEH_begin_function
1414 # .rva .LSEH_end_function
1415 # .rva function_unwind_info
1417 # Reference to function_unwind_info from .xdata segment is the anchor.
1418 # In case you wonder why references are 32-bit .rvas and not 64-bit
1419 # .quads. References put into these two segments are required to be
1420 # *relative* to the base address of the current binary module, a.k.a.
1421 # image base. No Win64 module, be it .exe or .dll, can be larger than
1422 # 2GB and thus such relative references can be and are accommodated in
1425 # Having reviewed the example function code, one can argue that "movq
1426 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1427 # rax would contain an undefined value. If this "offends" you, use
1428 # another register and refrain from modifying rax till magic_point is
1429 # reached, i.e. as if it was a non-volatile register. If more registers
1430 # are required prior [variable] frame setup is completed, note that
1431 # nobody says that you can have only one "magic point." You can
1432 # "liberate" non-volatile registers by denoting last stack off-load
1433 # instruction and reflecting it in finer grade unwind logic in handler.
1434 # After all, isn't it why it's called *language-specific* handler...
1436 # SE handlers are also involved in unwinding stack when executable is
1437 # profiled or debugged. Profiling implies additional limitations that
1438 # are too subtle to discuss here. For now it's sufficient to say that
1439 # in order to simplify handlers one should either a) offload original
1440 # %rsp to stack (like discussed above); or b) if you have a register to
1441 # spare for frame pointer, choose volatile one.
1443 # (*) Note that we're talking about run-time, not debug-time. Lack of
1444 # unwind information makes debugging hard on both Windows and
1445 # Unix. "Unlike" refers to the fact that on Unix signal handler
1446 # will always be invoked, core dumped and appropriate exit code
1447 # returned to parent (for user notification).