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;
23 # - indirect calls and jumps are not supported;
25 # Dual-ABI styling rules.
27 # 1. Adhere to Unix register and stack layout [see the end for
29 # 2. Forget about "red zone," stick to more traditional blended
30 # stack frame allocation. If volatile storage is actually required
31 # that is. If not, just leave the stack as is.
32 # 3. Functions tagged with ".type name,@function" get crafted with
33 # unified Win64 prologue and epilogue automatically. If you want
34 # to take care of ABI differences yourself, tag functions as
35 # ".type name,@abi-omnipotent" instead.
36 # 4. To optimize the Win64 prologue you can specify number of input
37 # arguments as ".type name,@function,N." Keep in mind that if N is
38 # larger than 6, then you *have to* write "abi-omnipotent" code,
39 # because >6 cases can't be addressed with unified prologue.
40 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
41 # (sorry about latter).
42 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
43 # required to identify the spots, where to inject Win64 epilogue!
44 # But on the pros, it's then prefixed with rep automatically:-)
45 # 7. Due to MASM limitations [and certain general counter-intuitivity
46 # of ip-relative addressing] generation of position-independent
47 # code is assisted by synthetic directive, .picmeup, which puts
48 # address of the *next* instruction into target register.
52 # lea .Label-.(%rax),%rax
57 # lea .Label-.Lpic_point(%rcx),%rbp
61 { my ($stddev,$stdino,@junk)=stat(STDOUT);
62 my ($outdev,$outino,@junk)=stat($output);
64 open STDOUT,">$output" || die "can't open $output: $!"
65 if ($stddev!=$outdev || $stdino!=$outino);
68 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
69 my $masm=$masmref if ($output =~ /\.asm/);
70 if ($masm && `ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
71 { $masm=$1 + $2*2**-16 + $4*2**-32; }
76 { package opcode; # pick up opcodes
78 my $self = shift; # single instance in enough...
82 if ($line =~ /^([a-z][a-z0-9]*)/i) {
85 $line = substr($line,@+[0]); $line =~ s/^\s+//;
88 if ($self->{op} =~ /^(movz)b.*/) { # movz is pain...
91 } elsif ($self->{op} =~ /call/) {
93 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
103 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
109 if ($self->{op} eq "movz") { # movz is pain...
110 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
111 } elsif ($self->{op} =~ /^set/) {
113 } elsif ($self->{op} eq "ret") {
116 "$self->{op}$self->{sz}";
119 $self->{op} =~ s/^movz/movzx/;
120 if ($self->{op} eq "ret") {
122 if ($current_function->{abi} eq "svr4") {
123 $self->{op} = "mov rdi,QWORD PTR 8[rsp]\t;WIN64 epilogue\n\t".
124 "mov rsi,QWORD PTR 16[rsp]\n\t";
126 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
132 { package const; # pick up constants, which start with $
134 my $self = shift; # single instance in enough...
138 if ($line =~ /^\$([^,]+)/) {
141 $line = substr($line,@+[0]); $line =~ s/^\s+//;
149 # Solaris /usr/ccs/bin/as can't handle multiplications
151 $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
152 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
153 sprintf "\$%s",$self->{value};
155 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
156 sprintf "%s",$self->{value};
160 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
162 my $self = shift; # single instance in enough...
166 if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
168 ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
169 $self->{scale} = 1 if (!defined($self->{scale}));
171 $line = substr($line,@+[0]); $line =~ s/^\s+//;
173 $self->{base} =~ s/^%//;
174 $self->{index} =~ s/^%// if (defined($self->{index}));
183 # Silently convert all EAs to 64-bit. This is required for
184 # elder GNU assembler and results in more compact code,
185 # *but* most importantly AES module depends on this feature!
186 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
187 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
190 # Solaris /usr/ccs/bin/as can't handle multiplications
193 $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
194 $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
195 $self->{label} =~ s/([0-9]+)/$1<<32>>32/eg;
197 if (defined($self->{index})) {
198 sprintf "%s(%%%s,%%%s,%d)",
199 $self->{label},$self->{base},
200 $self->{index},$self->{scale};
202 sprintf "%s(%%%s)", $self->{label},$self->{base};
205 %szmap = ( b=>"BYTE", w=>"WORD", l=>"DWORD", q=>"QWORD" );
207 $self->{label} =~ s/\./\$/g;
208 $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
209 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
211 if (defined($self->{index})) {
212 sprintf "%s PTR %s[%s*%d+%s]",$szmap{$sz},
214 $self->{index},$self->{scale},
216 } elsif ($self->{base} eq "rip") {
217 sprintf "%s PTR %s",$szmap{$sz},$self->{label};
219 sprintf "%s PTR %s[%s]",$szmap{$sz},
220 $self->{label},$self->{base};
225 { package register; # pick up registers, which start with %.
227 my $class = shift; # muliple instances...
232 if ($line =~ /^%(\w+)/) {
236 $line = substr($line,@+[0]); $line =~ s/^\s+//;
244 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
245 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
246 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
247 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
248 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
249 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
250 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
251 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
257 sprintf $masm?"%s":"%%%s",$self->{value};
260 { package label; # pick up labels, which end with :
262 my $self = shift; # single instance is enough...
266 if ($line =~ /(^[\.\w]+\:)/) {
269 $line = substr($line,@+[0]); $line =~ s/^\s+//;
271 $self->{value} =~ s/\.L/\$L/ if ($masm);
280 } elsif ($self->{value} ne "$current_function->{name}:") {
282 } elsif ($current_function->{abi} eq "svr4") {
283 my $func = "$current_function->{name} PROC\n".
284 " mov QWORD PTR 8[rsp],rdi\t;WIN64 prologue\n".
285 " mov QWORD PTR 16[rsp],rsi\n";
286 my $narg = $current_function->{narg};
287 $narg=6 if (!defined($narg));
288 $func .= " mov rdi,rcx\n" if ($narg>0);
289 $func .= " mov rsi,rdx\n" if ($narg>1);
290 $func .= " mov rdx,r8\n" if ($narg>2);
291 $func .= " mov rcx,r9\n" if ($narg>3);
292 $func .= " mov r8,QWORD PTR 40[rsp]\n" if ($narg>4);
293 $func .= " mov r9,QWORD PTR 48[rsp]\n" if ($narg>5);
296 "$current_function->{name} PROC";
300 { package expr; # pick up expressioins
302 my $self = shift; # single instance is enough...
306 if ($line =~ /(^[^,]+)/) {
309 $line = substr($line,@+[0]); $line =~ s/^\s+//;
311 $self->{value} =~ s/\.L/\$L/g if ($masm);
320 { package directive; # pick up directives, which start with .
322 my $self = shift; # single instance is enough...
326 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
327 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
328 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
329 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
330 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
331 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
332 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
333 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
334 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
336 if ($line =~ /^\s*(\.\w+)/) {
339 $line =~ s/\@abi\-omnipotent/\@function/;
340 $line =~ s/\@function.*/\@function/;
341 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
342 $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
343 } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
344 $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
345 } elsif ($line =~ /\.extern/) {
346 $self->{value} = ""; # swallow extern
348 $self->{value} = $line;
356 undef $self->{value};
357 $line = substr($line,@+[0]); $line =~ s/^\s+//;
361 $v="$current_segment\tENDS\n" if ($current_segment);
362 $current_segment = "_$1\$";
363 $current_segment =~ tr/[a-z]/[A-Z]/;
364 $v.="$current_segment\tSEGMENT ";
365 $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
370 /\.extern/ && do { $self->{value} = "EXTRN\t".$line.":BYTE"; last; };
371 /\.globl/ && do { $self->{value} = "PUBLIC\t".$line; last; };
372 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
373 if ($type eq "\@function") {
374 undef $current_function;
375 $current_function->{name} = $sym;
376 $current_function->{abi} = "svr4";
377 $current_function->{narg} = $narg;
378 } elsif ($type eq "\@abi-omnipotent") {
379 undef $current_function;
380 $current_function->{name} = $sym;
384 /\.size/ && do { if (defined($current_function)) {
385 $self->{value}="$current_function->{name}\tENDP";
386 undef $current_function;
390 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
391 /\.(byte|value|long|quad)/
392 && do { my @arr = split(',',$line);
393 my $sz = substr($1,0,1);
394 my $last = pop(@arr);
395 my $conv = sub { my $var=shift;
396 if ($var=~s/0x([0-9a-f]+)/0$1h/i) { $var; }
397 else { sprintf"0%Xh",$var; }
400 $sz =~ tr/bvlq/BWDQ/;
401 $self->{value} = "\tD$sz\t";
402 for (@arr) { $self->{value} .= &$conv($_).","; }
403 $self->{value} .= &$conv($last);
406 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t 0%Xh,090000000h",$opcode{$line};
409 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
410 my @str=unpack("C*",$1);
413 $self->{value}.="DB\t"
414 .join(",",@str[0..15])."\n";
415 foreach (0..15) { shift @str; }
417 $self->{value}.="DB\t"
418 .join(",",@str) if (@str);
438 $line =~ s|[#!].*$||; # get rid of asm-style comments...
439 $line =~ s|/\*.*\*/||; # ... and C-style comments...
440 $line =~ s|^\s+||; # ... and skip white spaces in beginning
448 if ($label=label->re(\$line)) { print $label->out(); }
450 if (directive->re(\$line)) {
451 printf "%s",directive->out();
452 } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
454 if ($src=register->re(\$line)) { opcode->size($src->size()); }
455 elsif ($src=const->re(\$line)) { }
456 elsif ($src=ea->re(\$line)) { }
457 elsif ($src=expr->re(\$line)) { }
459 last ARGUMENT if ($line !~ /^,/);
461 $line = substr($line,1); $line =~ s/^\s+//;
463 if ($dst=register->re(\$line)) { opcode->size($dst->size()); }
464 elsif ($dst=const->re(\$line)) { }
465 elsif ($dst=ea->re(\$line)) { }
473 printf "\t%s\t%s,%s", $opcode->out($dst->size()),
474 $src->out($sz),$dst->out($sz);
476 printf "\t%s\t%s,%s", $opcode->out(),
477 $dst->out($sz),$src->out($sz);
479 } elsif (defined($src)) {
480 printf "\t%s\t%s",$opcode->out(),$src->out($sz);
482 printf "\t%s",$opcode->out();
489 print "\n$current_segment\tENDS\nEND\n" if ($masm);
493 #################################################
494 # Cross-reference x86_64 ABI "card"
514 # (*) volatile register
515 # (-) preserved by callee
516 # (#) Nth argument, volatile
518 # In Unix terms top of stack is argument transfer area for arguments
519 # which could not be accomodated in registers. Or in other words 7th
520 # [integer] argument resides at 8(%rsp) upon function entry point.
521 # 128 bytes above %rsp constitute a "red zone" which is not touched
522 # by signal handlers and can be used as temporal storage without
523 # allocating a frame.
525 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
526 # which belongs to/can be overwritten by callee. N is the number of
527 # arguments passed to callee, *but* not less than 4! This means that
528 # upon function entry point 5th argument resides at 40(%rsp), as well
529 # as that 32 bytes from 8(%rsp) can always be used as temporal
530 # storage [without allocating a frame]. One can actually argue that
531 # one can assume a "red zone" above stack pointer under Win64 as well.
532 # Point is that at apparently no occasion Windows kernel would alter
533 # the area above user stack pointer in true asynchronous manner...
535 # All the above means that if assembler programmer adheres to Unix
536 # register and stack layout, but disregards the "red zone" existense,
537 # it's possible to use following prologue and epilogue to "gear" from
538 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
540 # omnipotent_function:
544 # movq %rcx,%rdi ; if 1st argument is actually present
545 # movq %rdx,%rsi ; if 2nd argument is actually ...
546 # movq %r8,%rdx ; if 3rd argument is ...
547 # movq %r9,%rcx ; if 4th argument ...
548 # movq 40(%rsp),%r8 ; if 5th ...
549 # movq 48(%rsp),%r9 ; if 6th ...