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