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