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