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