Policy validation fixes.
[openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM assembler translator by <appro>.
4 #
5 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6 # format is way easier to parse. Because it's simpler to "gear" from
7 # Unix ABI to Windows one [see cross-reference "card" at the end of
8 # file]. Because Linux targets were available first...
9 #
10 # In addition the script also "distills" code suitable for GNU
11 # assembler, so that it can be compiled with more rigid assemblers,
12 # such as Solaris /usr/ccs/bin/as.
13 #
14 # This translator is not designed to convert *arbitrary* assembler
15 # code from AT&T format to MASM one. It's designed to convert just
16 # enough to provide for dual-ABI OpenSSL modules development...
17 # There *are* limitations and you might have to modify your assembler
18 # code or this script to achieve the desired result...
19 #
20 # Currently recognized limitations:
21 #
22 # - can't use multiple ops per line;
23 #
24 # Dual-ABI styling rules.
25 #
26 # 1. Adhere to Unix register and stack layout [see the end for
27 #    explanation].
28 # 2. Forget about "red zone," stick to more traditional blended
29 #    stack frame allocation. If volatile storage is actually required
30 #    that is. If not, just leave the stack as is.
31 # 3. Functions tagged with ".type name,@function" get crafted with
32 #    unified Win64 prologue and epilogue automatically. If you want
33 #    to take care of ABI differences yourself, tag functions as
34 #    ".type name,@abi-omnipotent" instead.
35 # 4. To optimize the Win64 prologue you can specify number of input
36 #    arguments as ".type name,@function,N." Keep in mind that if N is
37 #    larger than 6, then you *have to* write "abi-omnipotent" code,
38 #    because >6 cases can't be addressed with unified prologue.
39 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
40 #    (sorry about latter).
41 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
42 #    required to identify the spots, where to inject Win64 epilogue!
43 #    But on the pros, it's then prefixed with rep automatically:-)
44 # 7. Due to MASM limitations [and certain general counter-intuitivity
45 #    of ip-relative addressing] generation of position-independent
46 #    code is assisted by synthetic directive, .picmeup, which puts
47 #    address of the *next* instruction into target register.
48 #
49 #    Example 1:
50 #               .picmeup        %rax
51 #               lea             .Label-.(%rax),%rax
52 #    Example 2:
53 #               .picmeup        %rcx
54 #       .Lpic_point:
55 #               ...
56 #               lea             .Label-.Lpic_point(%rcx),%rbp
57
58 my $output = shift;
59
60 { my ($stddev,$stdino,@junk)=stat(STDOUT);
61   my ($outdev,$outino,@junk)=stat($output);
62
63     open STDOUT,">$output" || die "can't open $output: $!"
64         if ($stddev!=$outdev || $stdino!=$outino);
65 }
66
67 my $win64=1 if ($output =~ /\.asm/);
68
69 my $masmref=8 + 50727*2**-32;   # 8.00.50727 shipped with VS2005
70 my $masm=0;
71 my $PTR=" PTR";
72
73 my $nasmref=2.03;
74 my $nasm=0;
75
76 if ($win64)
77 {   if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
78     {   $nasm = $1 + $2*0.01; $PTR="";  }
79     elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
80     {   $masm = $1 + $2*2**-16 + $4*2**-32;   }
81     die "no assembler found on %PATH" if (!($nasm || $masm));
82 }
83
84 my $current_segment;
85 my $current_function;
86 my %globals;
87
88 { package opcode;       # pick up opcodes
89     sub re {
90         my      $self = shift;  # single instance in enough...
91         local   *line = shift;
92         undef   $ret;
93
94         if ($line =~ /^([a-z][a-z0-9]*)/i) {
95             $self->{op} = $1;
96             $ret = $self;
97             $line = substr($line,@+[0]); $line =~ s/^\s+//;
98
99             undef $self->{sz};
100             if ($self->{op} =~ /^(movz)b.*/) {  # movz is pain...
101                 $self->{op} = $1;
102                 $self->{sz} = "b";
103             } elsif ($self->{op} =~ /call|jmp/) {
104                 $self->{sz} = ""
105             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
106                 $self->{op} = $1;
107                 $self->{sz} = $2;
108             }
109         }
110         $ret;
111     }
112     sub size {
113         my $self = shift;
114         my $sz   = shift;
115         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
116         $self->{sz};
117     }
118     sub out {
119         my $self = shift;
120         if (!$win64) {
121             if ($self->{op} eq "movz") {        # movz is pain...
122                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
123             } elsif ($self->{op} =~ /^set/) { 
124                 "$self->{op}";
125             } elsif ($self->{op} eq "ret") {
126                 ".byte  0xf3,0xc3";
127             } else {
128                 "$self->{op}$self->{sz}";
129             }
130         } else {
131             $self->{op} =~ s/^movz/movzx/;
132             if ($self->{op} eq "ret") {
133                 $self->{op} = "";
134                 if ($current_function->{abi} eq "svr4") {
135                     $self->{op} = "mov  rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
136                                   "mov  rsi,QWORD${PTR}[16+rsp]\n\t";
137                 }
138                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
139             }
140             $self->{op};
141         }
142     }
143     sub mnemonic { shift->{op}; }
144 }
145 { package const;        # pick up constants, which start with $
146     sub re {
147         my      $self = shift;  # single instance in enough...
148         local   *line = shift;
149         undef   $ret;
150
151         if ($line =~ /^\$([^,]+)/) {
152             $self->{value} = $1;
153             $ret = $self;
154             $line = substr($line,@+[0]); $line =~ s/^\s+//;
155         }
156         $ret;
157     }
158     sub out {
159         my $self = shift;
160
161         if (!$win64) {
162             # Solaris /usr/ccs/bin/as can't handle multiplications
163             # in $self->{value}
164             $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
165             $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
166             sprintf "\$%s",$self->{value};
167         } else {
168             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
169             sprintf "%s",$self->{value};
170         }
171     }
172 }
173 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
174     sub re {
175         my      $self = shift;  # single instance in enough...
176         local   *line = shift;
177         undef   $ret;
178
179         # optional * ---vvv--- appears in indirect jmp/call
180         if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
181             $self->{asterisk} = $1;
182             $self->{label} = $2;
183             ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
184             $self->{scale} = 1 if (!defined($self->{scale}));
185             $ret = $self;
186             $line = substr($line,@+[0]); $line =~ s/^\s+//;
187
188             $self->{base}  =~ s/^%//;
189             $self->{index} =~ s/^%// if (defined($self->{index}));
190         }
191         $ret;
192     }
193     sub size {}
194     sub out {
195         my $self = shift;
196         my $sz = shift;
197
198         # Silently convert all EAs to 64-bit. This is required for
199         # elder GNU assembler and results in more compact code,
200         # *but* most importantly AES module depends on this feature!
201         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
202         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
203
204         if (!$win64) {
205             # Solaris /usr/ccs/bin/as can't handle multiplications
206             # in $self->{label}
207             $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
208             $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
209
210             if (defined($self->{index})) {
211                 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk},
212                                         $self->{label},$self->{base},
213                                         $self->{index},$self->{scale};
214             } else {
215                 sprintf "%s%s(%%%s)",   $self->{asterisk},$self->{label},$self->{base};
216             }
217         } else {
218             %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
219
220             $self->{label} =~ s/\./\$/g;
221             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
222             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
223             $sz="q" if ($self->{asterisk});
224
225             if (defined($self->{index})) {
226                 sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
227                                         $self->{label}?"$self->{label}+":"",
228                                         $self->{index},$self->{scale},
229                                         $self->{base};
230             } elsif ($self->{base} eq "rip") {
231                 sprintf "%s[%s]",$szmap{$sz},$self->{label};
232             } else {
233                 sprintf "%s[%s%s]",$szmap{$sz},
234                                         $self->{label}?"$self->{label}+":"",
235                                         $self->{base};
236             }
237         }
238     }
239 }
240 { package register;     # pick up registers, which start with %.
241     sub re {
242         my      $class = shift; # muliple instances...
243         my      $self = {};
244         local   *line = shift;
245         undef   $ret;
246
247         # optional * ---vvv--- appears in indirect jmp/call
248         if ($line =~ /^(\*?)%(\w+)/) {
249             bless $self,$class;
250             $self->{asterisk} = $1;
251             $self->{value} = $2;
252             $ret = $self;
253             $line = substr($line,@+[0]); $line =~ s/^\s+//;
254         }
255         $ret;
256     }
257     sub size {
258         my      $self = shift;
259         undef   $ret;
260
261         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
262         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
263         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
264         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
265         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
266         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
267         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
268         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
269
270         $ret;
271     }
272     sub out {
273         my $self = shift;
274         if (!$win64)    { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
275         else            { $self->{value}; }
276     }
277 }
278 { package label;        # pick up labels, which end with :
279     sub re {
280         my      $self = shift;  # single instance is enough...
281         local   *line = shift;
282         undef   $ret;
283
284         if ($line =~ /(^[\.\w]+\:)/) {
285             $self->{value} = $1;
286             $ret = $self;
287             $line = substr($line,@+[0]); $line =~ s/^\s+//;
288
289             $self->{value} =~ s/\.L/\$L/ if ($win64);
290         }
291         $ret;
292     }
293     sub out {
294         my $self = shift;
295
296         if (!$win64) {
297             $self->{value};
298         } elsif ($self->{value} ne "$current_function->{name}:") {
299             $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
300             $self->{value};
301         } elsif ($current_function->{abi} eq "svr4") {
302             my $func =  "$current_function->{name}" .
303                         ($nasm ? ":" : "\tPROC $current_function->{scope}") .
304                         "\n";
305             $func .= "  mov     QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
306             $func .= "  mov     QWORD${PTR}[16+rsp],rsi\n";
307             my $narg = $current_function->{narg};
308             $narg=6 if (!defined($narg));
309             $func .= "  mov     rdi,rcx\n" if ($narg>0);
310             $func .= "  mov     rsi,rdx\n" if ($narg>1);
311             $func .= "  mov     rdx,r8\n"  if ($narg>2);
312             $func .= "  mov     rcx,r9\n"  if ($narg>3);
313             $func .= "  mov     r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
314             $func .= "  mov     r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
315             $func .= "\n";
316         } else {
317            "$current_function->{name}".
318                         ($nasm ? ":" : "\tPROC $current_function->{scope}");
319         }
320     }
321 }
322 { package expr;         # pick up expressioins
323     sub re {
324         my      $self = shift;  # single instance is enough...
325         local   *line = shift;
326         undef   $ret;
327
328         if ($line =~ /(^[^,]+)/) {
329             $self->{value} = $1;
330             $ret = $self;
331             $line = substr($line,@+[0]); $line =~ s/^\s+//;
332
333             $self->{value} =~ s/\.L/\$L/g if ($win64);
334         }
335         $ret;
336     }
337     sub out {
338         my $self = shift;
339         if ($nasm && opcode->mnemonic()=~m/^j/) {
340             "NEAR ".$self->{value};
341         } else {
342             $self->{value};
343         }
344     }
345 }
346 { package directive;    # pick up directives, which start with .
347     sub re {
348         my      $self = shift;  # single instance is enough...
349         local   *line = shift;
350         undef   $ret;
351         my      $dir;
352         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
353                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
354                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
355                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
356                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
357                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
358                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
359                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
360                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
361
362         if ($line =~ /^\s*(\.\w+)/) {
363             if (!$win64) {
364                 $self->{value} = $1;
365                 $line =~ s/\@abi\-omnipotent/\@function/;
366                 $line =~ s/\@function.*/\@function/;
367                 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
368                     $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
369                 } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
370                     $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
371                 } elsif ($line =~ /\.extern/) {
372                     $self->{value} = ""; # swallow extern
373                 } else {
374                     $self->{value} = $line;
375                 }
376                 $line = "";
377                 return $self;
378             }
379
380             $dir = $1;
381             $ret = $self;
382             undef $self->{value};
383             $line = substr($line,@+[0]); $line =~ s/^\s+//;
384             SWITCH: for ($dir) {
385                 /\.text/    && do { my $v=undef;
386                                     if ($nasm) {
387                                         $v="section     .text code align=64\n";
388                                     } else {
389                                         $v="$current_segment\tENDS\n" if ($current_segment);
390                                         $current_segment = ".text\$";
391                                         $v.="$current_segment\tSEGMENT ";
392                                         $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
393                                         $v.=" 'CODE'";
394                                     }
395                                     $self->{value} = $v;
396                                     last;
397                                   };
398                 /\.data/    && do { my $v=undef;
399                                     if ($nasm) {
400                                         $v="section     .data data align=8\n";
401                                     } else {
402                                         $v="$current_segment\tENDS\n" if ($current_segment);
403                                         $current_segment = "_DATA";
404                                         $v.="$current_segment\tSEGMENT";
405                                     }
406                                     $self->{value} = $v;
407                                     last;
408                                   };
409                 /\.section/ && do { my $v=undef;
410                                     if ($nasm) {
411                                         $v="section     $line";
412                                         if ($line=~/\.([px])data/) {
413                                             $v.=" rdata align=";
414                                             $v.=$1 eq "p"? 4 : 8;
415                                         }
416                                     } else {
417                                         $v="$current_segment\tENDS\n" if ($current_segment);
418                                         $v.="$line\tSEGMENT";
419                                         if ($line=~/\.([px])data/) {
420                                             $v.=" READONLY";
421                                             $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
422                                         }
423                                     }
424                                     $current_segment = $line;
425                                     $self->{value} = $v;
426                                     last;
427                                   };
428                 /\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
429                                     $self->{value} .= ":NEAR" if ($masm);
430                                     last;
431                                   };
432                 /\.globl/   && do { $self->{value} = "PUBLIC\t".$line;
433                                     $globals{$line} = $line;
434                                     last;
435                                   };
436                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
437                                     if ($type eq "\@function") {
438                                         undef $current_function;
439                                         $current_function->{name} = $sym;
440                                         $current_function->{abi}  = "svr4";
441                                         $current_function->{narg} = $narg;
442                                         $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
443                                     } elsif ($type eq "\@abi-omnipotent") {
444                                         undef $current_function;
445                                         $current_function->{name} = $sym;
446                                         $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
447                                     }
448                                     last;
449                                   };
450                 /\.size/    && do { if (defined($current_function)) {
451                                         $self->{value}="$current_function->{name}\tENDP" if(!$nasm);
452                                         undef $current_function;
453                                     }
454                                     last;
455                                   };
456                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
457                 /\.(byte|value|long|quad)/
458                             && do { my @arr = split(',',$line);
459                                     my $sz  = substr($1,0,1);
460                                     my $last = pop(@arr);
461                                     my $conv = sub  {   my $var=shift;
462                                                         $var=~s/0x([0-9a-f]+)/0$1h/ig;
463                                                         if ($current_segment=~/.[px]data/)
464                                                         { $var=~s/\b([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
465                                                         $var;
466                                                     };  
467
468                                     $sz =~ tr/bvlq/BWDQ/;
469                                     $self->{value} = "\tD$sz\t";
470                                     for (@arr) { $self->{value} .= &$conv($_).","; }
471                                     $self->{value} .= &$conv($last);
472                                     last;
473                                   };
474                 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t0%Xh,090000000h",$opcode{$line};
475                                     last;
476                                   };
477                 /\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
478                                         my @str=unpack("C*",$1);
479                                         push @str,0;
480                                         while ($#str>15) {
481                                             $self->{value}.="DB\t"
482                                                 .join(",",@str[0..15])."\n";
483                                             foreach (0..15) { shift @str; }
484                                         }
485                                         $self->{value}.="DB\t"
486                                                 .join(",",@str) if (@str);
487                                     }
488                                     last;
489                                   };
490             }
491             $line = "";
492         }
493
494         $ret;
495     }
496     sub out {
497         my $self = shift;
498         $self->{value};
499     }
500 }
501
502 if ($nasm) {
503     print <<___;
504 default rel
505 %define PUBLIC global
506 ___
507 } elsif ($masm) {
508     print <<___;
509 OPTION  DOTNAME
510 ___
511 }
512 while($line=<>) {
513
514     chomp($line);
515
516     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
517     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
518     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
519
520     undef $label;
521     undef $opcode;
522     undef $dst;
523     undef $src;
524     undef $sz;
525
526     if ($label=label->re(\$line))       { print $label->out(); }
527
528     if (directive->re(\$line)) {
529         printf "%s",directive->out();
530     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
531
532         if ($src=register->re(\$line))  { opcode->size($src->size()); }
533         elsif ($src=const->re(\$line))  { }
534         elsif ($src=ea->re(\$line))     { }
535         elsif ($src=expr->re(\$line))   { }
536
537         last ARGUMENT if ($line !~ /^,/);
538
539         $line = substr($line,1); $line =~ s/^\s+//;
540
541         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
542         elsif ($dst=const->re(\$line))  { }
543         elsif ($dst=ea->re(\$line))     { }
544
545         } # ARGUMENT:
546
547         $sz=opcode->size();
548
549         if (defined($dst)) {
550             if (!$win64) {
551                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
552                                         $src->out($sz),$dst->out($sz);
553             } else {
554                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
555                 printf "\t%s\t%s,%s",   $opcode->out(),
556                                         $dst->out($sz),$src->out($sz);
557             }
558         } elsif (defined($src)) {
559             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
560         } else {
561             printf "\t%s",$opcode->out();
562         }
563     }
564
565     print $line,"\n";
566 }
567
568 print "\n$current_segment\tENDS\nEND\n" if ($current_segment && $masm);
569
570 close STDOUT;
571
572 #################################################
573 # Cross-reference x86_64 ABI "card"
574 #
575 #               Unix            Win64
576 # %rax          *               *
577 # %rbx          -               -
578 # %rcx          #4              #1
579 # %rdx          #3              #2
580 # %rsi          #2              -
581 # %rdi          #1              -
582 # %rbp          -               -
583 # %rsp          -               -
584 # %r8           #5              #3
585 # %r9           #6              #4
586 # %r10          *               *
587 # %r11          *               *
588 # %r12          -               -
589 # %r13          -               -
590 # %r14          -               -
591 # %r15          -               -
592
593 # (*)   volatile register
594 # (-)   preserved by callee
595 # (#)   Nth argument, volatile
596 #
597 # In Unix terms top of stack is argument transfer area for arguments
598 # which could not be accomodated in registers. Or in other words 7th
599 # [integer] argument resides at 8(%rsp) upon function entry point.
600 # 128 bytes above %rsp constitute a "red zone" which is not touched
601 # by signal handlers and can be used as temporal storage without
602 # allocating a frame.
603 #
604 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
605 # which belongs to/can be overwritten by callee. N is the number of
606 # arguments passed to callee, *but* not less than 4! This means that
607 # upon function entry point 5th argument resides at 40(%rsp), as well
608 # as that 32 bytes from 8(%rsp) can always be used as temporal
609 # storage [without allocating a frame]. One can actually argue that
610 # one can assume a "red zone" above stack pointer under Win64 as well.
611 # Point is that at apparently no occasion Windows kernel would alter
612 # the area above user stack pointer in true asynchronous manner...
613 #
614 # All the above means that if assembler programmer adheres to Unix
615 # register and stack layout, but disregards the "red zone" existense,
616 # it's possible to use following prologue and epilogue to "gear" from
617 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
618 #
619 # omnipotent_function:
620 # ifdef WIN64
621 #       movq    %rdi,8(%rsp)
622 #       movq    %rsi,16(%rsp)
623 #       movq    %rcx,%rdi       ; if 1st argument is actually present
624 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
625 #       movq    %r8,%rdx        ; if 3rd argument is ...
626 #       movq    %r9,%rcx        ; if 4th argument ...
627 #       movq    40(%rsp),%r8    ; if 5th ...
628 #       movq    48(%rsp),%r9    ; if 6th ...
629 # endif
630 #       ...
631 # ifdef WIN64
632 #       movq    8(%rsp),%rdi
633 #       movq    16(%rsp),%rsi
634 # endif
635 #       ret
636 #
637 #################################################
638 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
639 # has undesired side-effect at run-time: if an exception is raised in
640 # assembler subroutine such as those in question (basically we're
641 # referring to segmentation violations caused by malformed input
642 # parameters), the application is briskly terminated without invoking
643 # any exception handlers, most notably without generating memory dump
644 # or any user notification whatsoever. This poses a problem. It's
645 # possible to address it by registering custom language-specific
646 # handler that would restore processor context to the state at
647 # subroutine entry point and return "exception is not handled, keep
648 # unwinding" code. Writing such handler can be a challenge... But it's
649 # doable, though requires certain coding convention. Consider following
650 # snippet:
651 #
652 # function:
653 #       movq    %rsp,%rax       # copy rsp to volatile register
654 #       pushq   %r15            # save non-volatile registers
655 #       pushq   %rbx
656 #       pushq   %rbp
657 #       movq    %rsp,%r11
658 #       subq    %rdi,%r11       # prepare [variable] stack frame
659 #       andq    $-64,%r11
660 #       movq    %rax,0(%r11)    # check for exceptions
661 #       movq    %r11,%rsp       # allocate [variable] stack frame
662 #       movq    %rax,0(%rsp)    # save original rsp value
663 # magic_point:
664 #       ...
665 #       movq    0(%rsp),%rcx    # pull original rsp value
666 #       movq    -24(%rcx),%rbp  # restore non-volatile registers
667 #       movq    -16(%rcx),%rbx
668 #       movq    -8(%rcx),%r15
669 #       movq    %rcx,%rsp       # restore original rsp
670 #       ret
671 #
672 # The key is that up to magic_point copy of original rsp value remains
673 # in chosen volatile register and no non-volatile register, except for
674 # rsp, is modified. While past magic_point rsp remains constant till
675 # the very end of the function. In this case custom language-specific
676 # exception handler would look like this:
677 #
678 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
679 #               CONTEXT *context,DISPATCHER_CONTEXT *disp)
680 # {     ULONG64 *rsp;
681 #       if (context->Rip<magic_point)
682 #           rsp = (ULONG64 *)context->Rax;
683 #       else
684 #       {   rsp = ((ULONG64 **)context->Rsp)[0];
685 #           context->Rbp = rsp[-3];
686 #           context->Rbx = rsp[-2];
687 #           context->R15 = rsp[-1];
688 #       }
689 #       context->Rsp = (ULONG64)rsp;
690 #       context->Rdi = rsp[1];
691 #       context->Rsi = rsp[2];
692 #
693 #       memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
694 #       RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
695 #               dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
696 #               &disp->HandlerData,&disp->EstablisherFrame,NULL);
697 #       return ExceptionContinueSearch;
698 # }
699 #
700 # It's appropriate to implement this handler in assembler, directly in
701 # function's module. In order to do that one has to know members'
702 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
703 # values. Here they are:
704 #
705 #       CONTEXT.Rax                             120
706 #       CONTEXT.Rcx                             128
707 #       CONTEXT.Rdx                             136
708 #       CONTEXT.Rbx                             144
709 #       CONTEXT.Rsp                             152
710 #       CONTEXT.Rbp                             160
711 #       CONTEXT.Rsi                             168
712 #       CONTEXT.Rdi                             176
713 #       CONTEXT.R8                              184
714 #       CONTEXT.R9                              192
715 #       CONTEXT.R10                             200
716 #       CONTEXT.R11                             208
717 #       CONTEXT.R12                             216
718 #       CONTEXT.R13                             224
719 #       CONTEXT.R14                             232
720 #       CONTEXT.R15                             240
721 #       CONTEXT.Rip                             248
722 #       sizeof(CONTEXT)                         1232
723 #       DISPATCHER_CONTEXT.ControlPc            0
724 #       DISPATCHER_CONTEXT.ImageBase            8
725 #       DISPATCHER_CONTEXT.FunctionEntry        16
726 #       DISPATCHER_CONTEXT.EstablisherFrame     24
727 #       DISPATCHER_CONTEXT.TargetIp             32
728 #       DISPATCHER_CONTEXT.ContextRecord        40
729 #       DISPATCHER_CONTEXT.LanguageHandler      48
730 #       DISPATCHER_CONTEXT.HandlerData          56
731 #       UNW_FLAG_NHANDLER                       0
732 #       ExceptionContinueSearch                 1
733 #
734 # UNWIND_INFO structure for .xdata segment would be
735 #       DB      9,0,0,0
736 #       DD      imagerel handler
737 # denoting exception handler for a function with zero-length prologue,
738 # no stack frame or frame register.
739 #
740 # P.S.  Attentive reader can notice that effectively no exceptions are
741 #       expected in "gear" prologue and epilogue [discussed in "ABI
742 #       cross-reference" above]. No, there are not. This is because if
743 #       memory area used by them was subject to segmentation violation,
744 #       then exception would be raised upon call to our function and be
745 #       accounted to caller and unwound from its frame, which is not a
746 #       problem.
747 #
748 # (*)   Note that we're talking about run-time, not debug-time. Lack of
749 #       unwind information makes debugging hard on both Windows and
750 #       Unix. "Unlike" referes to the fact that on Unix signal handler
751 #       will always be invoked, core dumped and appropriate exit code
752 #       returned to parent (for user notification).