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