crypto/x86[_64]cpuid.pl: add OPENSSL_ia32_rd[rand|seed]_bytes.
[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}, new gas requires sign extension...
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         $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
270
271         if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
272             $self->{base} =~ /(rbp|r13)/) {
273                 $self->{base} = $self->{index}; $self->{index} = $1;
274         }
275
276         if ($gas) {
277             $self->{label} =~ s/^___imp_/__imp__/   if ($flavour eq "mingw64");
278
279             if (defined($self->{index})) {
280                 sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
281                                         $self->{label},
282                                         $self->{base}?"%$self->{base}":"",
283                                         $self->{index},$self->{scale};
284             } else {
285                 sprintf "%s%s(%%%s)",   $self->{asterisk},$self->{label},$self->{base};
286             }
287         } else {
288             my %szmap = (       b=>"BYTE$PTR",  w=>"WORD$PTR",
289                         l=>"DWORD$PTR", d=>"DWORD$PTR",
290                         q=>"QWORD$PTR", o=>"OWORD$PTR",
291                         x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
292
293             $self->{label} =~ s/\./\$/g;
294             $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
295             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
296
297             my $mnemonic = $self->{opcode}->mnemonic();
298             ($self->{asterisk})                         && ($sz="q") ||
299             ($mnemonic =~ /^v?mov([qd])$/)              && ($sz=$1)  ||
300             ($mnemonic =~ /^v?pinsr([qdwb])$/)          && ($sz=$1)  ||
301             ($mnemonic =~ /^vpbroadcast([qdwb])$/)      && ($sz=$1)  ||
302             ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/)   && ($sz="x");
303
304             if (defined($self->{index})) {
305                 sprintf "%s[%s%s*%d%s]",$szmap{$sz},
306                                         $self->{label}?"$self->{label}+":"",
307                                         $self->{index},$self->{scale},
308                                         $self->{base}?"+$self->{base}":"";
309             } elsif ($self->{base} eq "rip") {
310                 sprintf "%s[%s]",$szmap{$sz},$self->{label};
311             } else {
312                 sprintf "%s[%s%s]",$szmap{$sz},
313                                         $self->{label}?"$self->{label}+":"",
314                                         $self->{base};
315             }
316         }
317     }
318 }
319 { package register;     # pick up registers, which start with %.
320     sub re {
321         my      ($class, $line, $opcode) = @_;
322         my      $self = {};
323         my      $ret;
324
325         # optional * ----vvv--- appears in indirect jmp/call
326         if ($$line =~ /^(\*?)%(\w+)/) {
327             bless $self,$class;
328             $self->{asterisk} = $1;
329             $self->{value} = $2;
330             $opcode->size($self->size());
331             $ret = $self;
332             $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
333         }
334         $ret;
335     }
336     sub size {
337         my      $self = shift;
338         my      $ret;
339
340         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
341         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
342         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
343         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
344         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
345         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
346         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
347         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
348
349         $ret;
350     }
351     sub out {
352         my $self = shift;
353         if ($gas)       { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
354         else            { $self->{value}; }
355     }
356 }
357 { package label;        # pick up labels, which end with :
358     sub re {
359         my      ($class, $line) = @_;
360         my      $self = {};
361         my      $ret;
362
363         if ($$line =~ /(^[\.\w]+)\:/) {
364             bless $self,$class;
365             $self->{value} = $1;
366             $ret = $self;
367             $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
368
369             $self->{value} =~ s/^\.L/$decor/;
370         }
371         $ret;
372     }
373     sub out {
374         my $self = shift;
375
376         if ($gas) {
377             my $func = ($globals{$self->{value}} or $self->{value}) . ":";
378             if ($win64  &&
379                         $current_function->{name} eq $self->{value} &&
380                         $current_function->{abi} eq "svr4") {
381                 $func .= "\n";
382                 $func .= "      movq    %rdi,8(%rsp)\n";
383                 $func .= "      movq    %rsi,16(%rsp)\n";
384                 $func .= "      movq    %rsp,%rax\n";
385                 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
386                 my $narg = $current_function->{narg};
387                 $narg=6 if (!defined($narg));
388                 $func .= "      movq    %rcx,%rdi\n" if ($narg>0);
389                 $func .= "      movq    %rdx,%rsi\n" if ($narg>1);
390                 $func .= "      movq    %r8,%rdx\n"  if ($narg>2);
391                 $func .= "      movq    %r9,%rcx\n"  if ($narg>3);
392                 $func .= "      movq    40(%rsp),%r8\n" if ($narg>4);
393                 $func .= "      movq    48(%rsp),%r9\n" if ($narg>5);
394             }
395             $func;
396         } elsif ($self->{value} ne "$current_function->{name}") {
397             # Make all labels in masm global.
398             $self->{value} .= ":" if ($masm);
399             $self->{value} . ":";
400         } elsif ($win64 && $current_function->{abi} eq "svr4") {
401             my $func =  "$current_function->{name}" .
402                         ($nasm ? ":" : "\tPROC $current_function->{scope}") .
403                         "\n";
404             $func .= "  mov     QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
405             $func .= "  mov     QWORD$PTR\[16+rsp\],rsi\n";
406             $func .= "  mov     rax,rsp\n";
407             $func .= "${decor}SEH_begin_$current_function->{name}:";
408             $func .= ":" if ($masm);
409             $func .= "\n";
410             my $narg = $current_function->{narg};
411             $narg=6 if (!defined($narg));
412             $func .= "  mov     rdi,rcx\n" if ($narg>0);
413             $func .= "  mov     rsi,rdx\n" if ($narg>1);
414             $func .= "  mov     rdx,r8\n"  if ($narg>2);
415             $func .= "  mov     rcx,r9\n"  if ($narg>3);
416             $func .= "  mov     r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
417             $func .= "  mov     r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
418             $func .= "\n";
419         } else {
420            "$current_function->{name}".
421                         ($nasm ? ":" : "\tPROC $current_function->{scope}");
422         }
423     }
424 }
425 { package expr;         # pick up expressioins
426     sub re {
427         my      ($class, $line, $opcode) = @_;
428         my      $self = {};
429         my      $ret;
430
431         if ($$line =~ /(^[^,]+)/) {
432             bless $self,$class;
433             $self->{value} = $1;
434             $ret = $self;
435             $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
436
437             $self->{value} =~ s/\@PLT// if (!$elf);
438             $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
439             $self->{value} =~ s/\.L/$decor/g;
440             $self->{opcode} = $opcode;
441         }
442         $ret;
443     }
444     sub out {
445         my $self = shift;
446         if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
447             "NEAR ".$self->{value};
448         } else {
449             $self->{value};
450         }
451     }
452 }
453 { package directive;    # pick up directives, which start with .
454     sub re {
455         my      ($class, $line) = @_;
456         my      $self = {};
457         my      $ret;
458         my      $dir;
459         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
460                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
461                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
462                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
463                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
464                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
465                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
466                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
467                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
468
469         if ($$line =~ /^\s*(\.\w+)/) {
470             bless $self,$class;
471             $dir = $1;
472             $ret = $self;
473             undef $self->{value};
474             $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
475
476             SWITCH: for ($dir) {
477                 /\.picmeup/ && do { if ($$line =~ /(%r[\w]+)/i) {
478                                         $dir="\t.long";
479                                         $$line=sprintf "0x%x,0x90000000",$opcode{$1};
480                                     }
481                                     last;
482                                   };
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 sub rex {
688  my $opcode=shift;
689  my ($dst,$src,$rex)=@_;
690
691    $rex|=0x04 if($dst>=8);
692    $rex|=0x01 if($src>=8);
693    push @$opcode,($rex|0x40) if ($rex);
694 }
695
696 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
697 # yet. In order not to be bothered by tracing exact assembler versions,
698 # but at the same time to provide a bare security minimum of AES-NI, we
699 # hard-code some instructions. Extensions past AES-NI on the other hand
700 # are traced by examining assembler version in individual perlasm
701 # modules...
702
703 my %regrm = (   "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
704                 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7      );
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 sub rxb {
830  my $opcode=shift;
831  my ($dst,$src1,$src2,$rxb)=@_;
832
833    $rxb|=0x7<<5;
834    $rxb&=~(0x04<<5) if($dst>=8);
835    $rxb&=~(0x01<<5) if($src1>=8);
836    $rxb&=~(0x02<<5) if($src2>=8);
837    push @$opcode,$rxb;
838 }
839
840 my $vprotd = sub {
841     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
842       my @opcode=(0x8f);
843         rxb(\@opcode,$3,$2,-1,0x08);
844         push @opcode,0x78,0xc2;
845         push @opcode,0xc0|($2&7)|(($3&7)<<3);           # ModR/M
846         my $c=$1;
847         push @opcode,$c=~/^0/?oct($c):$c;
848         @opcode;
849     } else {
850         ();
851     }
852 };
853
854 my $vprotq = sub {
855     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
856       my @opcode=(0x8f);
857         rxb(\@opcode,$3,$2,-1,0x08);
858         push @opcode,0x78,0xc3;
859         push @opcode,0xc0|($2&7)|(($3&7)<<3);           # ModR/M
860         my $c=$1;
861         push @opcode,$c=~/^0/?oct($c):$c;
862         @opcode;
863     } else {
864         ();
865     }
866 };
867
868 my $endbranch = sub {
869     (0xf3,0x0f,0x1e,0xfa);
870 };
871
872 if ($nasm) {
873     print <<___;
874 default rel
875 %define XMMWORD
876 %define YMMWORD
877 %define ZMMWORD
878 ___
879 } elsif ($masm) {
880     print <<___;
881 OPTION  DOTNAME
882 ___
883 }
884 while(defined(my $line=<>)) {
885
886     $line =~ s|\R$||;           # Better chomp
887
888     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
889     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
890     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
891     $line =~ s|\s+$||;          # ... and at the end
892
893     if (my $label=label->re(\$line))    { print $label->out(); }
894
895     if (my $directive=directive->re(\$line)) {
896         printf "%s",$directive->out();
897     } elsif (my $opcode=opcode->re(\$line)) {
898         my $asm = eval("\$".$opcode->mnemonic());
899         
900         if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
901             print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
902             next;
903         }
904
905         my @args;
906         ARGUMENT: while (1) {
907             my $arg;
908
909             ($arg=register->re(\$line, $opcode))||
910             ($arg=const->re(\$line))            ||
911             ($arg=ea->re(\$line, $opcode))      ||
912             ($arg=expr->re(\$line, $opcode))    ||
913             last ARGUMENT;
914
915             push @args,$arg;
916
917             last ARGUMENT if ($line !~ /^,/);
918
919             $line =~ s/^,\s*//;
920         } # ARGUMENT:
921
922         if ($#args>=0) {
923             my $insn;
924             my $sz=$opcode->size();
925
926             if ($gas) {
927                 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
928                 @args = map($_->out($sz),@args);
929                 printf "\t%s\t%s",$insn,join(",",@args);
930             } else {
931                 $insn = $opcode->out();
932                 foreach (@args) {
933                     my $arg = $_->out();
934                     # $insn.=$sz compensates for movq, pinsrw, ...
935                     if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
936                     if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
937                     if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
938                     if ($arg =~ /^mm[0-9]+$/)  { $insn.=$sz; $sz="q" if(!$sz); last; }
939                 }
940                 @args = reverse(@args);
941                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
942                 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
943             }
944         } else {
945             printf "\t%s",$opcode->out();
946         }
947     }
948
949     print $line,"\n";
950 }
951
952 print "\n$current_segment\tENDS\n"      if ($current_segment && $masm);
953 print "END\n"                           if ($masm);
954
955 close STDOUT;
956
957 \f#################################################
958 # Cross-reference x86_64 ABI "card"
959 #
960 #               Unix            Win64
961 # %rax          *               *
962 # %rbx          -               -
963 # %rcx          #4              #1
964 # %rdx          #3              #2
965 # %rsi          #2              -
966 # %rdi          #1              -
967 # %rbp          -               -
968 # %rsp          -               -
969 # %r8           #5              #3
970 # %r9           #6              #4
971 # %r10          *               *
972 # %r11          *               *
973 # %r12          -               -
974 # %r13          -               -
975 # %r14          -               -
976 # %r15          -               -
977
978 # (*)   volatile register
979 # (-)   preserved by callee
980 # (#)   Nth argument, volatile
981 #
982 # In Unix terms top of stack is argument transfer area for arguments
983 # which could not be accommodated in registers. Or in other words 7th
984 # [integer] argument resides at 8(%rsp) upon function entry point.
985 # 128 bytes above %rsp constitute a "red zone" which is not touched
986 # by signal handlers and can be used as temporal storage without
987 # allocating a frame.
988 #
989 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
990 # which belongs to/can be overwritten by callee. N is the number of
991 # arguments passed to callee, *but* not less than 4! This means that
992 # upon function entry point 5th argument resides at 40(%rsp), as well
993 # as that 32 bytes from 8(%rsp) can always be used as temporal
994 # storage [without allocating a frame]. One can actually argue that
995 # one can assume a "red zone" above stack pointer under Win64 as well.
996 # Point is that at apparently no occasion Windows kernel would alter
997 # the area above user stack pointer in true asynchronous manner...
998 #
999 # All the above means that if assembler programmer adheres to Unix
1000 # register and stack layout, but disregards the "red zone" existense,
1001 # it's possible to use following prologue and epilogue to "gear" from
1002 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1003 #
1004 # omnipotent_function:
1005 # ifdef WIN64
1006 #       movq    %rdi,8(%rsp)
1007 #       movq    %rsi,16(%rsp)
1008 #       movq    %rcx,%rdi       ; if 1st argument is actually present
1009 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
1010 #       movq    %r8,%rdx        ; if 3rd argument is ...
1011 #       movq    %r9,%rcx        ; if 4th argument ...
1012 #       movq    40(%rsp),%r8    ; if 5th ...
1013 #       movq    48(%rsp),%r9    ; if 6th ...
1014 # endif
1015 #       ...
1016 # ifdef WIN64
1017 #       movq    8(%rsp),%rdi
1018 #       movq    16(%rsp),%rsi
1019 # endif
1020 #       ret
1021 #
1022 \f#################################################
1023 # Win64 SEH, Structured Exception Handling.
1024 #
1025 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1026 # has undesired side-effect at run-time: if an exception is raised in
1027 # assembler subroutine such as those in question (basically we're
1028 # referring to segmentation violations caused by malformed input
1029 # parameters), the application is briskly terminated without invoking
1030 # any exception handlers, most notably without generating memory dump
1031 # or any user notification whatsoever. This poses a problem. It's
1032 # possible to address it by registering custom language-specific
1033 # handler that would restore processor context to the state at
1034 # subroutine entry point and return "exception is not handled, keep
1035 # unwinding" code. Writing such handler can be a challenge... But it's
1036 # doable, though requires certain coding convention. Consider following
1037 # snippet:
1038 #
1039 # .type function,@function
1040 # function:
1041 #       movq    %rsp,%rax       # copy rsp to volatile register
1042 #       pushq   %r15            # save non-volatile registers
1043 #       pushq   %rbx
1044 #       pushq   %rbp
1045 #       movq    %rsp,%r11
1046 #       subq    %rdi,%r11       # prepare [variable] stack frame
1047 #       andq    $-64,%r11
1048 #       movq    %rax,0(%r11)    # check for exceptions
1049 #       movq    %r11,%rsp       # allocate [variable] stack frame
1050 #       movq    %rax,0(%rsp)    # save original rsp value
1051 # magic_point:
1052 #       ...
1053 #       movq    0(%rsp),%rcx    # pull original rsp value
1054 #       movq    -24(%rcx),%rbp  # restore non-volatile registers
1055 #       movq    -16(%rcx),%rbx
1056 #       movq    -8(%rcx),%r15
1057 #       movq    %rcx,%rsp       # restore original rsp
1058 #       ret
1059 # .size function,.-function
1060 #
1061 # The key is that up to magic_point copy of original rsp value remains
1062 # in chosen volatile register and no non-volatile register, except for
1063 # rsp, is modified. While past magic_point rsp remains constant till
1064 # the very end of the function. In this case custom language-specific
1065 # exception handler would look like this:
1066 #
1067 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1068 #               CONTEXT *context,DISPATCHER_CONTEXT *disp)
1069 # {     ULONG64 *rsp = (ULONG64 *)context->Rax;
1070 #       if (context->Rip >= magic_point)
1071 #       {   rsp = ((ULONG64 **)context->Rsp)[0];
1072 #           context->Rbp = rsp[-3];
1073 #           context->Rbx = rsp[-2];
1074 #           context->R15 = rsp[-1];
1075 #       }
1076 #       context->Rsp = (ULONG64)rsp;
1077 #       context->Rdi = rsp[1];
1078 #       context->Rsi = rsp[2];
1079 #
1080 #       memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1081 #       RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1082 #               dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1083 #               &disp->HandlerData,&disp->EstablisherFrame,NULL);
1084 #       return ExceptionContinueSearch;
1085 # }
1086 #
1087 # It's appropriate to implement this handler in assembler, directly in
1088 # function's module. In order to do that one has to know members'
1089 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1090 # values. Here they are:
1091 #
1092 #       CONTEXT.Rax                             120
1093 #       CONTEXT.Rcx                             128
1094 #       CONTEXT.Rdx                             136
1095 #       CONTEXT.Rbx                             144
1096 #       CONTEXT.Rsp                             152
1097 #       CONTEXT.Rbp                             160
1098 #       CONTEXT.Rsi                             168
1099 #       CONTEXT.Rdi                             176
1100 #       CONTEXT.R8                              184
1101 #       CONTEXT.R9                              192
1102 #       CONTEXT.R10                             200
1103 #       CONTEXT.R11                             208
1104 #       CONTEXT.R12                             216
1105 #       CONTEXT.R13                             224
1106 #       CONTEXT.R14                             232
1107 #       CONTEXT.R15                             240
1108 #       CONTEXT.Rip                             248
1109 #       CONTEXT.Xmm6                            512
1110 #       sizeof(CONTEXT)                         1232
1111 #       DISPATCHER_CONTEXT.ControlPc            0
1112 #       DISPATCHER_CONTEXT.ImageBase            8
1113 #       DISPATCHER_CONTEXT.FunctionEntry        16
1114 #       DISPATCHER_CONTEXT.EstablisherFrame     24
1115 #       DISPATCHER_CONTEXT.TargetIp             32
1116 #       DISPATCHER_CONTEXT.ContextRecord        40
1117 #       DISPATCHER_CONTEXT.LanguageHandler      48
1118 #       DISPATCHER_CONTEXT.HandlerData          56
1119 #       UNW_FLAG_NHANDLER                       0
1120 #       ExceptionContinueSearch                 1
1121 #
1122 # In order to tie the handler to the function one has to compose
1123 # couple of structures: one for .xdata segment and one for .pdata.
1124 #
1125 # UNWIND_INFO structure for .xdata segment would be
1126 #
1127 # function_unwind_info:
1128 #       .byte   9,0,0,0
1129 #       .rva    handler
1130 #
1131 # This structure designates exception handler for a function with
1132 # zero-length prologue, no stack frame or frame register.
1133 #
1134 # To facilitate composing of .pdata structures, auto-generated "gear"
1135 # prologue copies rsp value to rax and denotes next instruction with
1136 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1137 # styling rule mentioned in the beginning. Position of this label is
1138 # chosen in such manner that possible exceptions raised in the "gear"
1139 # prologue would be accounted to caller and unwound from latter's frame.
1140 # End of function is marked with respective .LSEH_end_{function_name}
1141 # label. To summarize, .pdata segment would contain
1142 #
1143 #       .rva    .LSEH_begin_function
1144 #       .rva    .LSEH_end_function
1145 #       .rva    function_unwind_info
1146 #
1147 # Reference to function_unwind_info from .xdata segment is the anchor.
1148 # In case you wonder why references are 32-bit .rvas and not 64-bit
1149 # .quads. References put into these two segments are required to be
1150 # *relative* to the base address of the current binary module, a.k.a.
1151 # image base. No Win64 module, be it .exe or .dll, can be larger than
1152 # 2GB and thus such relative references can be and are accommodated in
1153 # 32 bits.
1154 #
1155 # Having reviewed the example function code, one can argue that "movq
1156 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1157 # rax would contain an undefined value. If this "offends" you, use
1158 # another register and refrain from modifying rax till magic_point is
1159 # reached, i.e. as if it was a non-volatile register. If more registers
1160 # are required prior [variable] frame setup is completed, note that
1161 # nobody says that you can have only one "magic point." You can
1162 # "liberate" non-volatile registers by denoting last stack off-load
1163 # instruction and reflecting it in finer grade unwind logic in handler.
1164 # After all, isn't it why it's called *language-specific* handler...
1165 #
1166 # Attentive reader can notice that exceptions would be mishandled in
1167 # auto-generated "gear" epilogue. Well, exception effectively can't
1168 # occur there, because if memory area used by it was subject to
1169 # segmentation violation, then it would be raised upon call to the
1170 # function (and as already mentioned be accounted to caller, which is
1171 # not a problem). If you're still not comfortable, then define tail
1172 # "magic point" just prior ret instruction and have handler treat it...
1173 #
1174 # (*)   Note that we're talking about run-time, not debug-time. Lack of
1175 #       unwind information makes debugging hard on both Windows and
1176 #       Unix. "Unlike" referes to the fact that on Unix signal handler
1177 #       will always be invoked, core dumped and appropriate exit code
1178 #       returned to parent (for user notification).