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