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