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