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