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