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