3 # Ascetic x86_64 AT&T to MASM assembler translator by <appro>.
5 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6 # format is way easier to parse. Because it's simpler to "gear" from
7 # Unix ABI to Windows one [see cross-reference "card" at the end of
8 # file]. Because Linux targets were available first...
10 # In addition the script also "distills" code suitable for GNU
11 # assembler, so that it can be compiled with more rigid assemblers,
12 # such as Solaris /usr/ccs/bin/as.
14 # This translator is not designed to convert *arbitrary* assembler
15 # code from AT&T format to MASM one. It's designed to convert just
16 # enough to provide for dual-ABI OpenSSL modules development...
17 # There *are* limitations and you might have to modify your assembler
18 # code or this script to achieve the desired result...
20 # Currently recognized limitations:
22 # - can't use multiple ops per line;
24 # Dual-ABI styling rules.
26 # 1. Adhere to Unix register and stack layout [see the end for
28 # 2. Forget about "red zone," stick to more traditional blended
29 # stack frame allocation. If volatile storage is actually required
30 # that is. If not, just leave the stack as is.
31 # 3. Functions tagged with ".type name,@function" get crafted with
32 # unified Win64 prologue and epilogue automatically. If you want
33 # to take care of ABI differences yourself, tag functions as
34 # ".type name,@abi-omnipotent" instead.
35 # 4. To optimize the Win64 prologue you can specify number of input
36 # arguments as ".type name,@function,N." Keep in mind that if N is
37 # larger than 6, then you *have to* write "abi-omnipotent" code,
38 # because >6 cases can't be addressed with unified prologue.
39 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
40 # (sorry about latter).
41 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
42 # required to identify the spots, where to inject Win64 epilogue!
43 # But on the pros, it's then prefixed with rep automatically:-)
44 # 7. Due to MASM limitations [and certain general counter-intuitivity
45 # of ip-relative addressing] generation of position-independent
46 # code is assisted by synthetic directive, .picmeup, which puts
47 # address of the *next* instruction into target register.
51 # lea .Label-.(%rax),%rax
56 # lea .Label-.Lpic_point(%rcx),%rbp
60 { my ($stddev,$stdino,@junk)=stat(STDOUT);
61 my ($outdev,$outino,@junk)=stat($output);
63 open STDOUT,">$output" || die "can't open $output: $!"
64 if ($stddev!=$outdev || $stdino!=$outino);
67 my $win64=1 if ($output =~ /\.asm/);
69 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
77 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
78 { $nasm = $1 + $2*0.01; $PTR=""; }
79 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
80 { $masm = $1 + $2*2**-16 + $4*2**-32; }
81 die "no assembler found on %PATH" if (!($nasm || $masm));
88 { package opcode; # pick up opcodes
90 my $self = shift; # single instance in enough...
94 if ($line =~ /^([a-z][a-z0-9]*)/i) {
97 $line = substr($line,@+[0]); $line =~ s/^\s+//;
100 if ($self->{op} =~ /^(movz)b.*/) { # movz is pain...
103 } elsif ($self->{op} =~ /call|jmp/) {
105 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
115 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
121 if ($self->{op} eq "movz") { # movz is pain...
122 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
123 } elsif ($self->{op} =~ /^set/) {
125 } elsif ($self->{op} eq "ret") {
128 "$self->{op}$self->{sz}";
131 $self->{op} =~ s/^movz/movzx/;
132 if ($self->{op} eq "ret") {
134 if ($current_function->{abi} eq "svr4") {
135 $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
136 "mov rsi,QWORD${PTR}[16+rsp]\n\t";
138 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
143 sub mnemonic { shift->{op}; }
145 { package const; # pick up constants, which start with $
147 my $self = shift; # single instance in enough...
151 if ($line =~ /^\$([^,]+)/) {
154 $line = substr($line,@+[0]); $line =~ s/^\s+//;
162 # Solaris /usr/ccs/bin/as can't handle multiplications
164 $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
165 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
166 sprintf "\$%s",$self->{value};
168 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
169 sprintf "%s",$self->{value};
173 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
175 my $self = shift; # single instance in enough...
179 # optional * ---vvv--- appears in indirect jmp/call
180 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
181 $self->{asterisk} = $1;
183 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
184 $self->{scale} = 1 if (!defined($self->{scale}));
186 $line = substr($line,@+[0]); $line =~ s/^\s+//;
188 $self->{base} =~ s/^%//;
189 $self->{index} =~ s/^%// if (defined($self->{index}));
198 # Silently convert all EAs to 64-bit. This is required for
199 # elder GNU assembler and results in more compact code,
200 # *but* most importantly AES module depends on this feature!
201 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
202 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
205 # Solaris /usr/ccs/bin/as can't handle multiplications
207 $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
208 $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
210 if (defined($self->{index})) {
211 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk},
212 $self->{label},$self->{base},
213 $self->{index},$self->{scale};
215 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
218 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
220 $self->{label} =~ s/\./\$/g;
221 $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
222 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
223 $sz="q" if ($self->{asterisk});
225 if (defined($self->{index})) {
226 sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
227 $self->{label}?"$self->{label}+":"",
228 $self->{index},$self->{scale},
230 } elsif ($self->{base} eq "rip") {
231 sprintf "%s[%s]",$szmap{$sz},$self->{label};
233 sprintf "%s[%s%s]",$szmap{$sz},
234 $self->{label}?"$self->{label}+":"",
240 { package register; # pick up registers, which start with %.
242 my $class = shift; # muliple instances...
247 # optional * ---vvv--- appears in indirect jmp/call
248 if ($line =~ /^(\*?)%(\w+)/) {
250 $self->{asterisk} = $1;
253 $line = substr($line,@+[0]); $line =~ s/^\s+//;
261 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
262 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
263 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
264 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
265 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
266 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
267 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
268 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
274 if (!$win64) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
275 else { $self->{value}; }
278 { package label; # pick up labels, which end with :
280 my $self = shift; # single instance is enough...
284 if ($line =~ /(^[\.\w]+\:)/) {
287 $line = substr($line,@+[0]); $line =~ s/^\s+//;
289 $self->{value} =~ s/\.L/\$L/ if ($win64);
298 } elsif ($self->{value} ne "$current_function->{name}:") {
299 $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
301 } elsif ($current_function->{abi} eq "svr4") {
302 my $func = "$current_function->{name}" .
303 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
305 $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
306 $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
307 my $narg = $current_function->{narg};
308 $narg=6 if (!defined($narg));
309 $func .= " mov rdi,rcx\n" if ($narg>0);
310 $func .= " mov rsi,rdx\n" if ($narg>1);
311 $func .= " mov rdx,r8\n" if ($narg>2);
312 $func .= " mov rcx,r9\n" if ($narg>3);
313 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
314 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
317 "$current_function->{name}".
318 ($nasm ? ":" : "\tPROC $current_function->{scope}");
322 { package expr; # pick up expressioins
324 my $self = shift; # single instance is enough...
328 if ($line =~ /(^[^,]+)/) {
331 $line = substr($line,@+[0]); $line =~ s/^\s+//;
333 $self->{value} =~ s/\.L/\$L/g if ($win64);
339 if ($nasm && opcode->mnemonic()=~m/^j/) {
340 "NEAR ".$self->{value};
346 { package directive; # pick up directives, which start with .
348 my $self = shift; # single instance is enough...
352 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
353 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
354 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
355 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
356 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
357 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
358 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
359 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
360 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
362 if ($line =~ /^\s*(\.\w+)/) {
365 $line =~ s/\@abi\-omnipotent/\@function/;
366 $line =~ s/\@function.*/\@function/;
367 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
368 $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
369 } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
370 $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
371 } elsif ($line =~ /\.extern/) {
372 $self->{value} = ""; # swallow extern
374 $self->{value} = $line;
382 undef $self->{value};
383 $line = substr($line,@+[0]); $line =~ s/^\s+//;
385 /\.text/ && do { my $v=undef;
387 $v="section .text code align=64\n";
389 $v="$current_segment\tENDS\n" if ($current_segment);
390 $current_segment = ".text\$";
391 $v.="$current_segment\tSEGMENT ";
392 $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
398 /\.data/ && do { my $v=undef;
400 $v="section .data data align=8\n";
402 $v="$current_segment\tENDS\n" if ($current_segment);
403 $current_segment = "_DATA";
404 $v.="$current_segment\tSEGMENT";
409 /\.section/ && do { my $v=undef;
412 if ($line=~/\.([px])data/) {
414 $v.=$1 eq "p"? 4 : 8;
417 $v="$current_segment\tENDS\n" if ($current_segment);
418 $v.="$line\tSEGMENT";
419 if ($line=~/\.([px])data/) {
421 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
424 $current_segment = $line;
428 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
429 $self->{value} .= ":NEAR" if ($masm);
432 /\.globl/ && do { $self->{value} = "PUBLIC\t".$line;
433 $globals{$line} = $line;
436 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
437 if ($type eq "\@function") {
438 undef $current_function;
439 $current_function->{name} = $sym;
440 $current_function->{abi} = "svr4";
441 $current_function->{narg} = $narg;
442 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
443 } elsif ($type eq "\@abi-omnipotent") {
444 undef $current_function;
445 $current_function->{name} = $sym;
446 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
450 /\.size/ && do { if (defined($current_function)) {
451 $self->{value}="$current_function->{name}\tENDP" if(!$nasm);
452 undef $current_function;
456 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
457 /\.(byte|value|long|quad)/
458 && do { my @arr = split(',',$line);
459 my $sz = substr($1,0,1);
460 my $last = pop(@arr);
461 my $conv = sub { my $var=shift;
462 $var=~s/0x([0-9a-f]+)/0$1h/ig;
463 if ($current_segment=~/.[px]data/)
464 { $var=~s/\b([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
468 $sz =~ tr/bvlq/BWDQ/;
469 $self->{value} = "\tD$sz\t";
470 for (@arr) { $self->{value} .= &$conv($_).","; }
471 $self->{value} .= &$conv($last);
474 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t0%Xh,090000000h",$opcode{$line};
477 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
478 my @str=unpack("C*",$1);
481 $self->{value}.="DB\t"
482 .join(",",@str[0..15])."\n";
483 foreach (0..15) { shift @str; }
485 $self->{value}.="DB\t"
486 .join(",",@str) if (@str);
505 %define PUBLIC global
516 $line =~ s|[#!].*$||; # get rid of asm-style comments...
517 $line =~ s|/\*.*\*/||; # ... and C-style comments...
518 $line =~ s|^\s+||; # ... and skip white spaces in beginning
526 if ($label=label->re(\$line)) { print $label->out(); }
528 if (directive->re(\$line)) {
529 printf "%s",directive->out();
530 } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
532 if ($src=register->re(\$line)) { opcode->size($src->size()); }
533 elsif ($src=const->re(\$line)) { }
534 elsif ($src=ea->re(\$line)) { }
535 elsif ($src=expr->re(\$line)) { }
537 last ARGUMENT if ($line !~ /^,/);
539 $line = substr($line,1); $line =~ s/^\s+//;
541 if ($dst=register->re(\$line)) { opcode->size($dst->size()); }
542 elsif ($dst=const->re(\$line)) { }
543 elsif ($dst=ea->re(\$line)) { }
551 printf "\t%s\t%s,%s", $opcode->out($dst->size()),
552 $src->out($sz),$dst->out($sz);
554 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
555 printf "\t%s\t%s,%s", $opcode->out(),
556 $dst->out($sz),$src->out($sz);
558 } elsif (defined($src)) {
559 printf "\t%s\t%s",$opcode->out(),$src->out($sz);
561 printf "\t%s",$opcode->out();
568 print "\n$current_segment\tENDS\nEND\n" if ($current_segment && $masm);
572 #################################################
573 # Cross-reference x86_64 ABI "card"
593 # (*) volatile register
594 # (-) preserved by callee
595 # (#) Nth argument, volatile
597 # In Unix terms top of stack is argument transfer area for arguments
598 # which could not be accomodated in registers. Or in other words 7th
599 # [integer] argument resides at 8(%rsp) upon function entry point.
600 # 128 bytes above %rsp constitute a "red zone" which is not touched
601 # by signal handlers and can be used as temporal storage without
602 # allocating a frame.
604 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
605 # which belongs to/can be overwritten by callee. N is the number of
606 # arguments passed to callee, *but* not less than 4! This means that
607 # upon function entry point 5th argument resides at 40(%rsp), as well
608 # as that 32 bytes from 8(%rsp) can always be used as temporal
609 # storage [without allocating a frame]. One can actually argue that
610 # one can assume a "red zone" above stack pointer under Win64 as well.
611 # Point is that at apparently no occasion Windows kernel would alter
612 # the area above user stack pointer in true asynchronous manner...
614 # All the above means that if assembler programmer adheres to Unix
615 # register and stack layout, but disregards the "red zone" existense,
616 # it's possible to use following prologue and epilogue to "gear" from
617 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
619 # omnipotent_function:
623 # movq %rcx,%rdi ; if 1st argument is actually present
624 # movq %rdx,%rsi ; if 2nd argument is actually ...
625 # movq %r8,%rdx ; if 3rd argument is ...
626 # movq %r9,%rcx ; if 4th argument ...
627 # movq 40(%rsp),%r8 ; if 5th ...
628 # movq 48(%rsp),%r9 ; if 6th ...
637 #################################################
638 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
639 # has undesired side-effect at run-time: if an exception is raised in
640 # assembler subroutine such as those in question (basically we're
641 # referring to segmentation violations caused by malformed input
642 # parameters), the application is briskly terminated without invoking
643 # any exception handlers, most notably without generating memory dump
644 # or any user notification whatsoever. This poses a problem. It's
645 # possible to address it by registering custom language-specific
646 # handler that would restore processor context to the state at
647 # subroutine entry point and return "exception is not handled, keep
648 # unwinding" code. Writing such handler can be a challenge... But it's
649 # doable, though requires certain coding convention. Consider following
653 # movq %rsp,%rax # copy rsp to volatile register
654 # pushq %r15 # save non-volatile registers
658 # subq %rdi,%r11 # prepare [variable] stack frame
660 # movq %rax,0(%r11) # check for exceptions
661 # movq %r11,%rsp # allocate [variable] stack frame
662 # movq %rax,0(%rsp) # save original rsp value
665 # movq 0(%rsp),%rcx # pull original rsp value
666 # movq -24(%rcx),%rbp # restore non-volatile registers
667 # movq -16(%rcx),%rbx
669 # movq %rcx,%rsp # restore original rsp
672 # The key is that up to magic_point copy of original rsp value remains
673 # in chosen volatile register and no non-volatile register, except for
674 # rsp, is modified. While past magic_point rsp remains constant till
675 # the very end of the function. In this case custom language-specific
676 # exception handler would look like this:
678 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
679 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
681 # if (context->Rip<magic_point)
682 # rsp = (ULONG64 *)context->Rax;
684 # { rsp = ((ULONG64 **)context->Rsp)[0];
685 # context->Rbp = rsp[-3];
686 # context->Rbx = rsp[-2];
687 # context->R15 = rsp[-1];
689 # context->Rsp = (ULONG64)rsp;
690 # context->Rdi = rsp[1];
691 # context->Rsi = rsp[2];
693 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
694 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
695 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
696 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
697 # return ExceptionContinueSearch;
700 # It's appropriate to implement this handler in assembler, directly in
701 # function's module. In order to do that one has to know members'
702 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
703 # values. Here they are:
722 # sizeof(CONTEXT) 1232
723 # DISPATCHER_CONTEXT.ControlPc 0
724 # DISPATCHER_CONTEXT.ImageBase 8
725 # DISPATCHER_CONTEXT.FunctionEntry 16
726 # DISPATCHER_CONTEXT.EstablisherFrame 24
727 # DISPATCHER_CONTEXT.TargetIp 32
728 # DISPATCHER_CONTEXT.ContextRecord 40
729 # DISPATCHER_CONTEXT.LanguageHandler 48
730 # DISPATCHER_CONTEXT.HandlerData 56
731 # UNW_FLAG_NHANDLER 0
732 # ExceptionContinueSearch 1
734 # UNWIND_INFO structure for .xdata segment would be
736 # DD imagerel handler
737 # denoting exception handler for a function with zero-length prologue,
738 # no stack frame or frame register.
740 # P.S. Attentive reader can notice that effectively no exceptions are
741 # expected in "gear" prologue and epilogue [discussed in "ABI
742 # cross-reference" above]. No, there are not. This is because if
743 # memory area used by them was subject to segmentation violation,
744 # then exception would be raised upon call to our function and be
745 # accounted to caller and unwound from its frame, which is not a
748 # (*) Note that we're talking about run-time, not debug-time. Lack of
749 # unwind information makes debugging hard on both Windows and
750 # Unix. "Unlike" referes to the fact that on Unix signal handler
751 # will always be invoked, core dumped and appropriate exit code
752 # returned to parent (for user notification).