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