3 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
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...
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.
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...
20 # Currently recognized limitations:
22 # - can't use multiple ops per line;
24 # Dual-ABI styling rules.
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. Stick to explicit ip-relative addressing. If you have to use
45 # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
46 # Both are recognized and translated to proper Win64 addressing
47 # modes. To support legacy code a synthetic directive, .picmeup,
48 # is implemented. It puts address of the *next* instruction into
49 # target register, e.g.:
52 # lea .Label-.(%rax),%rax
54 # 8. In order to provide for structured exception handling unified
55 # Win64 prologue copies %rsp value to %rax. For further details
56 # see SEH paragraph at the end.
57 # 9. .init segment is allowed to contain calls to functions only.
61 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
63 { my ($stddev,$stdino,@junk)=stat(STDOUT);
64 my ($outdev,$outino,@junk)=stat($output);
66 open STDOUT,">$output" || die "can't open $output: $!"
67 if ($stddev!=$outdev || $stdino!=$outino);
70 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
71 my $elf=1; $elf=0 if (!$gas);
76 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
83 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1; $prefix="_"; }
84 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
85 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
86 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
88 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
89 { $nasm = $1 + $2*0.01; $PTR=""; }
90 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
91 { $masm = $1 + $2*2**-16 + $4*2**-32; }
92 die "no assembler found on %PATH" if (!($nasm || $masm));
102 { package opcode; # pick up opcodes
104 my $self = shift; # single instance in enough...
108 if ($line =~ /^([a-z][a-z0-9]*)/i) {
111 $line = substr($line,@+[0]); $line =~ s/^\s+//;
114 if ($self->{op} =~ /^(movz)b.*/) { # movz is pain...
117 } elsif ($self->{op} =~ /call|jmp/) {
119 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
129 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
135 if ($self->{op} eq "movz") { # movz is pain...
136 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
137 } elsif ($self->{op} =~ /^set/) {
139 } elsif ($self->{op} eq "ret") {
141 if ($win64 && $current_function->{abi} eq "svr4") {
142 $epilogue = "movq 8(%rsp),%rdi\n\t" .
143 "movq 16(%rsp),%rsi\n\t";
145 $epilogue . ".byte 0xf3,0xc3";
146 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
147 ".p2align\t3\n\t.quad";
149 "$self->{op}$self->{sz}";
152 $self->{op} =~ s/^movz/movzx/;
153 if ($self->{op} eq "ret") {
155 if ($win64 && $current_function->{abi} eq "svr4") {
156 $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
157 "mov rsi,QWORD${PTR}[16+rsp]\n\t";
159 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
160 } elsif ($self->{op} =~ /^(pop|push)f/) {
161 $self->{op} .= $self->{sz};
162 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
163 $self->{op} = "ALIGN\t8\n\tDQ";
171 $self->{op}=$op if (defined($op));
175 { package const; # pick up constants, which start with $
177 my $self = shift; # single instance in enough...
181 if ($line =~ /^\$([^,]+)/) {
184 $line = substr($line,@+[0]); $line =~ s/^\s+//;
192 # Solaris /usr/ccs/bin/as can't handle multiplications
194 $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
195 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
196 sprintf "\$%s",$self->{value};
198 $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
199 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
200 sprintf "%s",$self->{value};
204 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
206 my $self = shift; # single instance in enough...
210 # optional * ---vvv--- appears in indirect jmp/call
211 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
212 $self->{asterisk} = $1;
214 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
215 $self->{scale} = 1 if (!defined($self->{scale}));
217 $line = substr($line,@+[0]); $line =~ s/^\s+//;
219 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
220 die if (opcode->mnemonic() ne "mov");
221 opcode->mnemonic("lea");
223 $self->{base} =~ s/^%//;
224 $self->{index} =~ s/^%// if (defined($self->{index}));
233 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
234 $self->{label} =~ s/\.L/$decor/g;
236 # Silently convert all EAs to 64-bit. This is required for
237 # elder GNU assembler and results in more compact code,
238 # *but* most importantly AES module depends on this feature!
239 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
240 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
243 # Solaris /usr/ccs/bin/as can't handle multiplications
244 # in $self->{label}, new gas requires sign extension...
246 $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
247 $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
248 $self->{label} =~ s/([0-9]+)/$1<<32>>32/eg;
249 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
251 if (defined($self->{index})) {
252 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk},
253 $self->{label},$self->{base},
254 $self->{index},$self->{scale};
256 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
259 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
261 $self->{label} =~ s/\./\$/g;
262 $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
263 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
264 $sz="q" if ($self->{asterisk});
266 if (defined($self->{index})) {
267 sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
268 $self->{label}?"$self->{label}+":"",
269 $self->{index},$self->{scale},
271 } elsif ($self->{base} eq "rip") {
272 sprintf "%s[%s]",$szmap{$sz},$self->{label};
274 sprintf "%s[%s%s]",$szmap{$sz},
275 $self->{label}?"$self->{label}+":"",
281 { package register; # pick up registers, which start with %.
283 my $class = shift; # muliple instances...
288 # optional * ---vvv--- appears in indirect jmp/call
289 if ($line =~ /^(\*?)%(\w+)/) {
291 $self->{asterisk} = $1;
294 $line = substr($line,@+[0]); $line =~ s/^\s+//;
302 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
303 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
304 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
305 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
306 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
307 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
308 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
309 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
315 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
316 else { $self->{value}; }
319 { package label; # pick up labels, which end with :
321 my $self = shift; # single instance is enough...
325 if ($line =~ /(^[\.\w]+)\:/) {
328 $line = substr($line,@+[0]); $line =~ s/^\s+//;
330 $self->{value} =~ s/^\.L/$decor/;
338 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
340 $current_function->{name} eq $self->{value} &&
341 $current_function->{abi} eq "svr4") {
343 $func .= " movq %rdi,8(%rsp)\n";
344 $func .= " movq %rsi,16(%rsp)\n";
345 $func .= " movq %rsp,%rax\n";
346 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
347 my $narg = $current_function->{narg};
348 $narg=6 if (!defined($narg));
349 $func .= " movq %rcx,%rdi\n" if ($narg>0);
350 $func .= " movq %rdx,%rsi\n" if ($narg>1);
351 $func .= " movq %r8,%rdx\n" if ($narg>2);
352 $func .= " movq %r9,%rcx\n" if ($narg>3);
353 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
354 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
357 } elsif ($self->{value} ne "$current_function->{name}") {
358 $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
359 $self->{value} . ":";
360 } elsif ($win64 && $current_function->{abi} eq "svr4") {
361 my $func = "$current_function->{name}" .
362 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
364 $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
365 $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
366 $func .= " mov rax,rsp\n";
367 $func .= "${decor}SEH_begin_$current_function->{name}:";
368 $func .= ":" if ($masm);
370 my $narg = $current_function->{narg};
371 $narg=6 if (!defined($narg));
372 $func .= " mov rdi,rcx\n" if ($narg>0);
373 $func .= " mov rsi,rdx\n" if ($narg>1);
374 $func .= " mov rdx,r8\n" if ($narg>2);
375 $func .= " mov rcx,r9\n" if ($narg>3);
376 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
377 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
380 "$current_function->{name}".
381 ($nasm ? ":" : "\tPROC $current_function->{scope}");
385 { package expr; # pick up expressioins
387 my $self = shift; # single instance is enough...
391 if ($line =~ /(^[^,]+)/) {
394 $line = substr($line,@+[0]); $line =~ s/^\s+//;
396 $self->{value} =~ s/\@PLT// if (!$elf);
397 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
398 $self->{value} =~ s/\.L/$decor/g;
404 if ($nasm && opcode->mnemonic()=~m/^j/) {
405 "NEAR ".$self->{value};
411 { package directive; # pick up directives, which start with .
413 my $self = shift; # single instance is enough...
417 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
418 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
419 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
420 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
421 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
422 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
423 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
424 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
425 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
427 if ($line =~ /^\s*(\.\w+)/) {
430 undef $self->{value};
431 $line = substr($line,@+[0]); $line =~ s/^\s+//;
434 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
436 $line=sprintf "0x%x,0x90000000",$opcode{$1};
440 /\.global|\.globl|\.extern/
441 && do { $globals{$line} = $prefix . $line;
442 $line = $globals{$line} if ($prefix);
445 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
446 if ($type eq "\@function") {
447 undef $current_function;
448 $current_function->{name} = $sym;
449 $current_function->{abi} = "svr4";
450 $current_function->{narg} = $narg;
451 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
452 } elsif ($type eq "\@abi-omnipotent") {
453 undef $current_function;
454 $current_function->{name} = $sym;
455 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
457 $line =~ s/\@abi\-omnipotent/\@function/;
458 $line =~ s/\@function.*/\@function/;
461 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
463 $line = join(",",unpack("C*",$1),0);
467 /\.rva|\.long|\.quad/
468 && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
469 $line =~ s/\.L/$decor/g;
475 $self->{value} = $dir . "\t" . $line;
477 if ($dir =~ /\.extern/) {
478 $self->{value} = ""; # swallow extern
479 } elsif (!$elf && $dir =~ /\.type/) {
481 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
482 (defined($globals{$1})?".scl 2;":".scl 3;") .
483 "\t.type 32;\t.endef"
484 if ($win64 && $line =~ /([^,]+),\@function/);
485 } elsif (!$elf && $dir =~ /\.size/) {
487 if (defined($current_function)) {
488 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
489 if ($win64 && $current_function->{abi} eq "svr4");
490 undef $current_function;
492 } elsif (!$elf && $dir =~ /\.align/) {
493 $self->{value} = ".p2align\t" . (log($line)/log(2));
494 } elsif ($dir eq ".section") {
495 $current_segment=$line;
496 if (!$elf && $current_segment eq ".init") {
497 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
498 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
500 } elsif ($dir =~ /\.(text|data)/) {
501 $current_segment=".$1";
507 # non-gas case or nasm/masm
509 /\.text/ && do { my $v=undef;
511 $v="section .text code align=64\n";
513 $v="$current_segment\tENDS\n" if ($current_segment);
514 $current_segment = ".text\$";
515 $v.="$current_segment\tSEGMENT ";
516 $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
522 /\.data/ && do { my $v=undef;
524 $v="section .data data align=8\n";
526 $v="$current_segment\tENDS\n" if ($current_segment);
527 $current_segment = "_DATA";
528 $v.="$current_segment\tSEGMENT";
533 /\.section/ && do { my $v=undef;
534 $line =~ s/([^,]*).*/$1/;
535 $line = ".CRT\$XCU" if ($line eq ".init");
538 if ($line=~/\.([px])data/) {
540 $v.=$1 eq "p"? 4 : 8;
543 $v="$current_segment\tENDS\n" if ($current_segment);
544 $v.="$line\tSEGMENT";
545 if ($line=~/\.([px])data/) {
547 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
550 $current_segment = $line;
554 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
555 $self->{value} .= ":NEAR" if ($masm);
559 && do { $self->{value} = $masm?"PUBLIC":"global";
560 $self->{value} .= "\t".$line;
563 /\.size/ && do { if (defined($current_function)) {
564 undef $self->{value};
565 if ($current_function->{abi} eq "svr4") {
566 $self->{value}="${decor}SEH_end_$current_function->{name}:";
567 $self->{value}.=":\n" if($masm);
569 $self->{value}.="$current_function->{name}\tENDP" if($masm);
570 undef $current_function;
574 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
575 /\.(value|long|rva|quad)/
576 && do { my $sz = substr($1,0,1);
577 my @arr = split(',',$line);
578 my $last = pop(@arr);
579 my $conv = sub { my $var=shift;
580 $var=~s/^(0b[0-1]+)/oct($1)/eig;
581 $var=~s/0x([0-9a-f]+)/0$1h/ig if ($masm);
582 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
583 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
587 $sz =~ tr/bvlrq/BWDDQ/;
588 $self->{value} = "\tD$sz\t";
589 for (@arr) { $self->{value} .= &$conv($_).","; }
590 $self->{value} .= &$conv($last);
593 /\.byte/ && do { my @str=split(",",$line);
594 map(s/(0b[0-1]+)/oct($1)/eig,@str);
595 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
597 $self->{value}.="DB\t"
598 .join(",",@str[0..15])."\n";
599 foreach (0..15) { shift @str; }
601 $self->{value}.="DB\t"
602 .join(",",@str) if (@str);
630 $line =~ s|[#!].*$||; # get rid of asm-style comments...
631 $line =~ s|/\*.*\*/||; # ... and C-style comments...
632 $line =~ s|^\s+||; # ... and skip white spaces in beginning
639 if ($label=label->re(\$line)) { print $label->out(); }
641 if (directive->re(\$line)) {
642 printf "%s",directive->out();
643 } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: while (1) {
646 if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
647 elsif ($arg=const->re(\$line)) { }
648 elsif ($arg=ea->re(\$line)) { }
649 elsif ($arg=expr->re(\$line)) { }
650 else { last ARGUMENT; }
654 last ARGUMENT if ($line !~ /^,/);
664 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
666 $insn = $opcode->out();
667 $insn .= $sz if (map($_->out() =~ /xmm|mmx/,@args));
668 @args = reverse(@args);
669 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
671 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
673 printf "\t%s",$opcode->out();
680 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
681 print "END\n" if ($masm);
685 \f#################################################
686 # Cross-reference x86_64 ABI "card"
706 # (*) volatile register
707 # (-) preserved by callee
708 # (#) Nth argument, volatile
710 # In Unix terms top of stack is argument transfer area for arguments
711 # which could not be accomodated in registers. Or in other words 7th
712 # [integer] argument resides at 8(%rsp) upon function entry point.
713 # 128 bytes above %rsp constitute a "red zone" which is not touched
714 # by signal handlers and can be used as temporal storage without
715 # allocating a frame.
717 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
718 # which belongs to/can be overwritten by callee. N is the number of
719 # arguments passed to callee, *but* not less than 4! This means that
720 # upon function entry point 5th argument resides at 40(%rsp), as well
721 # as that 32 bytes from 8(%rsp) can always be used as temporal
722 # storage [without allocating a frame]. One can actually argue that
723 # one can assume a "red zone" above stack pointer under Win64 as well.
724 # Point is that at apparently no occasion Windows kernel would alter
725 # the area above user stack pointer in true asynchronous manner...
727 # All the above means that if assembler programmer adheres to Unix
728 # register and stack layout, but disregards the "red zone" existense,
729 # it's possible to use following prologue and epilogue to "gear" from
730 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
732 # omnipotent_function:
736 # movq %rcx,%rdi ; if 1st argument is actually present
737 # movq %rdx,%rsi ; if 2nd argument is actually ...
738 # movq %r8,%rdx ; if 3rd argument is ...
739 # movq %r9,%rcx ; if 4th argument ...
740 # movq 40(%rsp),%r8 ; if 5th ...
741 # movq 48(%rsp),%r9 ; if 6th ...
750 \f#################################################
751 # Win64 SEH, Structured Exception Handling.
753 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
754 # has undesired side-effect at run-time: if an exception is raised in
755 # assembler subroutine such as those in question (basically we're
756 # referring to segmentation violations caused by malformed input
757 # parameters), the application is briskly terminated without invoking
758 # any exception handlers, most notably without generating memory dump
759 # or any user notification whatsoever. This poses a problem. It's
760 # possible to address it by registering custom language-specific
761 # handler that would restore processor context to the state at
762 # subroutine entry point and return "exception is not handled, keep
763 # unwinding" code. Writing such handler can be a challenge... But it's
764 # doable, though requires certain coding convention. Consider following
767 # .type function,@function
769 # movq %rsp,%rax # copy rsp to volatile register
770 # pushq %r15 # save non-volatile registers
774 # subq %rdi,%r11 # prepare [variable] stack frame
776 # movq %rax,0(%r11) # check for exceptions
777 # movq %r11,%rsp # allocate [variable] stack frame
778 # movq %rax,0(%rsp) # save original rsp value
781 # movq 0(%rsp),%rcx # pull original rsp value
782 # movq -24(%rcx),%rbp # restore non-volatile registers
783 # movq -16(%rcx),%rbx
785 # movq %rcx,%rsp # restore original rsp
787 # .size function,.-function
789 # The key is that up to magic_point copy of original rsp value remains
790 # in chosen volatile register and no non-volatile register, except for
791 # rsp, is modified. While past magic_point rsp remains constant till
792 # the very end of the function. In this case custom language-specific
793 # exception handler would look like this:
795 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
796 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
797 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
798 # if (context->Rip >= magic_point)
799 # { rsp = ((ULONG64 **)context->Rsp)[0];
800 # context->Rbp = rsp[-3];
801 # context->Rbx = rsp[-2];
802 # context->R15 = rsp[-1];
804 # context->Rsp = (ULONG64)rsp;
805 # context->Rdi = rsp[1];
806 # context->Rsi = rsp[2];
808 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
809 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
810 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
811 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
812 # return ExceptionContinueSearch;
815 # It's appropriate to implement this handler in assembler, directly in
816 # function's module. In order to do that one has to know members'
817 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
818 # values. Here they are:
838 # sizeof(CONTEXT) 1232
839 # DISPATCHER_CONTEXT.ControlPc 0
840 # DISPATCHER_CONTEXT.ImageBase 8
841 # DISPATCHER_CONTEXT.FunctionEntry 16
842 # DISPATCHER_CONTEXT.EstablisherFrame 24
843 # DISPATCHER_CONTEXT.TargetIp 32
844 # DISPATCHER_CONTEXT.ContextRecord 40
845 # DISPATCHER_CONTEXT.LanguageHandler 48
846 # DISPATCHER_CONTEXT.HandlerData 56
847 # UNW_FLAG_NHANDLER 0
848 # ExceptionContinueSearch 1
850 # In order to tie the handler to the function one has to compose
851 # couple of structures: one for .xdata segment and one for .pdata.
853 # UNWIND_INFO structure for .xdata segment would be
855 # function_unwind_info:
859 # This structure designates exception handler for a function with
860 # zero-length prologue, no stack frame or frame register.
862 # To facilitate composing of .pdata structures, auto-generated "gear"
863 # prologue copies rsp value to rax and denotes next instruction with
864 # .LSEH_begin_{function_name} label. This essentially defines the SEH
865 # styling rule mentioned in the beginning. Position of this label is
866 # chosen in such manner that possible exceptions raised in the "gear"
867 # prologue would be accounted to caller and unwound from latter's frame.
868 # End of function is marked with respective .LSEH_end_{function_name}
869 # label. To summarize, .pdata segment would contain
871 # .rva .LSEH_begin_function
872 # .rva .LSEH_end_function
873 # .rva function_unwind_info
875 # Reference to functon_unwind_info from .xdata segment is the anchor.
876 # In case you wonder why references are 32-bit .rvas and not 64-bit
877 # .quads. References put into these two segments are required to be
878 # *relative* to the base address of the current binary module, a.k.a.
879 # image base. No Win64 module, be it .exe or .dll, can be larger than
880 # 2GB and thus such relative references can be and are accommodated in
883 # Having reviewed the example function code, one can argue that "movq
884 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
885 # rax would contain an undefined value. If this "offends" you, use
886 # another register and refrain from modifying rax till magic_point is
887 # reached, i.e. as if it was a non-volatile register. If more registers
888 # are required prior [variable] frame setup is completed, note that
889 # nobody says that you can have only one "magic point." You can
890 # "liberate" non-volatile registers by denoting last stack off-load
891 # instruction and reflecting it in finer grade unwind logic in handler.
892 # After all, isn't it why it's called *language-specific* handler...
894 # Attentive reader can notice that exceptions would be mishandled in
895 # auto-generated "gear" epilogue. Well, exception effectively can't
896 # occur there, because if memory area used by it was subject to
897 # segmentation violation, then it would be raised upon call to the
898 # function (and as already mentioned be accounted to caller, which is
899 # not a problem). If you're still not comfortable, then define tail
900 # "magic point" just prior ret instruction and have handler treat it...
902 # (*) Note that we're talking about run-time, not debug-time. Lack of
903 # unwind information makes debugging hard on both Windows and
904 # Unix. "Unlike" referes to the fact that on Unix signal handler
905 # will always be invoked, core dumped and appropriate exit code
906 # returned to parent (for user notification).