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