10b8629e61472ca7def09ef782cef6f59063741d
[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                                         $self->{value}="\$L\$SEH_end_$current_function->{name}:";
466                                         $self->{value}.=":\n$current_function->{name}\tENDP" if($masm);
467                                         undef $current_function;
468                                     }
469                                     last;
470                                   };
471                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
472                 /\.(byte|value|long|quad)/
473                             && do { my $sz  = substr($1,0,1);
474                                     my @arr = split(',',$line);
475                                     my $last = pop(@arr);
476                                     my $conv = sub  {   my $var=shift;
477                                                         $var=~s/0x([0-9a-f]+)/0$1h/ig;
478                                                         $var=~s/\.L/\$L\$/g;
479                                                         if ($current_segment=~/.[px]data/)
480                                                         { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
481                                                         $var;
482                                                     };  
483
484                                     $sz =~ tr/bvlq/BWDQ/;
485                                     $self->{value} = "\tD$sz\t";
486                                     for (@arr) { $self->{value} .= &$conv($_).","; }
487                                     $self->{value} .= &$conv($last);
488                                     last;
489                                   };
490                 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t0%Xh,090000000h",$opcode{$line};
491                                     last;
492                                   };
493                 /\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
494                                         my @str=unpack("C*",$1);
495                                         push @str,0;
496                                         while ($#str>15) {
497                                             $self->{value}.="DB\t"
498                                                 .join(",",@str[0..15])."\n";
499                                             foreach (0..15) { shift @str; }
500                                         }
501                                         $self->{value}.="DB\t"
502                                                 .join(",",@str) if (@str);
503                                     }
504                                     last;
505                                   };
506             }
507             $line = "";
508         }
509
510         $ret;
511     }
512     sub out {
513         my $self = shift;
514         $self->{value};
515     }
516 }
517
518 if ($nasm) {
519     print <<___;
520 default rel
521 ___
522 } elsif ($masm) {
523     print <<___;
524 OPTION  DOTNAME
525 ___
526 }
527 while($line=<>) {
528
529     chomp($line);
530
531     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
532     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
533     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
534
535     undef $label;
536     undef $opcode;
537     undef $dst;
538     undef $src;
539     undef $sz;
540
541     if ($label=label->re(\$line))       { print $label->out(); }
542
543     if (directive->re(\$line)) {
544         printf "%s",directive->out();
545     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
546
547         if ($src=register->re(\$line))  { opcode->size($src->size()); }
548         elsif ($src=const->re(\$line))  { }
549         elsif ($src=ea->re(\$line))     { }
550         elsif ($src=expr->re(\$line))   { }
551
552         last ARGUMENT if ($line !~ /^,/);
553
554         $line = substr($line,1); $line =~ s/^\s+//;
555
556         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
557         elsif ($dst=const->re(\$line))  { }
558         elsif ($dst=ea->re(\$line))     { }
559
560         } # ARGUMENT:
561
562         $sz=opcode->size();
563
564         if (defined($dst)) {
565             if (!$win64) {
566                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
567                                         $src->out($sz),$dst->out($sz);
568             } else {
569                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
570                 printf "\t%s\t%s,%s",   $opcode->out(),
571                                         $dst->out($sz),$src->out($sz);
572             }
573         } elsif (defined($src)) {
574             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
575         } else {
576             printf "\t%s",$opcode->out();
577         }
578     }
579
580     print $line,"\n";
581 }
582
583 print "\n$current_segment\tENDS\nEND\n" if ($current_segment && $masm);
584
585 close STDOUT;
586
587 \f#################################################
588 # Cross-reference x86_64 ABI "card"
589 #
590 #               Unix            Win64
591 # %rax          *               *
592 # %rbx          -               -
593 # %rcx          #4              #1
594 # %rdx          #3              #2
595 # %rsi          #2              -
596 # %rdi          #1              -
597 # %rbp          -               -
598 # %rsp          -               -
599 # %r8           #5              #3
600 # %r9           #6              #4
601 # %r10          *               *
602 # %r11          *               *
603 # %r12          -               -
604 # %r13          -               -
605 # %r14          -               -
606 # %r15          -               -
607
608 # (*)   volatile register
609 # (-)   preserved by callee
610 # (#)   Nth argument, volatile
611 #
612 # In Unix terms top of stack is argument transfer area for arguments
613 # which could not be accomodated in registers. Or in other words 7th
614 # [integer] argument resides at 8(%rsp) upon function entry point.
615 # 128 bytes above %rsp constitute a "red zone" which is not touched
616 # by signal handlers and can be used as temporal storage without
617 # allocating a frame.
618 #
619 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
620 # which belongs to/can be overwritten by callee. N is the number of
621 # arguments passed to callee, *but* not less than 4! This means that
622 # upon function entry point 5th argument resides at 40(%rsp), as well
623 # as that 32 bytes from 8(%rsp) can always be used as temporal
624 # storage [without allocating a frame]. One can actually argue that
625 # one can assume a "red zone" above stack pointer under Win64 as well.
626 # Point is that at apparently no occasion Windows kernel would alter
627 # the area above user stack pointer in true asynchronous manner...
628 #
629 # All the above means that if assembler programmer adheres to Unix
630 # register and stack layout, but disregards the "red zone" existense,
631 # it's possible to use following prologue and epilogue to "gear" from
632 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
633 #
634 # omnipotent_function:
635 # ifdef WIN64
636 #       movq    %rdi,8(%rsp)
637 #       movq    %rsi,16(%rsp)
638 #       movq    %rcx,%rdi       ; if 1st argument is actually present
639 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
640 #       movq    %r8,%rdx        ; if 3rd argument is ...
641 #       movq    %r9,%rcx        ; if 4th argument ...
642 #       movq    40(%rsp),%r8    ; if 5th ...
643 #       movq    48(%rsp),%r9    ; if 6th ...
644 # endif
645 #       ...
646 # ifdef WIN64
647 #       movq    8(%rsp),%rdi
648 #       movq    16(%rsp),%rsi
649 # endif
650 #       ret
651 #
652 \f#################################################
653 # Win64 SEH, Structured Exception Handling.
654 #
655 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
656 # has undesired side-effect at run-time: if an exception is raised in
657 # assembler subroutine such as those in question (basically we're
658 # referring to segmentation violations caused by malformed input
659 # parameters), the application is briskly terminated without invoking
660 # any exception handlers, most notably without generating memory dump
661 # or any user notification whatsoever. This poses a problem. It's
662 # possible to address it by registering custom language-specific
663 # handler that would restore processor context to the state at
664 # subroutine entry point and return "exception is not handled, keep
665 # unwinding" code. Writing such handler can be a challenge... But it's
666 # doable, though requires certain coding convention. Consider following
667 # snippet:
668 #
669 # .type function,@function
670 # function:
671 #       movq    %rsp,%rax       # copy rsp to volatile register
672 #       pushq   %r15            # save non-volatile registers
673 #       pushq   %rbx
674 #       pushq   %rbp
675 #       movq    %rsp,%r11
676 #       subq    %rdi,%r11       # prepare [variable] stack frame
677 #       andq    $-64,%r11
678 #       movq    %rax,0(%r11)    # check for exceptions
679 #       movq    %r11,%rsp       # allocate [variable] stack frame
680 #       movq    %rax,0(%rsp)    # save original rsp value
681 # magic_point:
682 #       ...
683 #       movq    0(%rsp),%rcx    # pull original rsp value
684 #       movq    -24(%rcx),%rbp  # restore non-volatile registers
685 #       movq    -16(%rcx),%rbx
686 #       movq    -8(%rcx),%r15
687 #       movq    %rcx,%rsp       # restore original rsp
688 #       ret
689 # .size function,.-function
690 #
691 # The key is that up to magic_point copy of original rsp value remains
692 # in chosen volatile register and no non-volatile register, except for
693 # rsp, is modified. While past magic_point rsp remains constant till
694 # the very end of the function. In this case custom language-specific
695 # exception handler would look like this:
696 #
697 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
698 #               CONTEXT *context,DISPATCHER_CONTEXT *disp)
699 # {     ULONG64 *rsp = (ULONG64 *)context->Rax;
700 #       if (context->Rip >= magic_point)
701 #       {   rsp = ((ULONG64 **)context->Rsp)[0];
702 #           context->Rbp = rsp[-3];
703 #           context->Rbx = rsp[-2];
704 #           context->R15 = rsp[-1];
705 #       }
706 #       context->Rsp = (ULONG64)rsp;
707 #       context->Rdi = rsp[1];
708 #       context->Rsi = rsp[2];
709 #
710 #       memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
711 #       RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
712 #               dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
713 #               &disp->HandlerData,&disp->EstablisherFrame,NULL);
714 #       return ExceptionContinueSearch;
715 # }
716 #
717 # It's appropriate to implement this handler in assembler, directly in
718 # function's module. In order to do that one has to know members'
719 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
720 # values. Here they are:
721 #
722 #       CONTEXT.Rax                             120
723 #       CONTEXT.Rcx                             128
724 #       CONTEXT.Rdx                             136
725 #       CONTEXT.Rbx                             144
726 #       CONTEXT.Rsp                             152
727 #       CONTEXT.Rbp                             160
728 #       CONTEXT.Rsi                             168
729 #       CONTEXT.Rdi                             176
730 #       CONTEXT.R8                              184
731 #       CONTEXT.R9                              192
732 #       CONTEXT.R10                             200
733 #       CONTEXT.R11                             208
734 #       CONTEXT.R12                             216
735 #       CONTEXT.R13                             224
736 #       CONTEXT.R14                             232
737 #       CONTEXT.R15                             240
738 #       CONTEXT.Rip                             248
739 #       sizeof(CONTEXT)                         1232
740 #       DISPATCHER_CONTEXT.ControlPc            0
741 #       DISPATCHER_CONTEXT.ImageBase            8
742 #       DISPATCHER_CONTEXT.FunctionEntry        16
743 #       DISPATCHER_CONTEXT.EstablisherFrame     24
744 #       DISPATCHER_CONTEXT.TargetIp             32
745 #       DISPATCHER_CONTEXT.ContextRecord        40
746 #       DISPATCHER_CONTEXT.LanguageHandler      48
747 #       DISPATCHER_CONTEXT.HandlerData          56
748 #       UNW_FLAG_NHANDLER                       0
749 #       ExceptionContinueSearch                 1
750 #
751 # In order to tie the handler to the function one has to compose
752 # couple of structures: one for .xdata segment and one for .pdata.
753 #
754 # UNWIND_INFO structure for .xdata segment would be
755 #
756 # function_unwind_info:
757 #       .byte   9,0,0,0
758 #       .long   handler
759 #
760 # This structure designates exception handler for a function with
761 # zero-length prologue, no stack frame or frame register.
762 #
763 # To facilitate composing of .pdata structures, auto-generated "gear"
764 # prologue copies rsp value to rax and denotes next instruction with
765 # $L$SEH_begin_{function_name} label. This essentially defines the SEH
766 # styling rule mentioned in the beginning. Position of this label is
767 # chosen in such manner that possible exceptions raised in the "gear"
768 # prologue would be accounted to caller and unwound from latter's frame.
769 # End of function is marked with respective $L$SEH_end_{function_name}
770 # label. To summarize, .pdata segment would contain
771 #
772 #       .long   $L$SEH_begin_function
773 #       .long   $L$SEH_end_function
774 #       .long   function_unwind_info
775 #
776 # Reference to functon_unwind_info from .xdata segment is the anchor.
777 # In case you wonder why references are 32-bit .longs and not 64-bit
778 # .quads. References put into these two segments are required to be
779 # *relative* to the base address of the current binary module, a.k.a.
780 # image base. No Win64 module, be it .exe or .dll, can be larger than
781 # 2GB and thus such relative references can be and are accommodated in
782 # 32 bits.
783 #
784 # Having reviewed the example function code, one can argue that "movq
785 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
786 # rax would contain an undefined value. If this "offends" you, use
787 # another register and refrain from modifying rax till magic_point is
788 # reached, i.e. as if it was a non-volatile register. If more registers
789 # are required prior [variable] frame setup is completed, note that
790 # nobody says that you can have only one "magic point." You can
791 # "liberate" non-volatile registers by denoting last stack off-load
792 # instruction and reflecting it in finer grade unwind logic in handler.
793 # After all, isn't it why it's called *language-specific* handler...
794 #
795 # Attentive reader can notice that exceptions would be mishandled in
796 # auto-generated "gear" epilogue. Well, exception effectively can't
797 # occur there, because if memory area used by it was subject to
798 # segmentation violation, then it would be raised upon call to the
799 # function (and as already mentioned be accounted to caller, which is
800 # not a problem). If you're still not comfortable, then define tail
801 # "magic point" just prior ret instruction and have handler treat it...
802 #
803 # (*)   Note that we're talking about run-time, not debug-time. Lack of
804 #       unwind information makes debugging hard on both Windows and
805 #       Unix. "Unlike" referes to the fact that on Unix signal handler
806 #       will always be invoked, core dumped and appropriate exit code
807 #       returned to parent (for user notification).