Clarifying comment.
[openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM assembler translator by <appro>.
4 #
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...
9 #
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.
13 #
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...
19 #
20 # Currently recognized limitations:
21 #
22 # - can't use multiple ops per line;
23 # - indirect calls and jumps are not supported;
24 #
25 # Dual-ABI styling rules.
26 #
27 # 1. Adhere to Unix register and stack layout [see the end for
28 #    explanation].
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.
49 #
50 #    Example 1:
51 #               .picmeup        %rax
52 #               lea             .Label-.(%rax),%rax
53 #    Example 2:
54 #               .picmeup        %rcx
55 #       .Lpic_point:
56 #               ...
57 #               lea             .Label-.Lpic_point(%rcx),%rbp
58
59 my $output = shift;
60
61 { my ($stddev,$stdino,@junk)=stat(STDOUT);
62   my ($outdev,$outino,@junk)=stat($output);
63
64     open STDOUT,">$output" || die "can't open $output: $!"
65         if ($stddev!=$outdev || $stdino!=$outino);
66 }
67
68 my $win64=1 if ($output =~ /\.asm/);
69
70 my $masmref=8 + 50727*2**-32;   # 8.00.50727 shipped with VS2005
71 my $masm=$masmref;
72 my $PTR=" PTR";
73
74 my $nasm=0;
75
76 if ($win64)
77 {   if ($ENV{ASM} =~ m/nasm/)
78     {   $nasm = 1; $PTR="";   }
79     elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
80     {   $masm = $1 + $2*2**-16 + $4*2**-32;   }
81 }
82
83 my $current_segment;
84 my $current_function;
85
86 { package opcode;       # pick up opcodes
87     sub re {
88         my      $self = shift;  # single instance in enough...
89         local   *line = shift;
90         undef   $ret;
91
92         if ($line =~ /^([a-z][a-z0-9]*)/i) {
93             $self->{op} = $1;
94             $ret = $self;
95             $line = substr($line,@+[0]); $line =~ s/^\s+//;
96
97             undef $self->{sz};
98             if ($self->{op} =~ /^(movz)b.*/) {  # movz is pain...
99                 $self->{op} = $1;
100                 $self->{sz} = "b";
101             } elsif ($self->{op} =~ /call/) {
102                 $self->{sz} = ""
103             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
104                 $self->{op} = $1;
105                 $self->{sz} = $2;
106             }
107         }
108         $ret;
109     }
110     sub size {
111         my $self = shift;
112         my $sz   = shift;
113         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
114         $self->{sz};
115     }
116     sub out {
117         my $self = shift;
118         if (!$win64) {
119             if ($self->{op} eq "movz") {        # movz is pain...
120                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
121             } elsif ($self->{op} =~ /^set/) { 
122                 "$self->{op}";
123             } elsif ($self->{op} eq "ret") {
124                 ".byte  0xf3,0xc3";
125             } else {
126                 "$self->{op}$self->{sz}";
127             }
128         } else {
129             $self->{op} =~ s/^movz/movzx/;
130             if ($self->{op} eq "ret") {
131                 $self->{op} = "";
132                 if ($current_function->{abi} eq "svr4") {
133                     $self->{op} = "mov  rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
134                                   "mov  rsi,QWORD${PTR}[16+rsp]\n\t";
135                 }
136                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
137             } elsif ($self->{op} =~ /^j/ && $nasm) {
138                 $self->{op} .= " NEAR";
139             }
140             $self->{op};
141         }
142     }
143     sub mnemonic { shift->{op}; }
144 }
145 { package const;        # pick up constants, which start with $
146     sub re {
147         my      $self = shift;  # single instance in enough...
148         local   *line = shift;
149         undef   $ret;
150
151         if ($line =~ /^\$([^,]+)/) {
152             $self->{value} = $1;
153             $ret = $self;
154             $line = substr($line,@+[0]); $line =~ s/^\s+//;
155         }
156         $ret;
157     }
158     sub out {
159         my $self = shift;
160
161         if (!$win64) {
162             # Solaris /usr/ccs/bin/as can't handle multiplications
163             # in $self->{value}
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};
167         } else {
168             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
169             sprintf "%s",$self->{value};
170         }
171     }
172 }
173 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
174     sub re {
175         my      $self = shift;  # single instance in enough...
176         local   *line = shift;
177         undef   $ret;
178
179         if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
180             $self->{label} = $1;
181             ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
182             $self->{scale} = 1 if (!defined($self->{scale}));
183             $ret = $self;
184             $line = substr($line,@+[0]); $line =~ s/^\s+//;
185
186             $self->{base}  =~ s/^%//;
187             $self->{index} =~ s/^%// if (defined($self->{index}));
188         }
189         $ret;
190     }
191     sub size {}
192     sub out {
193         my $self = shift;
194         my $sz = shift;
195
196         # Silently convert all EAs to 64-bit. This is required for
197         # elder GNU assembler and results in more compact code,
198         # *but* most importantly AES module depends on this feature!
199         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
200         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
201
202         if (!$win64) {
203             # Solaris /usr/ccs/bin/as can't handle multiplications
204             # in $self->{label}
205             $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
206             $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
207
208             if (defined($self->{index})) {
209                 sprintf "%s(%%%s,%%%s,%d)",
210                                         $self->{label},$self->{base},
211                                         $self->{index},$self->{scale};
212             } else {
213                 sprintf "%s(%%%s)",     $self->{label},$self->{base};
214             }
215         } else {
216             %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
217
218             $self->{label} =~ s/\./\$/g;
219             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
220             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
221
222             if (defined($self->{index})) {
223                 sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
224                                         $self->{label}?"$self->{label}+":"",
225                                         $self->{index},$self->{scale},
226                                         $self->{base};
227             } elsif ($self->{base} eq "rip") {
228                 sprintf "%s[%s]",$szmap{$sz},$self->{label};
229             } else {
230                 sprintf "%s[%s%s]",$szmap{$sz},
231                                         $self->{label}?"$self->{label}+":"",
232                                         $self->{base};
233             }
234         }
235     }
236 }
237 { package register;     # pick up registers, which start with %.
238     sub re {
239         my      $class = shift; # muliple instances...
240         my      $self = {};
241         local   *line = shift;
242         undef   $ret;
243
244         if ($line =~ /^%(\w+)/) {
245             bless $self,$class;
246             $self->{value} = $1;
247             $ret = $self;
248             $line = substr($line,@+[0]); $line =~ s/^\s+//;
249         }
250         $ret;
251     }
252     sub size {
253         my      $self = shift;
254         undef   $ret;
255
256         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
257         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
258         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
259         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
260         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
261         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
262         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
263         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
264
265         $ret;
266     }
267     sub out {
268         my $self = shift;
269         sprintf $win64?"%s":"%%%s",$self->{value};
270     }
271 }
272 { package label;        # pick up labels, which end with :
273     sub re {
274         my      $self = shift;  # single instance is enough...
275         local   *line = shift;
276         undef   $ret;
277
278         if ($line =~ /(^[\.\w]+\:)/) {
279             $self->{value} = $1;
280             $ret = $self;
281             $line = substr($line,@+[0]); $line =~ s/^\s+//;
282
283             $self->{value} =~ s/\.L/\$L/ if ($win64);
284         }
285         $ret;
286     }
287     sub out {
288         my $self = shift;
289
290         if (!$win64) {
291             $self->{value};
292         } elsif ($self->{value} ne "$current_function->{name}:") {
293             $self->{value};
294         } elsif ($current_function->{abi} eq "svr4") {
295             my $func =  "$current_function->{name}".($nasm?":":"\tPROC")."\n".
296                         "       mov     QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n".
297                         "       mov     QWORD${PTR}[16+rsp],rsi\n";
298             my $narg = $current_function->{narg};
299             $narg=6 if (!defined($narg));
300             $func .= "  mov     rdi,rcx\n" if ($narg>0);
301             $func .= "  mov     rsi,rdx\n" if ($narg>1);
302             $func .= "  mov     rdx,r8\n"  if ($narg>2);
303             $func .= "  mov     rcx,r9\n"  if ($narg>3);
304             $func .= "  mov     r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
305             $func .= "  mov     r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
306             $func .= "\n";
307         } else {
308            "$current_function->{name}".($nasm?":":"\tPROC");
309         }
310     }
311 }
312 { package expr;         # pick up expressioins
313     sub re {
314         my      $self = shift;  # single instance is enough...
315         local   *line = shift;
316         undef   $ret;
317
318         if ($line =~ /(^[^,]+)/) {
319             $self->{value} = $1;
320             $ret = $self;
321             $line = substr($line,@+[0]); $line =~ s/^\s+//;
322
323             $self->{value} =~ s/\.L/\$L/g if ($win64);
324         }
325         $ret;
326     }
327     sub out {
328         my $self = shift;
329         $self->{value};
330     }
331 }
332 { package directive;    # pick up directives, which start with .
333     sub re {
334         my      $self = shift;  # single instance is enough...
335         local   *line = shift;
336         undef   $ret;
337         my      $dir;
338         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
339                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
340                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
341                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
342                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
343                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
344                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
345                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
346                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
347
348         if ($line =~ /^\s*(\.\w+)/) {
349             if (!$win64) {
350                 $self->{value} = $1;
351                 $line =~ s/\@abi\-omnipotent/\@function/;
352                 $line =~ s/\@function.*/\@function/;
353                 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
354                     $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
355                 } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
356                     $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
357                 } elsif ($line =~ /\.extern/) {
358                     $self->{value} = ""; # swallow extern
359                 } else {
360                     $self->{value} = $line;
361                 }
362                 $line = "";
363                 return $self;
364             }
365
366             $dir = $1;
367             $ret = $self;
368             undef $self->{value};
369             $line = substr($line,@+[0]); $line =~ s/^\s+//;
370             SWITCH: for ($dir) {
371                 /\.(text)/
372                             && do { my $v=undef;
373                                     if ($nasm) {
374                                         $v ="section    .$1 code align=64\n";
375                                         $v.="default    rel\n";
376                                         $v.="%define    PUBLIC global";
377                                     } else {
378                                         $v="$current_segment\tENDS\n" if ($current_segment);
379                                         $current_segment = "_$1\$";
380                                         $current_segment =~ tr/[a-z]/[A-Z]/;
381                                         $v.="$current_segment\tSEGMENT ";
382                                         $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
383                                         $v.=" 'CODE'";
384                                     }
385                                     $self->{value} = $v;
386                                     last;
387                                   };
388                 /\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
389                                     $self->{value} .= ":BYTE" if (!$nasm);
390                                     last;
391                                   };
392                 /\.globl/   && do { $self->{value} = "PUBLIC\t".$line; last; };
393                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
394                                     if ($type eq "\@function") {
395                                         undef $current_function;
396                                         $current_function->{name} = $sym;
397                                         $current_function->{abi}  = "svr4";
398                                         $current_function->{narg} = $narg;
399                                     } elsif ($type eq "\@abi-omnipotent") {
400                                         undef $current_function;
401                                         $current_function->{name} = $sym;
402                                     }
403                                     last;
404                                   };
405                 /\.size/    && do { if (defined($current_function)) {
406                                         $self->{value}="$current_function->{name}\tENDP" if(!$nasm);
407                                         undef $current_function;
408                                     }
409                                     last;
410                                   };
411                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
412                 /\.(byte|value|long|quad)/
413                             && do { my @arr = split(',',$line);
414                                     my $sz  = substr($1,0,1);
415                                     my $last = pop(@arr);
416                                     my $conv = sub  {   my $var=shift;
417                                                         if ($var=~s/0x([0-9a-f]+)/0$1h/i) { $var; }
418                                                         else { sprintf"0%Xh",$var; }
419                                                     };  
420
421                                     $sz =~ tr/bvlq/BWDQ/;
422                                     $self->{value} = "\tD$sz\t";
423                                     for (@arr) { $self->{value} .= &$conv($_).","; }
424                                     $self->{value} .= &$conv($last);
425                                     last;
426                                   };
427                 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t0%Xh,090000000h",$opcode{$line};
428                                     last;
429                                   };
430                 /\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
431                                         my @str=unpack("C*",$1);
432                                         push @str,0;
433                                         while ($#str>15) {
434                                             $self->{value}.="DB\t"
435                                                 .join(",",@str[0..15])."\n";
436                                             foreach (0..15) { shift @str; }
437                                         }
438                                         $self->{value}.="DB\t"
439                                                 .join(",",@str) if (@str);
440                                     }
441                                     last;
442                                   };
443             }
444             $line = "";
445         }
446
447         $ret;
448     }
449     sub out {
450         my $self = shift;
451         $self->{value};
452     }
453 }
454
455 while($line=<>) {
456
457     chomp($line);
458
459     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
460     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
461     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
462
463     undef $label;
464     undef $opcode;
465     undef $dst;
466     undef $src;
467     undef $sz;
468
469     if ($label=label->re(\$line))       { print $label->out(); }
470
471     if (directive->re(\$line)) {
472         printf "%s",directive->out();
473     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
474
475         if ($src=register->re(\$line))  { opcode->size($src->size()); }
476         elsif ($src=const->re(\$line))  { }
477         elsif ($src=ea->re(\$line))     { }
478         elsif ($src=expr->re(\$line))   { }
479
480         last ARGUMENT if ($line !~ /^,/);
481
482         $line = substr($line,1); $line =~ s/^\s+//;
483
484         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
485         elsif ($dst=const->re(\$line))  { }
486         elsif ($dst=ea->re(\$line))     { }
487
488         } # ARGUMENT:
489
490         $sz=opcode->size();
491
492         if (defined($dst)) {
493             if (!$win64) {
494                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
495                                         $src->out($sz),$dst->out($sz);
496             } else {
497                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
498                 printf "\t%s\t%s,%s",   $opcode->out(),
499                                         $dst->out($sz),$src->out($sz);
500             }
501         } elsif (defined($src)) {
502             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
503         } else {
504             printf "\t%s",$opcode->out();
505         }
506     }
507
508     print $line,"\n";
509 }
510
511 print "\n$current_segment\tENDS\nEND\n" if ($current_segment);
512
513 close STDOUT;
514
515 #################################################
516 # Cross-reference x86_64 ABI "card"
517 #
518 #               Unix            Win64
519 # %rax          *               *
520 # %rbx          -               -
521 # %rcx          #4              #1
522 # %rdx          #3              #2
523 # %rsi          #2              -
524 # %rdi          #1              -
525 # %rbp          -               -
526 # %rsp          -               -
527 # %r8           #5              #3
528 # %r9           #6              #4
529 # %r10          *               *
530 # %r11          *               *
531 # %r12          -               -
532 # %r13          -               -
533 # %r14          -               -
534 # %r15          -               -
535
536 # (*)   volatile register
537 # (-)   preserved by callee
538 # (#)   Nth argument, volatile
539 #
540 # In Unix terms top of stack is argument transfer area for arguments
541 # which could not be accomodated in registers. Or in other words 7th
542 # [integer] argument resides at 8(%rsp) upon function entry point.
543 # 128 bytes above %rsp constitute a "red zone" which is not touched
544 # by signal handlers and can be used as temporal storage without
545 # allocating a frame.
546 #
547 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
548 # which belongs to/can be overwritten by callee. N is the number of
549 # arguments passed to callee, *but* not less than 4! This means that
550 # upon function entry point 5th argument resides at 40(%rsp), as well
551 # as that 32 bytes from 8(%rsp) can always be used as temporal
552 # storage [without allocating a frame]. One can actually argue that
553 # one can assume a "red zone" above stack pointer under Win64 as well.
554 # Point is that at apparently no occasion Windows kernel would alter
555 # the area above user stack pointer in true asynchronous manner...
556 #
557 # All the above means that if assembler programmer adheres to Unix
558 # register and stack layout, but disregards the "red zone" existense,
559 # it's possible to use following prologue and epilogue to "gear" from
560 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
561 #
562 # omnipotent_function:
563 # ifdef WIN64
564 #       movq    %rdi,8(%rsp)
565 #       movq    %rsi,16(%rsp)
566 #       movq    %rcx,%rdi       ; if 1st argument is actually present
567 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
568 #       movq    %r8,%rdx        ; if 3rd argument is ...
569 #       movq    %r9,%rcx        ; if 4th argument ...
570 #       movq    40(%rsp),%r8    ; if 5th ...
571 #       movq    48(%rsp),%r9    ; if 6th ...
572 # endif
573 #       ...
574 # ifdef WIN64
575 #       movq    8(%rsp),%rdi
576 #       movq    16(%rsp),%rsi
577 # endif
578 #       ret