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