x86_64 assembler pack to comply with updated styling x86_64-xlate.pl rules.
[openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM/NASM 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 #
24 # Dual-ABI styling rules.
25 #
26 # 1. Adhere to Unix register and stack layout [see cross-reference
27 #    ABI "card" at the end for explanation].
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. Stick to explicit ip-relative addressing. If you have to use
45 #    GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
46 #    Both are recognized and translated to proper Win64 addressing
47 #    modes. To support legacy code a synthetic directive, .picmeup,
48 #    is implemented. It puts address of the *next* instruction into
49 #    target register, e.g.:
50 #
51 #               .picmeup        %rax
52 #               lea             .Label-.(%rax),%rax
53 #
54 # 8. In order to provide for structured exception handling unified
55 #    Win64 prologue copies %rsp value to %rax. For further details
56 #    see SEH paragraph at the end.
57 # 9. .init segment is allowed to contain calls to functions only.
58 \f
59 my $flavour = shift;
60 my $output  = shift;
61 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
62
63 { my ($stddev,$stdino,@junk)=stat(STDOUT);
64   my ($outdev,$outino,@junk)=stat($output);
65
66     open STDOUT,">$output" || die "can't open $output: $!"
67         if ($stddev!=$outdev || $stdino!=$outino);
68 }
69
70 my $gas=1;      $gas=0 if ($output =~ /\.asm$/);
71 my $elf=1;      $elf=0 if (!$gas);
72 my $win64=0;
73 my $prefix="";
74
75 my $masmref=8 + 50727*2**-32;   # 8.00.50727 shipped with VS2005
76 my $masm=0;
77 my $PTR=" PTR";
78
79 my $nasmref=2.03;
80 my $nasm=0;
81
82 if    ($flavour eq "mingw64")   { $gas=1; $elf=0; $win64=1; $prefix="_"; }
83 elsif ($flavour eq "macosx")    { $gas=1; $elf=0; $prefix="_"; }
84 elsif ($flavour eq "masm")      { $gas=0; $elf=0; $masm=$masmref; $win64=1; }
85 elsif ($flavour eq "nasm")      { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $PTR=""; }
86 elsif (!$gas)
87 {   if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
88     {   $nasm = $1 + $2*0.01; $PTR="";  }
89     elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
90     {   $masm = $1 + $2*2**-16 + $4*2**-32;   }
91     die "no assembler found on %PATH" if (!($nasm || $masm));
92     $win64=1;
93     $elf=0;
94 }
95
96 my $current_segment;
97 my $current_function;
98 my %globals;
99
100 { package opcode;       # pick up opcodes
101     sub re {
102         my      $self = shift;  # single instance in enough...
103         local   *line = shift;
104         undef   $ret;
105
106         if ($line =~ /^([a-z][a-z0-9]*)/i) {
107             $self->{op} = $1;
108             $ret = $self;
109             $line = substr($line,@+[0]); $line =~ s/^\s+//;
110
111             undef $self->{sz};
112             if ($self->{op} =~ /^(movz)b.*/) {  # movz is pain...
113                 $self->{op} = $1;
114                 $self->{sz} = "b";
115             } elsif ($self->{op} =~ /call|jmp/) {
116                 $self->{sz} = ""
117             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
118                 $self->{op} = $1;
119                 $self->{sz} = $2;
120             }
121         }
122         $ret;
123     }
124     sub size {
125         my $self = shift;
126         my $sz   = shift;
127         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
128         $self->{sz};
129     }
130     sub out {
131         my $self = shift;
132         if ($gas) {
133             if ($self->{op} eq "movz") {        # movz is pain...
134                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
135             } elsif ($self->{op} =~ /^set/) { 
136                 "$self->{op}";
137             } elsif ($self->{op} eq "ret") {
138                 my $epilogue = "";
139                 if ($win64 && $current_function->{abi} eq "svr4") {
140                     $epilogue = "movq   8(%rsp),%rdi\n\t" .
141                                 "movq   16(%rsp),%rsi\n\t";
142                 }
143                 $epilogue . ".byte      0xf3,0xc3";
144             } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
145                 ".p2align\t3\n\t.quad";
146             } else {
147                 "$self->{op}$self->{sz}";
148             }
149         } else {
150             $self->{op} =~ s/^movz/movzx/;
151             if ($self->{op} eq "ret") {
152                 $self->{op} = "";
153                 if ($win64 && $current_function->{abi} eq "svr4") {
154                     $self->{op} = "mov  rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
155                                   "mov  rsi,QWORD${PTR}[16+rsp]\n\t";
156                 }
157                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
158             } elsif ($self->{op} =~ /^(pop|push)f/) {
159                 $self->{op} .= $self->{sz};
160             } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
161                 $self->{op} = "ALIGN\t8\n\tDQ";
162             } 
163             $self->{op};
164         }
165     }
166     sub mnemonic {
167         my $self=shift;
168         my $op=shift;
169         $self->{op}=$op if (defined($op));
170         $self->{op};
171     }
172 }
173 { package const;        # pick up constants, which start with $
174     sub re {
175         my      $self = shift;  # single instance in enough...
176         local   *line = shift;
177         undef   $ret;
178
179         if ($line =~ /^\$([^,]+)/) {
180             $self->{value} = $1;
181             $ret = $self;
182             $line = substr($line,@+[0]); $line =~ s/^\s+//;
183         }
184         $ret;
185     }
186     sub out {
187         my $self = shift;
188
189         if ($gas) {
190             # Solaris /usr/ccs/bin/as can't handle multiplications
191             # in $self->{value}
192             $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
193             $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
194             sprintf "\$%s",$self->{value};
195         } else {
196             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
197             sprintf "%s",$self->{value};
198         }
199     }
200 }
201 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
202     sub re {
203         my      $self = shift;  # single instance in enough...
204         local   *line = shift;
205         undef   $ret;
206
207         # optional * ---vvv--- appears in indirect jmp/call
208         if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
209             $self->{asterisk} = $1;
210             $self->{label} = $2;
211             ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
212             $self->{scale} = 1 if (!defined($self->{scale}));
213             $ret = $self;
214             $line = substr($line,@+[0]); $line =~ s/^\s+//;
215
216             if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
217                 die if (opcode->mnemonic() ne "mov");
218                 opcode->mnemonic("lea");
219             }
220             $self->{base}  =~ s/^%//;
221             $self->{index} =~ s/^%// if (defined($self->{index}));
222         }
223         $ret;
224     }
225     sub size {}
226     sub out {
227         my $self = shift;
228         my $sz = shift;
229
230         $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
231
232         # Silently convert all EAs to 64-bit. This is required for
233         # elder GNU assembler and results in more compact code,
234         # *but* most importantly AES module depends on this feature!
235         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
236         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
237
238         if ($gas) {
239             # Solaris /usr/ccs/bin/as can't handle multiplications
240             # in $self->{label}
241             $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
242             $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
243             $self->{label} =~ s/\.L/L\$/g       if (!$elf);
244
245             if (defined($self->{index})) {
246                 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk},
247                                         $self->{label},$self->{base},
248                                         $self->{index},$self->{scale};
249             } else {
250                 sprintf "%s%s(%%%s)",   $self->{asterisk},$self->{label},$self->{base};
251             }
252         } else {
253             %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
254
255             $self->{label} =~ s/\.L/\$L\$/g;
256             $self->{label} =~ s/\./\$/g;
257             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
258             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
259             $sz="q" if ($self->{asterisk});
260
261             if (defined($self->{index})) {
262                 sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
263                                         $self->{label}?"$self->{label}+":"",
264                                         $self->{index},$self->{scale},
265                                         $self->{base};
266             } elsif ($self->{base} eq "rip") {
267                 sprintf "%s[%s]",$szmap{$sz},$self->{label};
268             } else {
269                 sprintf "%s[%s%s]",$szmap{$sz},
270                                         $self->{label}?"$self->{label}+":"",
271                                         $self->{base};
272             }
273         }
274     }
275 }
276 { package register;     # pick up registers, which start with %.
277     sub re {
278         my      $class = shift; # muliple instances...
279         my      $self = {};
280         local   *line = shift;
281         undef   $ret;
282
283         # optional * ---vvv--- appears in indirect jmp/call
284         if ($line =~ /^(\*?)%(\w+)/) {
285             bless $self,$class;
286             $self->{asterisk} = $1;
287             $self->{value} = $2;
288             $ret = $self;
289             $line = substr($line,@+[0]); $line =~ s/^\s+//;
290         }
291         $ret;
292     }
293     sub size {
294         my      $self = shift;
295         undef   $ret;
296
297         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
298         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
299         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
300         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
301         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
302         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
303         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
304         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
305
306         $ret;
307     }
308     sub out {
309         my $self = shift;
310         if ($gas)       { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
311         else            { $self->{value}; }
312     }
313 }
314 { package label;        # pick up labels, which end with :
315     sub re {
316         my      $self = shift;  # single instance is enough...
317         local   *line = shift;
318         undef   $ret;
319
320         if ($line =~ /(^[\.\w]+)\:/) {
321             $self->{value} = $1;
322             $ret = $self;
323             $line = substr($line,@+[0]); $line =~ s/^\s+//;
324
325             $self->{value} =~ s/\.L/\$L\$/ if (!$gas);
326             $self->{value} =~ s/\.L/L\$/   if (!$elf);
327         }
328         $ret;
329     }
330     sub out {
331         my $self = shift;
332
333         if ($gas) {
334             my $func = ($globals{$self->{value}} or $self->{value}) . ":";
335             if ($win64  &&
336                         $current_function->{name} eq $self->{value} &&
337                         $current_function->{abi} eq "svr4") {
338                 $func .= "\n";
339                 $func .= "      movq    %rdi,8(%rsp)\n";
340                 $func .= "      movq    %rsi,16(%rsp)\n";
341                 $func .= "      movq    %rsp,%rax\n";
342                 $func .= ".LSEH_begin_$current_function->{name}:\n";
343                 my $narg = $current_function->{narg};
344                 $narg=6 if (!defined($narg));
345                 $func .= "      movq    %rcx,%rdi\n" if ($narg>0);
346                 $func .= "      movq    %rdx,%rsi\n" if ($narg>1);
347                 $func .= "      movq    %r8,%rdx\n"  if ($narg>2);
348                 $func .= "      movq    %r9,%rcx\n"  if ($narg>3);
349                 $func .= "      movq    40(%rsp),%r8\n" if ($narg>4);
350                 $func .= "      movq    48(%rsp),%r9\n" if ($narg>5);
351             }
352             $func;
353         } elsif ($self->{value} ne "$current_function->{name}") {
354             $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
355             $self->{value} . ":";
356         } elsif ($win64 && $current_function->{abi} eq "svr4") {
357             my $func =  "$current_function->{name}" .
358                         ($nasm ? ":" : "\tPROC $current_function->{scope}") .
359                         "\n";
360             $func .= "  mov     QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
361             $func .= "  mov     QWORD${PTR}[16+rsp],rsi\n";
362             $func .= "  mov     rax,rsp\n";
363             $func .= "\$L\$SEH_begin_$current_function->{name}:";
364             $func .= ":" if ($masm);
365             $func .= "\n";
366             my $narg = $current_function->{narg};
367             $narg=6 if (!defined($narg));
368             $func .= "  mov     rdi,rcx\n" if ($narg>0);
369             $func .= "  mov     rsi,rdx\n" if ($narg>1);
370             $func .= "  mov     rdx,r8\n"  if ($narg>2);
371             $func .= "  mov     rcx,r9\n"  if ($narg>3);
372             $func .= "  mov     r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
373             $func .= "  mov     r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
374             $func .= "\n";
375         } else {
376            "$current_function->{name}".
377                         ($nasm ? ":" : "\tPROC $current_function->{scope}");
378         }
379     }
380 }
381 { package expr;         # pick up expressioins
382     sub re {
383         my      $self = shift;  # single instance is enough...
384         local   *line = shift;
385         undef   $ret;
386
387         if ($line =~ /(^[^,]+)/) {
388             $self->{value} = $1;
389             $ret = $self;
390             $line = substr($line,@+[0]); $line =~ s/^\s+//;
391
392             $self->{value} =~ s/\@PLT// if (!$elf);
393             $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
394             $self->{value} =~ s/\.L/\$L\$/g if (!$gas);
395             $self->{value} =~ s/\.L/L\$/g   if (!$elf);
396         }
397         $ret;
398     }
399     sub out {
400         my $self = shift;
401         if ($nasm && opcode->mnemonic()=~m/^j/) {
402             "NEAR ".$self->{value};
403         } else {
404             $self->{value};
405         }
406     }
407 }
408 { package directive;    # pick up directives, which start with .
409     sub re {
410         my      $self = shift;  # single instance is enough...
411         local   *line = shift;
412         undef   $ret;
413         my      $dir;
414         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
415                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
416                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
417                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
418                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
419                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
420                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
421                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
422                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
423
424         if ($line =~ /^\s*(\.\w+)/) {
425             $dir = $1;
426             $ret = $self;
427             undef $self->{value};
428             $line = substr($line,@+[0]); $line =~ s/^\s+//;
429
430             SWITCH: for ($dir) {
431                 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
432                                         $dir="\t.long";
433                                         $line=sprintf "0x%x,0x90000000",$opcode{$1};
434                                     }
435                                     last;
436                                   };
437                 /\.global|\.globl|\.extern/
438                             && do { $globals{$line} = $prefix . $line;
439                                     $line = $globals{$line} if ($prefix);
440                                     last;
441                                   };
442                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
443                                     if ($type eq "\@function") {
444                                         undef $current_function;
445                                         $current_function->{name} = $sym;
446                                         $current_function->{abi}  = "svr4";
447                                         $current_function->{narg} = $narg;
448                                         $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
449                                     } elsif ($type eq "\@abi-omnipotent") {
450                                         undef $current_function;
451                                         $current_function->{name} = $sym;
452                                         $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
453                                     }
454                                     $line =~ s/\@abi\-omnipotent/\@function/;
455                                     $line =~ s/\@function.*/\@function/;
456                                     last;
457                                   };
458                 /\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
459                                         $dir  = ".byte";
460                                         $line = join(",",unpack("C*",$1),0);
461                                     }
462                                     last;
463                                   };
464             }
465
466             if ($gas) {
467                 $self->{value} = $dir . "\t" . $line;
468
469                 if ($dir =~ /\.extern/) {
470                     $self->{value} = ""; # swallow extern
471                 } elsif (!$elf && $dir =~ /\.type/) {
472                     $self->{value} = "";
473                     $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
474                                 (defined($globals{$1})?".scl 2;":".scl 3;") .
475                                 "\t.type 32;\t.endef"
476                                 if ($win64 && $line =~ /([^,]+),\@function/);
477                 } elsif (!$elf && $dir =~ /\.size/) {
478                     $self->{value} = "";
479                     if (defined($current_function)) {
480                         $self->{value} .= ".LSEH_end_$current_function->{name}:"
481                                 if ($win64 && $current_function->{abi} eq "svr4");
482                         undef $current_function;
483                     }
484                 } elsif (!$elf && $dir =~ /\.align/) {
485                     $self->{value} = ".p2align\t" . (log($line)/log(2));
486                 } elsif ($dir eq ".section") {
487                     $current_segment=$line;
488                     if (!$elf && $current_segment eq ".init") {
489                         if      ($flavour eq "macosx")  { $self->{value} = ".mod_init_func"; }
490                         elsif   ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
491                     }
492                 } elsif ($dir =~ /\.(text|data)/) {
493                     $current_segment=".$1";
494                 }
495                 $line = "";
496                 return $self;
497             }
498
499             # non-gas case or nasm/masm
500             SWITCH: for ($dir) {
501                 /\.text/    && do { my $v=undef;
502                                     if ($nasm) {
503                                         $v="section     .text code align=64\n";
504                                     } else {
505                                         $v="$current_segment\tENDS\n" if ($current_segment);
506                                         $current_segment = ".text\$";
507                                         $v.="$current_segment\tSEGMENT ";
508                                         $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
509                                         $v.=" 'CODE'";
510                                     }
511                                     $self->{value} = $v;
512                                     last;
513                                   };
514                 /\.data/    && do { my $v=undef;
515                                     if ($nasm) {
516                                         $v="section     .data data align=8\n";
517                                     } else {
518                                         $v="$current_segment\tENDS\n" if ($current_segment);
519                                         $current_segment = "_DATA";
520                                         $v.="$current_segment\tSEGMENT";
521                                     }
522                                     $self->{value} = $v;
523                                     last;
524                                   };
525                 /\.section/ && do { my $v=undef;
526                                     $line =~ s/([^,]*).*/$1/;
527                                     $line = ".CRT\$XCU" if ($line eq ".init");
528                                     if ($nasm) {
529                                         $v="section     $line";
530                                         if ($line=~/\.([px])data/) {
531                                             $v.=" rdata align=";
532                                             $v.=$1 eq "p"? 4 : 8;
533                                         }
534                                     } else {
535                                         $v="$current_segment\tENDS\n" if ($current_segment);
536                                         $v.="$line\tSEGMENT";
537                                         if ($line=~/\.([px])data/) {
538                                             $v.=" READONLY";
539                                             $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
540                                         }
541                                     }
542                                     $current_segment = $line;
543                                     $self->{value} = $v;
544                                     last;
545                                   };
546                 /\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
547                                     $self->{value} .= ":NEAR" if ($masm);
548                                     last;
549                                   };
550                 /\.globl|.global/
551                             && do { $self->{value}  = $masm?"PUBLIC":"global";
552                                     $self->{value} .= "\t".$line;
553                                     last;
554                                   };
555                 /\.size/    && do { if (defined($current_function)) {
556                                         undef $self->{value};
557                                         if ($current_function->{abi} eq "svr4") {
558                                             $self->{value}="\$L\$SEH_end_$current_function->{name}:";
559                                             $self->{value}.=":\n" if($masm);
560                                         }
561                                         $self->{value}.="$current_function->{name}\tENDP" if($masm);
562                                         undef $current_function;
563                                     }
564                                     last;
565                                   };
566                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
567                 /\.(value|long|rva|quad)/
568                             && do { my $sz  = substr($1,0,1);
569                                     my @arr = split(',',$line);
570                                     my $last = pop(@arr);
571                                     my $conv = sub  {   my $var=shift;
572                                                         $var=~s/0x([0-9a-f]+)/0$1h/ig;
573                                                         $var=~s/\.L/\$L\$/g;
574                                                         if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
575                                                         { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
576                                                         $var;
577                                                     };  
578
579                                     $sz =~ tr/bvlrq/BWDDQ/;
580                                     $self->{value} = "\tD$sz\t";
581                                     for (@arr) { $self->{value} .= &$conv($_).","; }
582                                     $self->{value} .= &$conv($last);
583                                     last;
584                                   };
585                 /\.byte/    && do { my @str=split(",",$line);
586                                     while ($#str>15) {
587                                         $self->{value}.="DB\t"
588                                                 .join(",",@str[0..15])."\n";
589                                         foreach (0..15) { shift @str; }
590                                     }
591                                     $self->{value}.="DB\t"
592                                                 .join(",",@str) if (@str);
593                                     last;
594                                   };
595             }
596             $line = "";
597         }
598
599         $ret;
600     }
601     sub out {
602         my $self = shift;
603         $self->{value};
604     }
605 }
606
607 if ($nasm) {
608     print <<___;
609 default rel
610 ___
611 } elsif ($masm) {
612     print <<___;
613 OPTION  DOTNAME
614 ___
615 }
616 while($line=<>) {
617
618     chomp($line);
619
620     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
621     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
622     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
623
624     undef $label;
625     undef $opcode;
626     undef $dst;
627     undef $src;
628     undef $sz;
629
630     if ($label=label->re(\$line))       { print $label->out(); }
631
632     if (directive->re(\$line)) {
633         printf "%s",directive->out();
634     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
635
636         if ($src=register->re(\$line))  { opcode->size($src->size()); }
637         elsif ($src=const->re(\$line))  { }
638         elsif ($src=ea->re(\$line))     { }
639         elsif ($src=expr->re(\$line))   { }
640
641         last ARGUMENT if ($line !~ /^,/);
642
643         $line = substr($line,1); $line =~ s/^\s+//;
644
645         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
646         elsif ($dst=const->re(\$line))  { }
647         elsif ($dst=ea->re(\$line))     { }
648
649         } # ARGUMENT:
650
651         $sz=opcode->size();
652
653         if (defined($dst)) {
654             if ($gas) {
655                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
656                                         $src->out($sz),$dst->out($sz);
657             } else {
658                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
659                 printf "\t%s\t%s,%s",   $opcode->out(),
660                                         $dst->out($sz),$src->out($sz);
661             }
662         } elsif (defined($src)) {
663             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
664         } else {
665             printf "\t%s",$opcode->out();
666         }
667     }
668
669     print $line,"\n";
670 }
671
672 print "\n$current_segment\tENDS\n"      if ($current_segment && $masm);
673 print "END\n"                           if ($masm);
674
675 close STDOUT;
676
677 \f#################################################
678 # Cross-reference x86_64 ABI "card"
679 #
680 #               Unix            Win64
681 # %rax          *               *
682 # %rbx          -               -
683 # %rcx          #4              #1
684 # %rdx          #3              #2
685 # %rsi          #2              -
686 # %rdi          #1              -
687 # %rbp          -               -
688 # %rsp          -               -
689 # %r8           #5              #3
690 # %r9           #6              #4
691 # %r10          *               *
692 # %r11          *               *
693 # %r12          -               -
694 # %r13          -               -
695 # %r14          -               -
696 # %r15          -               -
697
698 # (*)   volatile register
699 # (-)   preserved by callee
700 # (#)   Nth argument, volatile
701 #
702 # In Unix terms top of stack is argument transfer area for arguments
703 # which could not be accomodated in registers. Or in other words 7th
704 # [integer] argument resides at 8(%rsp) upon function entry point.
705 # 128 bytes above %rsp constitute a "red zone" which is not touched
706 # by signal handlers and can be used as temporal storage without
707 # allocating a frame.
708 #
709 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
710 # which belongs to/can be overwritten by callee. N is the number of
711 # arguments passed to callee, *but* not less than 4! This means that
712 # upon function entry point 5th argument resides at 40(%rsp), as well
713 # as that 32 bytes from 8(%rsp) can always be used as temporal
714 # storage [without allocating a frame]. One can actually argue that
715 # one can assume a "red zone" above stack pointer under Win64 as well.
716 # Point is that at apparently no occasion Windows kernel would alter
717 # the area above user stack pointer in true asynchronous manner...
718 #
719 # All the above means that if assembler programmer adheres to Unix
720 # register and stack layout, but disregards the "red zone" existense,
721 # it's possible to use following prologue and epilogue to "gear" from
722 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
723 #
724 # omnipotent_function:
725 # ifdef WIN64
726 #       movq    %rdi,8(%rsp)
727 #       movq    %rsi,16(%rsp)
728 #       movq    %rcx,%rdi       ; if 1st argument is actually present
729 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
730 #       movq    %r8,%rdx        ; if 3rd argument is ...
731 #       movq    %r9,%rcx        ; if 4th argument ...
732 #       movq    40(%rsp),%r8    ; if 5th ...
733 #       movq    48(%rsp),%r9    ; if 6th ...
734 # endif
735 #       ...
736 # ifdef WIN64
737 #       movq    8(%rsp),%rdi
738 #       movq    16(%rsp),%rsi
739 # endif
740 #       ret
741 #
742 \f#################################################
743 # Win64 SEH, Structured Exception Handling.
744 #
745 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
746 # has undesired side-effect at run-time: if an exception is raised in
747 # assembler subroutine such as those in question (basically we're
748 # referring to segmentation violations caused by malformed input
749 # parameters), the application is briskly terminated without invoking
750 # any exception handlers, most notably without generating memory dump
751 # or any user notification whatsoever. This poses a problem. It's
752 # possible to address it by registering custom language-specific
753 # handler that would restore processor context to the state at
754 # subroutine entry point and return "exception is not handled, keep
755 # unwinding" code. Writing such handler can be a challenge... But it's
756 # doable, though requires certain coding convention. Consider following
757 # snippet:
758 #
759 # .type function,@function
760 # function:
761 #       movq    %rsp,%rax       # copy rsp to volatile register
762 #       pushq   %r15            # save non-volatile registers
763 #       pushq   %rbx
764 #       pushq   %rbp
765 #       movq    %rsp,%r11
766 #       subq    %rdi,%r11       # prepare [variable] stack frame
767 #       andq    $-64,%r11
768 #       movq    %rax,0(%r11)    # check for exceptions
769 #       movq    %r11,%rsp       # allocate [variable] stack frame
770 #       movq    %rax,0(%rsp)    # save original rsp value
771 # magic_point:
772 #       ...
773 #       movq    0(%rsp),%rcx    # pull original rsp value
774 #       movq    -24(%rcx),%rbp  # restore non-volatile registers
775 #       movq    -16(%rcx),%rbx
776 #       movq    -8(%rcx),%r15
777 #       movq    %rcx,%rsp       # restore original rsp
778 #       ret
779 # .size function,.-function
780 #
781 # The key is that up to magic_point copy of original rsp value remains
782 # in chosen volatile register and no non-volatile register, except for
783 # rsp, is modified. While past magic_point rsp remains constant till
784 # the very end of the function. In this case custom language-specific
785 # exception handler would look like this:
786 #
787 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
788 #               CONTEXT *context,DISPATCHER_CONTEXT *disp)
789 # {     ULONG64 *rsp = (ULONG64 *)context->Rax;
790 #       if (context->Rip >= magic_point)
791 #       {   rsp = ((ULONG64 **)context->Rsp)[0];
792 #           context->Rbp = rsp[-3];
793 #           context->Rbx = rsp[-2];
794 #           context->R15 = rsp[-1];
795 #       }
796 #       context->Rsp = (ULONG64)rsp;
797 #       context->Rdi = rsp[1];
798 #       context->Rsi = rsp[2];
799 #
800 #       memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
801 #       RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
802 #               dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
803 #               &disp->HandlerData,&disp->EstablisherFrame,NULL);
804 #       return ExceptionContinueSearch;
805 # }
806 #
807 # It's appropriate to implement this handler in assembler, directly in
808 # function's module. In order to do that one has to know members'
809 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
810 # values. Here they are:
811 #
812 #       CONTEXT.Rax                             120
813 #       CONTEXT.Rcx                             128
814 #       CONTEXT.Rdx                             136
815 #       CONTEXT.Rbx                             144
816 #       CONTEXT.Rsp                             152
817 #       CONTEXT.Rbp                             160
818 #       CONTEXT.Rsi                             168
819 #       CONTEXT.Rdi                             176
820 #       CONTEXT.R8                              184
821 #       CONTEXT.R9                              192
822 #       CONTEXT.R10                             200
823 #       CONTEXT.R11                             208
824 #       CONTEXT.R12                             216
825 #       CONTEXT.R13                             224
826 #       CONTEXT.R14                             232
827 #       CONTEXT.R15                             240
828 #       CONTEXT.Rip                             248
829 #       sizeof(CONTEXT)                         1232
830 #       DISPATCHER_CONTEXT.ControlPc            0
831 #       DISPATCHER_CONTEXT.ImageBase            8
832 #       DISPATCHER_CONTEXT.FunctionEntry        16
833 #       DISPATCHER_CONTEXT.EstablisherFrame     24
834 #       DISPATCHER_CONTEXT.TargetIp             32
835 #       DISPATCHER_CONTEXT.ContextRecord        40
836 #       DISPATCHER_CONTEXT.LanguageHandler      48
837 #       DISPATCHER_CONTEXT.HandlerData          56
838 #       UNW_FLAG_NHANDLER                       0
839 #       ExceptionContinueSearch                 1
840 #
841 # In order to tie the handler to the function one has to compose
842 # couple of structures: one for .xdata segment and one for .pdata.
843 #
844 # UNWIND_INFO structure for .xdata segment would be
845 #
846 # function_unwind_info:
847 #       .byte   9,0,0,0
848 #       .rva    handler
849 #
850 # This structure designates exception handler for a function with
851 # zero-length prologue, no stack frame or frame register.
852 #
853 # To facilitate composing of .pdata structures, auto-generated "gear"
854 # prologue copies rsp value to rax and denotes next instruction with
855 # .LSEH_begin_{function_name} label. This essentially defines the SEH
856 # styling rule mentioned in the beginning. Position of this label is
857 # chosen in such manner that possible exceptions raised in the "gear"
858 # prologue would be accounted to caller and unwound from latter's frame.
859 # End of function is marked with respective .LSEH_end_{function_name}
860 # label. To summarize, .pdata segment would contain
861 #
862 #       .rva    .LSEH_begin_function
863 #       .rva    .LSEH_end_function
864 #       .rva    function_unwind_info
865 #
866 # Reference to functon_unwind_info from .xdata segment is the anchor.
867 # In case you wonder why references are 32-bit .rvas and not 64-bit
868 # .quads. References put into these two segments are required to be
869 # *relative* to the base address of the current binary module, a.k.a.
870 # image base. No Win64 module, be it .exe or .dll, can be larger than
871 # 2GB and thus such relative references can be and are accommodated in
872 # 32 bits.
873 #
874 # Having reviewed the example function code, one can argue that "movq
875 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
876 # rax would contain an undefined value. If this "offends" you, use
877 # another register and refrain from modifying rax till magic_point is
878 # reached, i.e. as if it was a non-volatile register. If more registers
879 # are required prior [variable] frame setup is completed, note that
880 # nobody says that you can have only one "magic point." You can
881 # "liberate" non-volatile registers by denoting last stack off-load
882 # instruction and reflecting it in finer grade unwind logic in handler.
883 # After all, isn't it why it's called *language-specific* handler...
884 #
885 # Attentive reader can notice that exceptions would be mishandled in
886 # auto-generated "gear" epilogue. Well, exception effectively can't
887 # occur there, because if memory area used by it was subject to
888 # segmentation violation, then it would be raised upon call to the
889 # function (and as already mentioned be accounted to caller, which is
890 # not a problem). If you're still not comfortable, then define tail
891 # "magic point" just prior ret instruction and have handler treat it...
892 #
893 # (*)   Note that we're talking about run-time, not debug-time. Lack of
894 #       unwind information makes debugging hard on both Windows and
895 #       Unix. "Unlike" referes to the fact that on Unix signal handler
896 #       will always be invoked, core dumped and appropriate exit code
897 #       returned to parent (for user notification).