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