Fix for CVE-2014-0076
[oweals/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 open STDOUT,">$output" || die "can't open $output: $!"
66         if (defined($output));
67
68 my $gas=1;      $gas=0 if ($output =~ /\.asm$/);
69 my $elf=1;      $elf=0 if (!$gas);
70 my $win64=0;
71 my $prefix="";
72 my $decor=".L";
73
74 my $masmref=8 + 50727*2**-32;   # 8.00.50727 shipped with VS2005
75 my $masm=0;
76 my $PTR=" PTR";
77
78 my $nasmref=2.03;
79 my $nasm=0;
80
81 if    ($flavour eq "mingw64")   { $gas=1; $elf=0; $win64=1;
82                                   $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
83                                   chomp($prefix);
84                                 }
85 elsif ($flavour eq "macosx")    { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
86 elsif ($flavour eq "masm")      { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
87 elsif ($flavour eq "nasm")      { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
88 elsif (!$gas)
89 {   if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
90     {   $nasm = $1 + $2*0.01; $PTR="";  }
91     elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
92     {   $masm = $1 + $2*2**-16 + $4*2**-32;   }
93     die "no assembler found on %PATH" if (!($nasm || $masm));
94     $win64=1;
95     $elf=0;
96     $decor="\$L\$";
97 }
98
99 my $current_segment;
100 my $current_function;
101 my %globals;
102
103 { package opcode;       # pick up opcodes
104     sub re {
105         my      $self = shift;  # single instance in enough...
106         local   *line = shift;
107         undef   $ret;
108
109         if ($line =~ /^([a-z][a-z0-9]*)/i) {
110             $self->{op} = $1;
111             $ret = $self;
112             $line = substr($line,@+[0]); $line =~ s/^\s+//;
113
114             undef $self->{sz};
115             if ($self->{op} =~ /^(movz)b.*/) {  # movz is pain...
116                 $self->{op} = $1;
117                 $self->{sz} = "b";
118             } elsif ($self->{op} =~ /call|jmp/) {
119                 $self->{sz} = "";
120             } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op)/) { # SSEn
121                 $self->{sz} = "";
122             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
123                 $self->{op} = $1;
124                 $self->{sz} = $2;
125             }
126         }
127         $ret;
128     }
129     sub size {
130         my $self = shift;
131         my $sz   = shift;
132         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
133         $self->{sz};
134     }
135     sub out {
136         my $self = shift;
137         if ($gas) {
138             if ($self->{op} eq "movz") {        # movz is pain...
139                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
140             } elsif ($self->{op} =~ /^set/) { 
141                 "$self->{op}";
142             } elsif ($self->{op} eq "ret") {
143                 my $epilogue = "";
144                 if ($win64 && $current_function->{abi} eq "svr4") {
145                     $epilogue = "movq   8(%rsp),%rdi\n\t" .
146                                 "movq   16(%rsp),%rsi\n\t";
147                 }
148                 $epilogue . ".byte      0xf3,0xc3";
149             } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
150                 ".p2align\t3\n\t.quad";
151             } else {
152                 "$self->{op}$self->{sz}";
153             }
154         } else {
155             $self->{op} =~ s/^movz/movzx/;
156             if ($self->{op} eq "ret") {
157                 $self->{op} = "";
158                 if ($win64 && $current_function->{abi} eq "svr4") {
159                     $self->{op} = "mov  rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
160                                   "mov  rsi,QWORD${PTR}[16+rsp]\n\t";
161                 }
162                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
163             } elsif ($self->{op} =~ /^(pop|push)f/) {
164                 $self->{op} .= $self->{sz};
165             } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
166                 $self->{op} = "\tDQ";
167             } 
168             $self->{op};
169         }
170     }
171     sub mnemonic {
172         my $self=shift;
173         my $op=shift;
174         $self->{op}=$op if (defined($op));
175         $self->{op};
176     }
177 }
178 { package const;        # pick up constants, which start with $
179     sub re {
180         my      $self = shift;  # single instance in enough...
181         local   *line = shift;
182         undef   $ret;
183
184         if ($line =~ /^\$([^,]+)/) {
185             $self->{value} = $1;
186             $ret = $self;
187             $line = substr($line,@+[0]); $line =~ s/^\s+//;
188         }
189         $ret;
190     }
191     sub out {
192         my $self = shift;
193
194         if ($gas) {
195             # Solaris /usr/ccs/bin/as can't handle multiplications
196             # in $self->{value}
197             $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
198             $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
199             sprintf "\$%s",$self->{value};
200         } else {
201             $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
202             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
203             sprintf "%s",$self->{value};
204         }
205     }
206 }
207 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
208     sub re {
209         my      $self = shift;  # single instance in enough...
210         local   *line = shift;
211         undef   $ret;
212
213         # optional * ---vvv--- appears in indirect jmp/call
214         if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
215             $self->{asterisk} = $1;
216             $self->{label} = $2;
217             ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
218             $self->{scale} = 1 if (!defined($self->{scale}));
219             $ret = $self;
220             $line = substr($line,@+[0]); $line =~ s/^\s+//;
221
222             if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
223                 die if (opcode->mnemonic() ne "mov");
224                 opcode->mnemonic("lea");
225             }
226             $self->{base}  =~ s/^%//;
227             $self->{index} =~ s/^%// if (defined($self->{index}));
228         }
229         $ret;
230     }
231     sub size {}
232     sub out {
233         my $self = shift;
234         my $sz = shift;
235
236         $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
237         $self->{label} =~ s/\.L/$decor/g;
238
239         # Silently convert all EAs to 64-bit. This is required for
240         # elder GNU assembler and results in more compact code,
241         # *but* most importantly AES module depends on this feature!
242         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
243         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
244
245         if ($gas) {
246             # Solaris /usr/ccs/bin/as can't handle multiplications
247             # in $self->{label}, new gas requires sign extension...
248             use integer;
249             $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
250             $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
251             $self->{label} =~ s/([0-9]+)/$1<<32>>32/eg;
252             $self->{label} =~ s/^___imp_/__imp__/   if ($flavour eq "mingw64");
253
254             if (defined($self->{index})) {
255                 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk},
256                                         $self->{label},$self->{base},
257                                         $self->{index},$self->{scale};
258             } else {
259                 sprintf "%s%s(%%%s)",   $self->{asterisk},$self->{label},$self->{base};
260             }
261         } else {
262             %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
263
264             $self->{label} =~ s/\./\$/g;
265             $self->{label} =~ s/(?<![\w\$\.])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                                         } elsif ($line=~/\.CRT\$/i) {
545                                             $v.=" rdata align=8";
546                                         }
547                                     } else {
548                                         $v="$current_segment\tENDS\n" if ($current_segment);
549                                         $v.="$line\tSEGMENT";
550                                         if ($line=~/\.([px])data/) {
551                                             $v.=" READONLY";
552                                             $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
553                                         } elsif ($line=~/\.CRT\$/i) {
554                                             $v.=" READONLY ";
555                                             $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
556                                         }
557                                     }
558                                     $current_segment = $line;
559                                     $self->{value} = $v;
560                                     last;
561                                   };
562                 /\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
563                                     $self->{value} .= ":NEAR" if ($masm);
564                                     last;
565                                   };
566                 /\.globl|.global/
567                             && do { $self->{value}  = $masm?"PUBLIC":"global";
568                                     $self->{value} .= "\t".$line;
569                                     last;
570                                   };
571                 /\.size/    && do { if (defined($current_function)) {
572                                         undef $self->{value};
573                                         if ($current_function->{abi} eq "svr4") {
574                                             $self->{value}="${decor}SEH_end_$current_function->{name}:";
575                                             $self->{value}.=":\n" if($masm);
576                                         }
577                                         $self->{value}.="$current_function->{name}\tENDP" if($masm);
578                                         undef $current_function;
579                                     }
580                                     last;
581                                   };
582                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
583                 /\.(value|long|rva|quad)/
584                             && do { my $sz  = substr($1,0,1);
585                                     my @arr = split(/,\s*/,$line);
586                                     my $last = pop(@arr);
587                                     my $conv = sub  {   my $var=shift;
588                                                         $var=~s/^(0b[0-1]+)/oct($1)/eig;
589                                                         $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
590                                                         if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
591                                                         { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
592                                                         $var;
593                                                     };  
594
595                                     $sz =~ tr/bvlrq/BWDDQ/;
596                                     $self->{value} = "\tD$sz\t";
597                                     for (@arr) { $self->{value} .= &$conv($_).","; }
598                                     $self->{value} .= &$conv($last);
599                                     last;
600                                   };
601                 /\.byte/    && do { my @str=split(/,\s*/,$line);
602                                     map(s/(0b[0-1]+)/oct($1)/eig,@str);
603                                     map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);       
604                                     while ($#str>15) {
605                                         $self->{value}.="DB\t"
606                                                 .join(",",@str[0..15])."\n";
607                                         foreach (0..15) { shift @str; }
608                                     }
609                                     $self->{value}.="DB\t"
610                                                 .join(",",@str) if (@str);
611                                     last;
612                                   };
613             }
614             $line = "";
615         }
616
617         $ret;
618     }
619     sub out {
620         my $self = shift;
621         $self->{value};
622     }
623 }
624
625 if ($nasm) {
626     print <<___;
627 default rel
628 ___
629 } elsif ($masm) {
630     print <<___;
631 OPTION  DOTNAME
632 ___
633 }
634 while($line=<>) {
635
636     chomp($line);
637
638     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
639     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
640     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
641
642     undef $label;
643     undef $opcode;
644     undef $sz;
645     undef @args;
646
647     if ($label=label->re(\$line))       { print $label->out(); }
648
649     if (directive->re(\$line)) {
650         printf "%s",directive->out();
651     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: while (1) {
652         my $arg;
653
654         if ($arg=register->re(\$line))  { opcode->size($arg->size()); }
655         elsif ($arg=const->re(\$line))  { }
656         elsif ($arg=ea->re(\$line))     { }
657         elsif ($arg=expr->re(\$line))   { }
658         else                            { last ARGUMENT; }
659
660         push @args,$arg;
661
662         last ARGUMENT if ($line !~ /^,/);
663
664         $line =~ s/^,\s*//;
665         } # ARGUMENT:
666
667         $sz=opcode->size();
668
669         if ($#args>=0) {
670             my $insn;
671             if ($gas) {
672                 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
673             } else {
674                 $insn = $opcode->out();
675                 $insn .= $sz if (map($_->out() =~ /x?mm/,@args));
676                 @args = reverse(@args);
677                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
678             }
679             printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
680         } else {
681             printf "\t%s",$opcode->out();
682         }
683     }
684
685     print $line,"\n";
686 }
687
688 print "\n$current_segment\tENDS\n"      if ($current_segment && $masm);
689 print "END\n"                           if ($masm);
690
691 close STDOUT;
692
693 \f#################################################
694 # Cross-reference x86_64 ABI "card"
695 #
696 #               Unix            Win64
697 # %rax          *               *
698 # %rbx          -               -
699 # %rcx          #4              #1
700 # %rdx          #3              #2
701 # %rsi          #2              -
702 # %rdi          #1              -
703 # %rbp          -               -
704 # %rsp          -               -
705 # %r8           #5              #3
706 # %r9           #6              #4
707 # %r10          *               *
708 # %r11          *               *
709 # %r12          -               -
710 # %r13          -               -
711 # %r14          -               -
712 # %r15          -               -
713
714 # (*)   volatile register
715 # (-)   preserved by callee
716 # (#)   Nth argument, volatile
717 #
718 # In Unix terms top of stack is argument transfer area for arguments
719 # which could not be accomodated in registers. Or in other words 7th
720 # [integer] argument resides at 8(%rsp) upon function entry point.
721 # 128 bytes above %rsp constitute a "red zone" which is not touched
722 # by signal handlers and can be used as temporal storage without
723 # allocating a frame.
724 #
725 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
726 # which belongs to/can be overwritten by callee. N is the number of
727 # arguments passed to callee, *but* not less than 4! This means that
728 # upon function entry point 5th argument resides at 40(%rsp), as well
729 # as that 32 bytes from 8(%rsp) can always be used as temporal
730 # storage [without allocating a frame]. One can actually argue that
731 # one can assume a "red zone" above stack pointer under Win64 as well.
732 # Point is that at apparently no occasion Windows kernel would alter
733 # the area above user stack pointer in true asynchronous manner...
734 #
735 # All the above means that if assembler programmer adheres to Unix
736 # register and stack layout, but disregards the "red zone" existense,
737 # it's possible to use following prologue and epilogue to "gear" from
738 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
739 #
740 # omnipotent_function:
741 # ifdef WIN64
742 #       movq    %rdi,8(%rsp)
743 #       movq    %rsi,16(%rsp)
744 #       movq    %rcx,%rdi       ; if 1st argument is actually present
745 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
746 #       movq    %r8,%rdx        ; if 3rd argument is ...
747 #       movq    %r9,%rcx        ; if 4th argument ...
748 #       movq    40(%rsp),%r8    ; if 5th ...
749 #       movq    48(%rsp),%r9    ; if 6th ...
750 # endif
751 #       ...
752 # ifdef WIN64
753 #       movq    8(%rsp),%rdi
754 #       movq    16(%rsp),%rsi
755 # endif
756 #       ret
757 #
758 \f#################################################
759 # Win64 SEH, Structured Exception Handling.
760 #
761 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
762 # has undesired side-effect at run-time: if an exception is raised in
763 # assembler subroutine such as those in question (basically we're
764 # referring to segmentation violations caused by malformed input
765 # parameters), the application is briskly terminated without invoking
766 # any exception handlers, most notably without generating memory dump
767 # or any user notification whatsoever. This poses a problem. It's
768 # possible to address it by registering custom language-specific
769 # handler that would restore processor context to the state at
770 # subroutine entry point and return "exception is not handled, keep
771 # unwinding" code. Writing such handler can be a challenge... But it's
772 # doable, though requires certain coding convention. Consider following
773 # snippet:
774 #
775 # .type function,@function
776 # function:
777 #       movq    %rsp,%rax       # copy rsp to volatile register
778 #       pushq   %r15            # save non-volatile registers
779 #       pushq   %rbx
780 #       pushq   %rbp
781 #       movq    %rsp,%r11
782 #       subq    %rdi,%r11       # prepare [variable] stack frame
783 #       andq    $-64,%r11
784 #       movq    %rax,0(%r11)    # check for exceptions
785 #       movq    %r11,%rsp       # allocate [variable] stack frame
786 #       movq    %rax,0(%rsp)    # save original rsp value
787 # magic_point:
788 #       ...
789 #       movq    0(%rsp),%rcx    # pull original rsp value
790 #       movq    -24(%rcx),%rbp  # restore non-volatile registers
791 #       movq    -16(%rcx),%rbx
792 #       movq    -8(%rcx),%r15
793 #       movq    %rcx,%rsp       # restore original rsp
794 #       ret
795 # .size function,.-function
796 #
797 # The key is that up to magic_point copy of original rsp value remains
798 # in chosen volatile register and no non-volatile register, except for
799 # rsp, is modified. While past magic_point rsp remains constant till
800 # the very end of the function. In this case custom language-specific
801 # exception handler would look like this:
802 #
803 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
804 #               CONTEXT *context,DISPATCHER_CONTEXT *disp)
805 # {     ULONG64 *rsp = (ULONG64 *)context->Rax;
806 #       if (context->Rip >= magic_point)
807 #       {   rsp = ((ULONG64 **)context->Rsp)[0];
808 #           context->Rbp = rsp[-3];
809 #           context->Rbx = rsp[-2];
810 #           context->R15 = rsp[-1];
811 #       }
812 #       context->Rsp = (ULONG64)rsp;
813 #       context->Rdi = rsp[1];
814 #       context->Rsi = rsp[2];
815 #
816 #       memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
817 #       RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
818 #               dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
819 #               &disp->HandlerData,&disp->EstablisherFrame,NULL);
820 #       return ExceptionContinueSearch;
821 # }
822 #
823 # It's appropriate to implement this handler in assembler, directly in
824 # function's module. In order to do that one has to know members'
825 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
826 # values. Here they are:
827 #
828 #       CONTEXT.Rax                             120
829 #       CONTEXT.Rcx                             128
830 #       CONTEXT.Rdx                             136
831 #       CONTEXT.Rbx                             144
832 #       CONTEXT.Rsp                             152
833 #       CONTEXT.Rbp                             160
834 #       CONTEXT.Rsi                             168
835 #       CONTEXT.Rdi                             176
836 #       CONTEXT.R8                              184
837 #       CONTEXT.R9                              192
838 #       CONTEXT.R10                             200
839 #       CONTEXT.R11                             208
840 #       CONTEXT.R12                             216
841 #       CONTEXT.R13                             224
842 #       CONTEXT.R14                             232
843 #       CONTEXT.R15                             240
844 #       CONTEXT.Rip                             248
845 #       CONTEXT.Xmm6                            512
846 #       sizeof(CONTEXT)                         1232
847 #       DISPATCHER_CONTEXT.ControlPc            0
848 #       DISPATCHER_CONTEXT.ImageBase            8
849 #       DISPATCHER_CONTEXT.FunctionEntry        16
850 #       DISPATCHER_CONTEXT.EstablisherFrame     24
851 #       DISPATCHER_CONTEXT.TargetIp             32
852 #       DISPATCHER_CONTEXT.ContextRecord        40
853 #       DISPATCHER_CONTEXT.LanguageHandler      48
854 #       DISPATCHER_CONTEXT.HandlerData          56
855 #       UNW_FLAG_NHANDLER                       0
856 #       ExceptionContinueSearch                 1
857 #
858 # In order to tie the handler to the function one has to compose
859 # couple of structures: one for .xdata segment and one for .pdata.
860 #
861 # UNWIND_INFO structure for .xdata segment would be
862 #
863 # function_unwind_info:
864 #       .byte   9,0,0,0
865 #       .rva    handler
866 #
867 # This structure designates exception handler for a function with
868 # zero-length prologue, no stack frame or frame register.
869 #
870 # To facilitate composing of .pdata structures, auto-generated "gear"
871 # prologue copies rsp value to rax and denotes next instruction with
872 # .LSEH_begin_{function_name} label. This essentially defines the SEH
873 # styling rule mentioned in the beginning. Position of this label is
874 # chosen in such manner that possible exceptions raised in the "gear"
875 # prologue would be accounted to caller and unwound from latter's frame.
876 # End of function is marked with respective .LSEH_end_{function_name}
877 # label. To summarize, .pdata segment would contain
878 #
879 #       .rva    .LSEH_begin_function
880 #       .rva    .LSEH_end_function
881 #       .rva    function_unwind_info
882 #
883 # Reference to functon_unwind_info from .xdata segment is the anchor.
884 # In case you wonder why references are 32-bit .rvas and not 64-bit
885 # .quads. References put into these two segments are required to be
886 # *relative* to the base address of the current binary module, a.k.a.
887 # image base. No Win64 module, be it .exe or .dll, can be larger than
888 # 2GB and thus such relative references can be and are accommodated in
889 # 32 bits.
890 #
891 # Having reviewed the example function code, one can argue that "movq
892 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
893 # rax would contain an undefined value. If this "offends" you, use
894 # another register and refrain from modifying rax till magic_point is
895 # reached, i.e. as if it was a non-volatile register. If more registers
896 # are required prior [variable] frame setup is completed, note that
897 # nobody says that you can have only one "magic point." You can
898 # "liberate" non-volatile registers by denoting last stack off-load
899 # instruction and reflecting it in finer grade unwind logic in handler.
900 # After all, isn't it why it's called *language-specific* handler...
901 #
902 # Attentive reader can notice that exceptions would be mishandled in
903 # auto-generated "gear" epilogue. Well, exception effectively can't
904 # occur there, because if memory area used by it was subject to
905 # segmentation violation, then it would be raised upon call to the
906 # function (and as already mentioned be accounted to caller, which is
907 # not a problem). If you're still not comfortable, then define tail
908 # "magic point" just prior ret instruction and have handler treat it...
909 #
910 # (*)   Note that we're talking about run-time, not debug-time. Lack of
911 #       unwind information makes debugging hard on both Windows and
912 #       Unix. "Unlike" referes to the fact that on Unix signal handler
913 #       will always be invoked, core dumped and appropriate exit code
914 #       returned to parent (for user notification).