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