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