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 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); last; };
654 && do { $cfa_reg = $$line; last; };
656 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
660 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
663 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
665 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
669 /push/ && do { $dir = undef;
671 if ($cfa_reg eq "%rsp") {
672 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
674 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
677 /pop/ && do { $dir = undef;
679 if ($cfa_reg eq "%rsp") {
680 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
682 $self->{value} .= ".cfi_restore\t$$line";
686 && do { $dir = undef;
687 $self->{value} = ".cfi_escape\t" .
688 join(",", map(sprintf("0x%02x", $_),
689 cfa_expression($$line)));
693 && do { push @cfa_stack, [$cfa_reg, $cfa_rsp];
697 && do { ($cfa_reg, $cfa_rsp) = @{pop @cfa_stack};
702 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
711 return ($elf ? $self->{value} : undef);
714 { package directive; # pick up directives, which start with .
716 my ($class, $line) = @_;
721 # chain-call to cfi_directive
722 $ret = cfi_directive->re($line) and return $ret;
724 if ($$line =~ /^\s*(\.\w+)/) {
728 undef $self->{value};
729 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
732 /\.global|\.globl|\.extern/
733 && do { $globals{$$line} = $prefix . $$line;
734 $$line = $globals{$$line} if ($prefix);
737 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
738 if ($type eq "\@function") {
739 undef $current_function;
740 $current_function->{name} = $sym;
741 $current_function->{abi} = "svr4";
742 $current_function->{narg} = $narg;
743 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
744 } elsif ($type eq "\@abi-omnipotent") {
745 undef $current_function;
746 $current_function->{name} = $sym;
747 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
749 $$line =~ s/\@abi\-omnipotent/\@function/;
750 $$line =~ s/\@function.*/\@function/;
753 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
755 $$line = join(",",unpack("C*",$1),0);
759 /\.rva|\.long|\.quad/
760 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
761 $$line =~ s/\.L/$decor/g;
767 $self->{value} = $dir . "\t" . $$line;
769 if ($dir =~ /\.extern/) {
770 $self->{value} = ""; # swallow extern
771 } elsif (!$elf && $dir =~ /\.type/) {
773 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
774 (defined($globals{$1})?".scl 2;":".scl 3;") .
775 "\t.type 32;\t.endef"
776 if ($win64 && $$line =~ /([^,]+),\@function/);
777 } elsif (!$elf && $dir =~ /\.size/) {
779 if (defined($current_function)) {
780 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
781 if ($win64 && $current_function->{abi} eq "svr4");
782 undef $current_function;
784 } elsif (!$elf && $dir =~ /\.align/) {
785 $self->{value} = ".p2align\t" . (log($$line)/log(2));
786 } elsif ($dir eq ".section") {
787 $current_segment=$$line;
788 if (!$elf && $current_segment eq ".init") {
789 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
790 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
792 } elsif ($dir =~ /\.(text|data)/) {
793 $current_segment=".$1";
794 } elsif ($dir =~ /\.hidden/) {
795 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
796 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
797 } elsif ($dir =~ /\.comm/) {
798 $self->{value} = "$dir\t$prefix$$line";
799 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
805 # non-gas case or nasm/masm
807 /\.text/ && do { my $v=undef;
809 $v="section .text code align=64\n";
811 $v="$current_segment\tENDS\n" if ($current_segment);
812 $current_segment = ".text\$";
813 $v.="$current_segment\tSEGMENT ";
814 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
820 /\.data/ && do { my $v=undef;
822 $v="section .data data align=8\n";
824 $v="$current_segment\tENDS\n" if ($current_segment);
825 $current_segment = "_DATA";
826 $v.="$current_segment\tSEGMENT";
831 /\.section/ && do { my $v=undef;
832 $$line =~ s/([^,]*).*/$1/;
833 $$line = ".CRT\$XCU" if ($$line eq ".init");
836 if ($$line=~/\.([px])data/) {
838 $v.=$1 eq "p"? 4 : 8;
839 } elsif ($$line=~/\.CRT\$/i) {
840 $v.=" rdata align=8";
843 $v="$current_segment\tENDS\n" if ($current_segment);
844 $v.="$$line\tSEGMENT";
845 if ($$line=~/\.([px])data/) {
847 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
848 } elsif ($$line=~/\.CRT\$/i) {
850 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
853 $current_segment = $$line;
857 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
858 $self->{value} .= ":NEAR" if ($masm);
862 && do { $self->{value} = $masm?"PUBLIC":"global";
863 $self->{value} .= "\t".$$line;
866 /\.size/ && do { if (defined($current_function)) {
867 undef $self->{value};
868 if ($current_function->{abi} eq "svr4") {
869 $self->{value}="${decor}SEH_end_$current_function->{name}:";
870 $self->{value}.=":\n" if($masm);
872 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
873 undef $current_function;
877 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
878 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
881 /\.(value|long|rva|quad)/
882 && do { my $sz = substr($1,0,1);
883 my @arr = split(/,\s*/,$$line);
884 my $last = pop(@arr);
885 my $conv = sub { my $var=shift;
886 $var=~s/^(0b[0-1]+)/oct($1)/eig;
887 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
888 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
889 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
893 $sz =~ tr/bvlrq/BWDDQ/;
894 $self->{value} = "\tD$sz\t";
895 for (@arr) { $self->{value} .= &$conv($_).","; }
896 $self->{value} .= &$conv($last);
899 /\.byte/ && do { my @str=split(/,\s*/,$$line);
900 map(s/(0b[0-1]+)/oct($1)/eig,@str);
901 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
903 $self->{value}.="DB\t"
904 .join(",",@str[0..15])."\n";
905 foreach (0..15) { shift @str; }
907 $self->{value}.="DB\t"
908 .join(",",@str) if (@str);
911 /\.comm/ && do { my @str=split(/,\s*/,$$line);
914 $v.="common $prefix@str[0] @str[1]";
916 $v="$current_segment\tENDS\n" if ($current_segment);
917 $current_segment = "_DATA";
918 $v.="$current_segment\tSEGMENT\n";
919 $v.="COMM @str[0]:DWORD:".@str[1]/4;
936 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
937 # yet. In order not to be bothered by tracing exact assembler versions,
938 # but at the same time to provide a bare security minimum of AES-NI, we
939 # hard-code some instructions. Extensions past AES-NI on the other hand
940 # are traced by examining assembler version in individual perlasm
943 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
944 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
948 my ($dst,$src,$rex)=@_;
950 $rex|=0x04 if($dst>=8);
951 $rex|=0x01 if($src>=8);
952 push @$opcode,($rex|0x40) if ($rex);
955 my $movq = sub { # elderly gas can't handle inter-register movq
958 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
959 my ($src,$dst)=($1,$2);
960 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
961 rex(\@opcode,$src,$dst,0x8);
962 push @opcode,0x0f,0x7e;
963 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
965 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
966 my ($src,$dst)=($2,$1);
967 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
968 rex(\@opcode,$src,$dst,0x8);
969 push @opcode,0x0f,0x6e;
970 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
978 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
983 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
984 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
985 rex(\@opcode,$src,$dst);
986 push @opcode,0x0f,0x3a,0x16;
987 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
996 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
1001 if ($src =~ /%r([0-9]+)/) { $src = $1; }
1002 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
1003 rex(\@opcode,$dst,$src);
1004 push @opcode,0x0f,0x3a,0x22;
1005 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1014 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1016 rex(\@opcode,$2,$1);
1017 push @opcode,0x0f,0x38,0x00;
1018 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1026 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1028 rex(\@opcode,$3,$2);
1029 push @opcode,0x0f,0x3a,0x0f;
1030 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1038 my $pclmulqdq = sub {
1039 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1041 rex(\@opcode,$3,$2);
1042 push @opcode,0x0f,0x3a,0x44;
1043 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1045 push @opcode,$c=~/^0/?oct($c):$c;
1053 if (shift =~ /%[er](\w+)/) {
1056 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1057 rex(\@opcode,0,$dst,8);
1058 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1066 if (shift =~ /%[er](\w+)/) {
1069 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1070 rex(\@opcode,0,$dst,8);
1071 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1078 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1079 # are using only two instructions hand-code them in order to be excused
1080 # from chasing assembler versions...
1084 my ($dst,$src1,$src2,$rxb)=@_;
1087 $rxb&=~(0x04<<5) if($dst>=8);
1088 $rxb&=~(0x01<<5) if($src1>=8);
1089 $rxb&=~(0x02<<5) if($src2>=8);
1094 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1096 rxb(\@opcode,$3,$2,-1,0x08);
1097 push @opcode,0x78,0xc2;
1098 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1100 push @opcode,$c=~/^0/?oct($c):$c;
1108 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1110 rxb(\@opcode,$3,$2,-1,0x08);
1111 push @opcode,0x78,0xc3;
1112 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1114 push @opcode,$c=~/^0/?oct($c):$c;
1121 # Intel Control-flow Enforcement Technology extension. All functions and
1122 # indirect branch targets will have to start with this instruction...
1124 my $endbranch = sub {
1125 (0xf3,0x0f,0x1e,0xfa);
1128 ########################################################################
1142 while(defined(my $line=<>)) {
1144 $line =~ s|\R$||; # Better chomp
1146 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1147 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1148 $line =~ s|^\s+||; # ... and skip white spaces in beginning
1149 $line =~ s|\s+$||; # ... and at the end
1151 if (my $label=label->re(\$line)) { print $label->out(); }
1153 if (my $directive=directive->re(\$line)) {
1154 printf "%s",$directive->out();
1155 } elsif (my $opcode=opcode->re(\$line)) {
1156 my $asm = eval("\$".$opcode->mnemonic());
1158 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1159 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1164 ARGUMENT: while (1) {
1167 ($arg=register->re(\$line, $opcode))||
1168 ($arg=const->re(\$line)) ||
1169 ($arg=ea->re(\$line, $opcode)) ||
1170 ($arg=expr->re(\$line, $opcode)) ||
1175 last ARGUMENT if ($line !~ /^,/);
1182 my $sz=$opcode->size();
1185 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1186 @args = map($_->out($sz),@args);
1187 printf "\t%s\t%s",$insn,join(",",@args);
1189 $insn = $opcode->out();
1191 my $arg = $_->out();
1192 # $insn.=$sz compensates for movq, pinsrw, ...
1193 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1194 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1195 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1196 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1198 @args = reverse(@args);
1199 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1200 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1203 printf "\t%s",$opcode->out();
1210 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1211 print "END\n" if ($masm);
1215 \f#################################################
1216 # Cross-reference x86_64 ABI "card"
1236 # (*) volatile register
1237 # (-) preserved by callee
1238 # (#) Nth argument, volatile
1240 # In Unix terms top of stack is argument transfer area for arguments
1241 # which could not be accommodated in registers. Or in other words 7th
1242 # [integer] argument resides at 8(%rsp) upon function entry point.
1243 # 128 bytes above %rsp constitute a "red zone" which is not touched
1244 # by signal handlers and can be used as temporal storage without
1245 # allocating a frame.
1247 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1248 # which belongs to/can be overwritten by callee. N is the number of
1249 # arguments passed to callee, *but* not less than 4! This means that
1250 # upon function entry point 5th argument resides at 40(%rsp), as well
1251 # as that 32 bytes from 8(%rsp) can always be used as temporal
1252 # storage [without allocating a frame]. One can actually argue that
1253 # one can assume a "red zone" above stack pointer under Win64 as well.
1254 # Point is that at apparently no occasion Windows kernel would alter
1255 # the area above user stack pointer in true asynchronous manner...
1257 # All the above means that if assembler programmer adheres to Unix
1258 # register and stack layout, but disregards the "red zone" existence,
1259 # it's possible to use following prologue and epilogue to "gear" from
1260 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1262 # omnipotent_function:
1265 # movq %rsi,16(%rsp)
1266 # movq %rcx,%rdi ; if 1st argument is actually present
1267 # movq %rdx,%rsi ; if 2nd argument is actually ...
1268 # movq %r8,%rdx ; if 3rd argument is ...
1269 # movq %r9,%rcx ; if 4th argument ...
1270 # movq 40(%rsp),%r8 ; if 5th ...
1271 # movq 48(%rsp),%r9 ; if 6th ...
1276 # movq 16(%rsp),%rsi
1280 \f#################################################
1281 # Win64 SEH, Structured Exception Handling.
1283 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1284 # has undesired side-effect at run-time: if an exception is raised in
1285 # assembler subroutine such as those in question (basically we're
1286 # referring to segmentation violations caused by malformed input
1287 # parameters), the application is briskly terminated without invoking
1288 # any exception handlers, most notably without generating memory dump
1289 # or any user notification whatsoever. This poses a problem. It's
1290 # possible to address it by registering custom language-specific
1291 # handler that would restore processor context to the state at
1292 # subroutine entry point and return "exception is not handled, keep
1293 # unwinding" code. Writing such handler can be a challenge... But it's
1294 # doable, though requires certain coding convention. Consider following
1297 # .type function,@function
1299 # movq %rsp,%rax # copy rsp to volatile register
1300 # pushq %r15 # save non-volatile registers
1304 # subq %rdi,%r11 # prepare [variable] stack frame
1306 # movq %rax,0(%r11) # check for exceptions
1307 # movq %r11,%rsp # allocate [variable] stack frame
1308 # movq %rax,0(%rsp) # save original rsp value
1311 # movq 0(%rsp),%rcx # pull original rsp value
1312 # movq -24(%rcx),%rbp # restore non-volatile registers
1313 # movq -16(%rcx),%rbx
1314 # movq -8(%rcx),%r15
1315 # movq %rcx,%rsp # restore original rsp
1318 # .size function,.-function
1320 # The key is that up to magic_point copy of original rsp value remains
1321 # in chosen volatile register and no non-volatile register, except for
1322 # rsp, is modified. While past magic_point rsp remains constant till
1323 # the very end of the function. In this case custom language-specific
1324 # exception handler would look like this:
1326 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1327 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1328 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1329 # ULONG64 rip = context->Rip;
1331 # if (rip >= magic_point)
1332 # { rsp = (ULONG64 *)context->Rsp;
1333 # if (rip < magic_epilogue)
1334 # { rsp = (ULONG64 *)rsp[0];
1335 # context->Rbp = rsp[-3];
1336 # context->Rbx = rsp[-2];
1337 # context->R15 = rsp[-1];
1340 # context->Rsp = (ULONG64)rsp;
1341 # context->Rdi = rsp[1];
1342 # context->Rsi = rsp[2];
1344 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1345 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1346 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1347 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1348 # return ExceptionContinueSearch;
1351 # It's appropriate to implement this handler in assembler, directly in
1352 # function's module. In order to do that one has to know members'
1353 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1354 # values. Here they are:
1374 # sizeof(CONTEXT) 1232
1375 # DISPATCHER_CONTEXT.ControlPc 0
1376 # DISPATCHER_CONTEXT.ImageBase 8
1377 # DISPATCHER_CONTEXT.FunctionEntry 16
1378 # DISPATCHER_CONTEXT.EstablisherFrame 24
1379 # DISPATCHER_CONTEXT.TargetIp 32
1380 # DISPATCHER_CONTEXT.ContextRecord 40
1381 # DISPATCHER_CONTEXT.LanguageHandler 48
1382 # DISPATCHER_CONTEXT.HandlerData 56
1383 # UNW_FLAG_NHANDLER 0
1384 # ExceptionContinueSearch 1
1386 # In order to tie the handler to the function one has to compose
1387 # couple of structures: one for .xdata segment and one for .pdata.
1389 # UNWIND_INFO structure for .xdata segment would be
1391 # function_unwind_info:
1395 # This structure designates exception handler for a function with
1396 # zero-length prologue, no stack frame or frame register.
1398 # To facilitate composing of .pdata structures, auto-generated "gear"
1399 # prologue copies rsp value to rax and denotes next instruction with
1400 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1401 # styling rule mentioned in the beginning. Position of this label is
1402 # chosen in such manner that possible exceptions raised in the "gear"
1403 # prologue would be accounted to caller and unwound from latter's frame.
1404 # End of function is marked with respective .LSEH_end_{function_name}
1405 # label. To summarize, .pdata segment would contain
1407 # .rva .LSEH_begin_function
1408 # .rva .LSEH_end_function
1409 # .rva function_unwind_info
1411 # Reference to function_unwind_info from .xdata segment is the anchor.
1412 # In case you wonder why references are 32-bit .rvas and not 64-bit
1413 # .quads. References put into these two segments are required to be
1414 # *relative* to the base address of the current binary module, a.k.a.
1415 # image base. No Win64 module, be it .exe or .dll, can be larger than
1416 # 2GB and thus such relative references can be and are accommodated in
1419 # Having reviewed the example function code, one can argue that "movq
1420 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1421 # rax would contain an undefined value. If this "offends" you, use
1422 # another register and refrain from modifying rax till magic_point is
1423 # reached, i.e. as if it was a non-volatile register. If more registers
1424 # are required prior [variable] frame setup is completed, note that
1425 # nobody says that you can have only one "magic point." You can
1426 # "liberate" non-volatile registers by denoting last stack off-load
1427 # instruction and reflecting it in finer grade unwind logic in handler.
1428 # After all, isn't it why it's called *language-specific* handler...
1430 # SE handlers are also involved in unwinding stack when executable is
1431 # profiled or debugged. Profiling implies additional limitations that
1432 # are too subtle to discuss here. For now it's sufficient to say that
1433 # in order to simplify handlers one should either a) offload original
1434 # %rsp to stack (like discussed above); or b) if you have a register to
1435 # spare for frame pointer, choose volatile one.
1437 # (*) Note that we're talking about run-time, not debug-time. Lack of
1438 # unwind information makes debugging hard on both Windows and
1439 # Unix. "Unlike" refers to the fact that on Unix signal handler
1440 # will always be invoked, core dumped and appropriate exit code
1441 # returned to parent (for user notification).