2 # Copyright 2005-2022 The OpenSSL Project Authors. All Rights Reserved.
4 # Licensed under the Apache License 2.0 (the "License"). You may not use
5 # this file except in compliance with the License. You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
10 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
12 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
13 # format is way easier to parse. Because it's simpler to "gear" from
14 # Unix ABI to Windows one [see cross-reference "card" at the end of
15 # file]. Because Linux targets were available first...
17 # In addition the script also "distills" code suitable for GNU
18 # assembler, so that it can be compiled with more rigid assemblers,
19 # such as Solaris /usr/ccs/bin/as.
21 # This translator is not designed to convert *arbitrary* assembler
22 # code from AT&T format to MASM one. It's designed to convert just
23 # enough to provide for dual-ABI OpenSSL modules development...
24 # There *are* limitations and you might have to modify your assembler
25 # code or this script to achieve the desired result...
27 # Currently recognized limitations:
29 # - can't use multiple ops per line;
31 # Dual-ABI styling rules.
33 # 1. Adhere to Unix register and stack layout [see cross-reference
34 # ABI "card" at the end for explanation].
35 # 2. Forget about "red zone," stick to more traditional blended
36 # stack frame allocation. If volatile storage is actually required
37 # that is. If not, just leave the stack as is.
38 # 3. Functions tagged with ".type name,@function" get crafted with
39 # unified Win64 prologue and epilogue automatically. If you want
40 # to take care of ABI differences yourself, tag functions as
41 # ".type name,@abi-omnipotent" instead.
42 # 4. To optimize the Win64 prologue you can specify number of input
43 # arguments as ".type name,@function,N." Keep in mind that if N is
44 # larger than 6, then you *have to* write "abi-omnipotent" code,
45 # because >6 cases can't be addressed with unified prologue.
46 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
47 # (sorry about latter).
48 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
49 # required to identify the spots, where to inject Win64 epilogue!
50 # But on the pros, it's then prefixed with rep automatically:-)
51 # 7. Stick to explicit ip-relative addressing. If you have to use
52 # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
53 # Both are recognized and translated to proper Win64 addressing
56 # 8. In order to provide for structured exception handling unified
57 # Win64 prologue copies %rsp value to %rax. For further details
58 # see SEH paragraph at the end.
59 # 9. .init segment is allowed to contain calls to functions only.
60 # a. If function accepts more than 4 arguments *and* >4th argument
61 # is declared as non 64-bit value, do clear its upper part.
68 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
70 open STDOUT,">$output" || die "can't open $output: $!"
71 if (defined($output));
73 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
74 my $elf=1; $elf=0 if (!$gas);
79 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
86 # GNU as indicator, as opposed to $gas, which indicates acceptable
90 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
91 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
92 $prefix =~ s|\R$||; # Better chomp
94 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
95 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
96 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
98 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
99 { $nasm = $1 + $2*0.01; $PTR=""; }
100 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
101 { $masm = $1 + $2*2**-16 + $4*2**-32; }
102 die "no assembler found on %PATH%" if (!($nasm || $masm));
107 # Find out if we're using GNU as
108 elsif (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1`
109 =~ /GNU assembler version ([2-9]\.[0-9]+)/)
113 elsif (`$ENV{CC} --version 2>/dev/null`
114 =~ /(clang .*|Intel.*oneAPI .*)/)
118 elsif (`$ENV{CC} -V 2>/dev/null`
125 if ($flavour =~ /elf/) {
126 # Always generate .note.gnu.property section for ELF outputs to
127 # mark Intel CET support since all input files must be marked
128 # with Intel CET support in order for linker to mark output with
130 my $p2align=3; $p2align=2 if ($flavour eq "elf32");
131 my $section='.note.gnu.property, #alloc';
132 $section='".note.gnu.property", "a"' if $gnuas;
133 $cet_property = <<_____;
140 # "GNU" encoded with .byte, since .asciz isn't supported
160 # I could not find equivalent of .previous directive for MASM (Microsoft
161 # assembler ML). Using of .previous got introduced to .pl files with
162 # placing of various constants into .rodata sections (segments).
163 # Each .rodata section is terminated by .previous directive which
164 # restores the preceding section to .rodata:
167 # ; this is is the text section/segment
169 # ; constant definitions go here
171 # ; the .text section which precedes .rodata got restored here
173 # The equivalent form for masm reads as follows:
175 # .text$ SEGMENT ALIGN(256) 'CODE'
176 # ; this is is the text section/segment
178 # .rdata SEGMENT READONLY ALIGN(64)
179 # ; constant definitions go here
181 # .text$ SEGMENT ALIGN(256) 'CODE'
182 # ; text section follows
185 # The .previous directive typically terminates .roadata segments/sections which
186 # hold definitions of constants. In order to place constants into .rdata
187 # segments when using masm we need to introduce a segment_stack array so we can
188 # emit proper ENDS directive whenever we see .previous.
190 # The code is tailored to work current set of .pl/asm files. There are some
191 # inconsistencies. For example .text section is the first section in all those
192 # files except ecp_nistz256. So we need to take that into account.
196 # ; push '.text ' section twice, the stack looks as
198 # ; ('.text', '.text')
200 # ; pop() so we can generate proper 'ENDS' for masm.
201 # ; stack looks like:
203 # ; push '.rodata', so we can create corresponding ENDS for masm.
204 # ; stack looks like:
205 # ; ('.rodata', '.text')
207 # ; pop() '.rodata' from stack, so we create '.rodata ENDS'
208 # ; in masm flavour. For nasm flavour we just pop() because
209 # ; nasm does not use .rodata ENDS to close the current section
210 # ; the stack content is like this:
211 # ; ('.text', '.text')
212 # ; pop() again to find a previous section we need to restore.
213 # ; Depending on flavour we either generate .section .text
214 # ; or .text SEGMENT. The stack looks like:
217 my @segment_stack = ();
218 my $current_function;
221 { package opcode; # pick up opcodes
223 my ($class, $line) = @_;
227 if ($$line =~ /^([a-z][a-z0-9]*)/i) {
231 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
234 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
237 } elsif ($self->{op} =~ /call|jmp/) {
239 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
241 } elsif ($self->{op} =~ /^[vk]/) { # VEX or k* such as kmov
243 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) {
245 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
253 my ($self, $sz) = @_;
254 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
260 if ($self->{op} eq "movz") { # movz is pain...
261 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
262 } elsif ($self->{op} =~ /^set/) {
264 } elsif ($self->{op} eq "ret") {
266 if ($win64 && $current_function->{abi} eq "svr4") {
267 $epilogue = "movq 8(%rsp),%rdi\n\t" .
268 "movq 16(%rsp),%rsi\n\t";
270 $epilogue . ".byte 0xf3,0xc3";
271 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
272 ".p2align\t3\n\t.quad";
274 "$self->{op}$self->{sz}";
277 $self->{op} =~ s/^movz/movzx/;
278 if ($self->{op} eq "ret") {
280 if ($win64 && $current_function->{abi} eq "svr4") {
281 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t".
282 "mov rsi,QWORD$PTR\[16+rsp\]\n\t";
284 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
285 } elsif ($self->{op} =~ /^(pop|push)f/) {
286 $self->{op} .= $self->{sz};
287 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
288 $self->{op} = "\tDQ";
294 my ($self, $op) = @_;
295 $self->{op}=$op if (defined($op));
299 { package const; # pick up constants, which start with $
301 my ($class, $line) = @_;
305 if ($$line =~ /^\$([^,]+)/) {
309 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
316 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
318 # Solaris /usr/ccs/bin/as can't handle multiplications
320 my $value = $self->{value};
321 no warnings; # oct might complain about overflow, ignore here...
322 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
323 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
324 $self->{value} = $value;
326 sprintf "\$%s",$self->{value};
328 my $value = $self->{value};
329 $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
334 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
336 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
337 l=>"DWORD$PTR", d=>"DWORD$PTR",
338 q=>"QWORD$PTR", o=>"OWORD$PTR",
339 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR",
340 z=>"ZMMWORD$PTR" ) if (!$gas);
343 my ($class, $line, $opcode) = @_;
347 # optional * ----vvv--- appears in indirect jmp/call
348 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) {
350 $self->{asterisk} = $1;
352 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
353 $self->{scale} = 1 if (!defined($self->{scale}));
354 $self->{opmask} = $4;
356 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
358 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
359 die if ($opcode->mnemonic() ne "mov");
360 $opcode->mnemonic("lea");
362 $self->{base} =~ s/^%//;
363 $self->{index} =~ s/^%// if (defined($self->{index}));
364 $self->{opcode} = $opcode;
370 my ($self, $sz) = @_;
372 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
373 $self->{label} =~ s/\.L/$decor/g;
375 # Silently convert all EAs to 64-bit. This is required for
376 # elder GNU assembler and results in more compact code,
377 # *but* most importantly AES module depends on this feature!
378 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
379 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
381 # Solaris /usr/ccs/bin/as can't handle multiplications
382 # in $self->{label}...
384 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
385 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
387 # Some assemblers insist on signed presentation of 32-bit
388 # offsets, but sign extension is a tricky business in perl...
390 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
392 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
395 # if base register is %rbp or %r13, see if it's possible to
396 # flip base and index registers [for better performance]
397 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
398 $self->{base} =~ /(rbp|r13)/) {
399 $self->{base} = $self->{index}; $self->{index} = $1;
403 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
405 if (defined($self->{index})) {
406 sprintf "%s%s(%s,%%%s,%d)%s",
407 $self->{asterisk},$self->{label},
408 $self->{base}?"%$self->{base}":"",
409 $self->{index},$self->{scale},
412 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label},
413 $self->{base},$self->{opmask};
416 $self->{label} =~ s/\./\$/g;
417 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
418 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
420 my $mnemonic = $self->{opcode}->mnemonic();
421 ($self->{asterisk}) && ($sz="q") ||
422 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
423 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
424 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
425 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
427 $self->{opmask} =~ s/%(k[0-7])/$1/;
429 if (defined($self->{index})) {
430 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz},
431 $self->{label}?"$self->{label}+":"",
432 $self->{index},$self->{scale},
433 $self->{base}?"+$self->{base}":"",
435 } elsif ($self->{base} eq "rip") {
436 sprintf "%s[%s]",$szmap{$sz},$self->{label};
438 sprintf "%s[%s%s]%s", $szmap{$sz},
439 $self->{label}?"$self->{label}+":"",
440 $self->{base},$self->{opmask};
445 { package register; # pick up registers, which start with %.
447 my ($class, $line, $opcode) = @_;
451 # optional * ----vvv--- appears in indirect jmp/call
452 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) {
454 $self->{asterisk} = $1;
456 $self->{opmask} = $3;
457 $opcode->size($self->size());
459 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
467 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
468 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
469 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
470 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
471 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
472 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
473 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
474 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
480 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk},
483 else { $self->{opmask} =~ s/%(k[0-7])/$1/;
484 $self->{value}.$self->{opmask}; }
487 { package label; # pick up labels, which end with :
489 my ($class, $line) = @_;
493 if ($$line =~ /(^[\.\w]+)\:/) {
497 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
499 $self->{value} =~ s/^\.L/$decor/;
507 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
508 if ($win64 && $current_function->{name} eq $self->{value}
509 && $current_function->{abi} eq "svr4") {
511 $func .= " movq %rdi,8(%rsp)\n";
512 $func .= " movq %rsi,16(%rsp)\n";
513 $func .= " movq %rsp,%rax\n";
514 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
515 my $narg = $current_function->{narg};
516 $narg=6 if (!defined($narg));
517 $func .= " movq %rcx,%rdi\n" if ($narg>0);
518 $func .= " movq %rdx,%rsi\n" if ($narg>1);
519 $func .= " movq %r8,%rdx\n" if ($narg>2);
520 $func .= " movq %r9,%rcx\n" if ($narg>3);
521 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
522 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
525 } elsif ($self->{value} ne "$current_function->{name}") {
526 # Make all labels in masm global.
527 $self->{value} .= ":" if ($masm);
528 $self->{value} . ":";
529 } elsif ($win64 && $current_function->{abi} eq "svr4") {
530 my $func = "$current_function->{name}" .
531 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
533 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
534 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
535 $func .= " mov rax,rsp\n";
536 $func .= "${decor}SEH_begin_$current_function->{name}:";
537 $func .= ":" if ($masm);
539 my $narg = $current_function->{narg};
540 $narg=6 if (!defined($narg));
541 $func .= " mov rdi,rcx\n" if ($narg>0);
542 $func .= " mov rsi,rdx\n" if ($narg>1);
543 $func .= " mov rdx,r8\n" if ($narg>2);
544 $func .= " mov rcx,r9\n" if ($narg>3);
545 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
546 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
549 "$current_function->{name}".
550 ($nasm ? ":" : "\tPROC $current_function->{scope}");
554 { package expr; # pick up expressions
556 my ($class, $line, $opcode) = @_;
560 if ($$line =~ /(^[^,]+)/) {
564 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
566 $self->{value} =~ s/\@PLT// if (!$elf);
567 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
568 $self->{value} =~ s/\.L/$decor/g;
569 $self->{opcode} = $opcode;
575 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
576 "NEAR ".$self->{value};
582 { package cfi_directive;
583 # CFI directives annotate instructions that are significant for
584 # stack unwinding procedure compliant with DWARF specification,
585 # see http://dwarfstd.org/. Besides naturally expected for this
586 # script platform-specific filtering function, this module adds
587 # three auxiliary synthetic directives not recognized by [GNU]
590 # - .cfi_push to annotate push instructions in prologue, which
591 # translates to .cfi_adjust_cfa_offset (if needed) and
593 # - .cfi_pop to annotate pop instructions in epilogue, which
594 # translates to .cfi_adjust_cfa_offset (if needed) and
596 # - [and most notably] .cfi_cfa_expression which encodes
597 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as
600 # CFA expressions were introduced in DWARF specification version
601 # 3 and describe how to deduce CFA, Canonical Frame Address. This
602 # becomes handy if your stack frame is variable and you can't
603 # spare register for [previous] frame pointer. Suggested directive
604 # syntax is made-up mix of DWARF operator suffixes [subset of]
605 # and references to registers with optional bias. Following example
606 # describes offloaded *original* stack pointer at specific offset
607 # from *current* stack pointer:
609 # .cfi_cfa_expression %rsp+40,deref,+8
611 # Final +8 has everything to do with the fact that CFA is defined
612 # as reference to top of caller's stack, and on x86_64 call to
613 # subroutine pushes 8-byte return address. In other words original
614 # stack pointer upon entry to a subroutine is 8 bytes off from CFA.
616 # Below constants are taken from "DWARF Expressions" section of the
617 # DWARF specification, section is numbered 7.7 in versions 3 and 4.
618 my %DW_OP_simple = ( # no-arg operators, mapped directly
619 deref => 0x06, dup => 0x12,
620 drop => 0x13, over => 0x14,
621 pick => 0x15, swap => 0x16,
622 rot => 0x17, xderef => 0x18,
624 abs => 0x19, and => 0x1a,
625 div => 0x1b, minus => 0x1c,
626 mod => 0x1d, mul => 0x1e,
627 neg => 0x1f, not => 0x20,
628 or => 0x21, plus => 0x22,
629 shl => 0x24, shr => 0x25,
630 shra => 0x26, xor => 0x27,
633 my %DW_OP_complex = ( # used in specific subroutines
634 constu => 0x10, # uleb128
635 consts => 0x11, # sleb128
636 plus_uconst => 0x23, # uleb128
637 lit0 => 0x30, # add 0-31 to opcode
638 reg0 => 0x50, # add 0-31 to opcode
639 breg0 => 0x70, # add 0-31 to opcole, sleb128
640 regx => 0x90, # uleb28
641 fbreg => 0x91, # sleb128
642 bregx => 0x92, # uleb128, sleb128
643 piece => 0x93, # uleb128
646 # Following constants are defined in x86_64 ABI supplement, for
647 # example available at https://www.uclibc.org/docs/psABI-x86_64.pdf,
648 # see section 3.7 "Stack Unwind Algorithm".
650 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3,
651 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7,
652 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11,
653 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15
656 my ($cfa_reg, $cfa_rsp);
659 # [us]leb128 format is variable-length integer representation base
660 # 2^128, with most significant bit of each byte being 0 denoting
661 # *last* most significant digit. See "Variable Length Data" in the
662 # DWARF specification, numbered 7.6 at least in versions 3 and 4.
664 use integer; # get right shift extend sign
667 my $sign = ($val < 0) ? -1 : 0;
671 push @ret, $val&0x7f;
673 # see if remaining bits are same and equal to most
674 # significant bit of the current digit, if so, it's
676 last if (($val>>6) == $sign);
689 push @ret, $val&0x7f;
691 # see if it's last significant digit...
692 last if (($val >>= 7) == 0);
702 if ($val >= 0 && $val < 32) {
703 return ($DW_OP_complex{lit0}+$val);
705 return ($DW_OP_complex{consts}, sleb128($val));
710 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/);
712 my $reg = $DW_reg_idx{$1};
713 my $off = eval ("0 $2 $3");
715 return (($DW_OP_complex{breg0} + $reg), sleb128($off));
716 # Yes, we use DW_OP_bregX+0 to push register value and not
717 # DW_OP_regX, because latter would require even DW_OP_piece,
718 # which would be a waste under the circumstances. If you have
719 # to use DWP_OP_reg, use "regx:N"...
725 foreach my $token (split(/,\s*/,$line)) {
726 if ($token =~ /^%r/) {
727 push @ret,reg($token);
728 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) {
729 push @ret,reg("$2+$1");
730 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) {
732 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i));
733 } elsif (my $i = 1*eval($token) or $token eq "0") {
734 if ($token =~ /^\+/) {
735 push @ret,$DW_OP_complex{plus_uconst},uleb128($i);
740 push @ret,$DW_OP_simple{$token};
744 # Finally we return DW_CFA_def_cfa_expression, 15, followed by
745 # length of the expression and of course the expression itself.
746 return (15,scalar(@ret),@ret);
749 my ($class, $line) = @_;
753 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) {
756 undef $self->{value};
760 # What is $cfa_rsp? Effectively it's difference between %rsp
761 # value and current CFA, Canonical Frame Address, which is
762 # why it starts with -8. Recall that CFA is top of caller's
764 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; };
765 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0);
766 # .cfi_remember_state directives that are not
767 # matched with .cfi_restore_state are
769 die "unpaired .cfi_remember_state" if (@cfa_stack);
773 && do { $cfa_reg = $$line; last; };
775 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
779 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
782 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
784 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
788 /push/ && do { $dir = undef;
790 if ($cfa_reg eq "%rsp") {
791 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
793 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
796 /pop/ && do { $dir = undef;
798 if ($cfa_reg eq "%rsp") {
799 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
801 $self->{value} .= ".cfi_restore\t$$line";
805 && do { $dir = undef;
806 $self->{value} = ".cfi_escape\t" .
807 join(",", map(sprintf("0x%02x", $_),
808 cfa_expression($$line)));
812 && do { push @cfa_stack, [$cfa_reg, $cfa_rsp];
816 && do { ($cfa_reg, $cfa_rsp) = @{pop @cfa_stack};
821 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
830 return ($elf ? $self->{value} : undef);
833 { package directive; # pick up directives, which start with .
835 my ($class, $line) = @_;
840 # chain-call to cfi_directive
841 $ret = cfi_directive->re($line) and return $ret;
843 if ($$line =~ /^\s*(\.\w+)/) {
847 undef $self->{value};
848 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
851 /\.global|\.globl|\.extern/
852 && do { $globals{$$line} = $prefix . $$line;
853 $$line = $globals{$$line} if ($prefix);
856 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line);
857 if ($type eq "\@function") {
858 undef $current_function;
859 $current_function->{name} = $sym;
860 $current_function->{abi} = "svr4";
861 $current_function->{narg} = $narg;
862 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
863 } elsif ($type eq "\@abi-omnipotent") {
864 undef $current_function;
865 $current_function->{name} = $sym;
866 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
868 $$line =~ s/\@abi\-omnipotent/\@function/;
869 $$line =~ s/\@function.*/\@function/;
872 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
874 $$line = join(",",unpack("C*",$1),0);
878 /\.rva|\.long|\.quad|\.byte/
879 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
880 $$line =~ s/\.L/$decor/g;
886 $self->{value} = $dir . "\t" . $$line;
888 if ($dir =~ /\.extern/) {
889 $self->{value} = ""; # swallow extern
890 } elsif (!$elf && $dir =~ /\.type/) {
892 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
893 (defined($globals{$1})?".scl 2;":".scl 3;") .
894 "\t.type 32;\t.endef"
895 if ($win64 && $$line =~ /([^,]+),\@function/);
896 } elsif (!$elf && $dir =~ /\.size/) {
898 if (defined($current_function)) {
899 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
900 if ($win64 && $current_function->{abi} eq "svr4");
901 undef $current_function;
903 } elsif (!$elf && $dir =~ /\.align/) {
904 $self->{value} = ".p2align\t" . (log($$line)/log(2));
905 } elsif ($dir eq ".section") {
907 # get rid off align option, it's not supported/tolerated
908 # by gcc. openssl project introduced the option as an aid
909 # to deal with nasm/masm assembly.
911 $self->{value} =~ s/(.+)\s+align\s*=.*$/$1/;
913 # $$line may still contains align= option. We do care
914 # about section type here.
916 $current_segment = $$line;
917 $current_segment =~ s/([^\s]+).*$/$1/;
918 if (!$elf && $current_segment eq ".rodata") {
919 if ($flavour eq "macosx") { $self->{value} = ".section\t__DATA,__const"; }
921 if (!$elf && $current_segment eq ".init") {
922 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
923 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
925 } elsif ($dir =~ /\.(text|data)/) {
926 $current_segment=".$1";
927 } elsif ($dir =~ /\.hidden/) {
928 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
929 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
930 } elsif ($dir =~ /\.comm/) {
931 $self->{value} = "$dir\t$prefix$$line";
932 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
933 } elsif ($dir =~ /\.previous/) {
934 $self->{value} = "" if ($flavour eq "mingw64");
940 # non-gas case or nasm/masm
942 /\.text/ && do { my $v=undef;
944 $current_segment = pop(@segment_stack);
945 if (not $current_segment) {
946 push(@segment_stack, ".text");
948 $v="section .text code align=64\n";
949 $current_segment = ".text";
950 push(@segment_stack, $current_segment);
952 $current_segment = pop(@segment_stack);
953 if (not $current_segment) {
954 push(@segment_stack, ".text\$");
956 $v="$current_segment\tENDS\n" if ($current_segment);
957 $current_segment = ".text\$";
958 push(@segment_stack, $current_segment);
959 $v.="$current_segment\tSEGMENT ";
960 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
966 /\.data/ && do { my $v=undef;
968 $v="section .data data align=8\n";
970 $current_segment = pop(@segment_stack);
971 $v="$current_segment\tENDS\n" if ($current_segment);
972 $current_segment = "_DATA";
973 push(@segment_stack, $current_segment);
974 $v.="$current_segment\tSEGMENT";
979 /\.section/ && do { my $v=undef;
982 # $$line may currently contain something like this
984 # align part is optional
987 $align =~ s/(.*)(align\s*=\s*\d+$)/$2/;
988 $$line =~ s/(.*)(\s+align\s*=\s*\d+$)/$1/;
989 $$line = ".CRT\$XCU" if ($$line eq ".init");
990 $$line = ".rdata" if ($$line eq ".rodata");
992 $current_segment = pop(@segment_stack);
993 if (not $current_segment) {
995 # This is a hack which deals with ecp_nistz256-x86_64.pl,
996 # The precomputed curve is stored in the first section
997 # in .asm file. Pushing extra .text section here
998 # allows our poor man's solution to stick to assumption
999 # .text section is always the first.
1001 push(@segment_stack, ".text");
1003 $v="section $$line";
1004 if ($$line=~/\.([prx])data/) {
1005 if ($align =~ /align\s*=\s*(\d+)/) {
1006 $v.= " rdata align=$1" ;
1008 $v.=" rdata align=";
1009 $v.=$1 eq "p"? 4 : 8;
1011 } elsif ($$line=~/\.CRT\$/i) {
1012 $v.=" rdata align=8";
1015 $current_segment = pop(@segment_stack);
1016 if (not $current_segment) {
1018 # same hack for masm to keep ecp_nistz256-x86_64.pl
1021 push(@segment_stack, ".text\$");
1023 $v="$current_segment\tENDS\n" if ($current_segment);
1024 $v.="$$line\tSEGMENT";
1025 if ($$line=~/\.([prx])data/) {
1027 if ($align =~ /align\s*=\s*(\d+)$/) {
1028 $v.=" ALIGN($1)" if ($masm>=$masmref);
1030 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
1032 } elsif ($$line=~/\.CRT\$/i) {
1034 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
1037 $current_segment = $$line;
1038 push(@segment_stack, $$line);
1039 $self->{value} = $v;
1042 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
1043 $self->{value} .= ":NEAR" if ($masm);
1047 && do { $self->{value} = $masm?"PUBLIC":"global";
1048 $self->{value} .= "\t".$$line;
1051 /\.size/ && do { if (defined($current_function)) {
1052 undef $self->{value};
1053 if ($current_function->{abi} eq "svr4") {
1054 $self->{value}="${decor}SEH_end_$current_function->{name}:";
1055 $self->{value}.=":\n" if($masm);
1057 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
1058 undef $current_function;
1062 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
1063 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
1066 /\.(value|long|rva|quad)/
1067 && do { my $sz = substr($1,0,1);
1068 my @arr = split(/,\s*/,$$line);
1069 my $last = pop(@arr);
1070 my $conv = sub { my $var=shift;
1071 $var=~s/^(0b[0-1]+)/oct($1)/eig;
1072 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
1073 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
1074 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
1078 $sz =~ tr/bvlrq/BWDDQ/;
1079 $self->{value} = "\tD$sz\t";
1080 for (@arr) { $self->{value} .= &$conv($_).","; }
1081 $self->{value} .= &$conv($last);
1084 /\.byte/ && do { my @str=split(/,\s*/,$$line);
1085 map(s/(0b[0-1]+)/oct($1)/eig,@str);
1086 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
1088 $self->{value}.="DB\t"
1089 .join(",",@str[0..15])."\n";
1090 foreach (0..15) { shift @str; }
1092 $self->{value}.="DB\t"
1093 .join(",",@str) if (@str);
1096 /\.comm/ && do { my @str=split(/,\s*/,$$line);
1099 $v.="common $prefix@str[0] @str[1]";
1101 $current_segment = pop(@segment_stack);;
1102 $v="$current_segment\tENDS\n" if ($current_segment);
1103 $current_segment = "_DATA";
1104 push(@segment_stack, $current_segment);
1105 $v.="$current_segment\tSEGMENT\n";
1106 $v.="COMM @str[0]:DWORD:".@str[1]/4;
1108 $self->{value} = $v;
1111 /^.previous/ && do {
1114 pop(@segment_stack); # pop ourselves, we don't need to emit END directive
1115 # pop section so we can emit proper .section name.
1116 $current_segment = pop(@segment_stack);
1117 $v="section $current_segment";
1119 # push section/segment to stack. The .previous is currently paired
1120 # with .rodata only. We have to keep extra '.text' on stack for
1121 # situation where there is for example .pdata section 'terminated'
1122 # by new '.text' section.
1124 push(@segment_stack, $current_segment);
1126 $current_segment = pop(@segment_stack);
1127 $v="$current_segment\tENDS\n" if ($current_segment);
1128 $current_segment = pop(@segment_stack);
1129 if ($current_segment =~ /\.text\$/) {
1130 $v.="$current_segment\tSEGMENT ";
1131 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
1133 push(@segment_stack, $current_segment);
1136 $self->{value} = $v;
1151 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
1152 # yet. In order not to be bothered by tracing exact assembler versions,
1153 # but at the same time to provide a bare security minimum of AES-NI, we
1154 # hard-code some instructions. Extensions past AES-NI on the other hand
1155 # are traced by examining assembler version in individual perlasm
1158 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
1159 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
1163 my ($dst,$src,$rex)=@_;
1165 $rex|=0x04 if($dst>=8);
1166 $rex|=0x01 if($src>=8);
1167 push @$opcode,($rex|0x40) if ($rex);
1170 my $movq = sub { # elderly gas can't handle inter-register movq
1173 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
1174 my ($src,$dst)=($1,$2);
1175 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1176 rex(\@opcode,$src,$dst,0x8);
1177 push @opcode,0x0f,0x7e;
1178 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1180 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
1181 my ($src,$dst)=($2,$1);
1182 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1183 rex(\@opcode,$src,$dst,0x8);
1184 push @opcode,0x0f,0x6e;
1185 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1193 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
1198 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
1199 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
1200 rex(\@opcode,$src,$dst);
1201 push @opcode,0x0f,0x3a,0x16;
1202 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1211 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
1216 if ($src =~ /%r([0-9]+)/) { $src = $1; }
1217 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
1218 rex(\@opcode,$dst,$src);
1219 push @opcode,0x0f,0x3a,0x22;
1220 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1229 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1231 rex(\@opcode,$2,$1);
1232 push @opcode,0x0f,0x38,0x00;
1233 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1241 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1243 rex(\@opcode,$3,$2);
1244 push @opcode,0x0f,0x3a,0x0f;
1245 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1253 my $pclmulqdq = sub {
1254 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1256 rex(\@opcode,$3,$2);
1257 push @opcode,0x0f,0x3a,0x44;
1258 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1260 push @opcode,$c=~/^0/?oct($c):$c;
1268 if (shift =~ /%[er](\w+)/) {
1271 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1272 rex(\@opcode,0,$dst,8);
1273 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1281 if (shift =~ /%[er](\w+)/) {
1284 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1285 rex(\@opcode,0,$dst,8);
1286 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1293 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1294 # are using only two instructions hand-code them in order to be excused
1295 # from chasing assembler versions...
1299 my ($dst,$src1,$src2,$rxb)=@_;
1302 $rxb&=~(0x04<<5) if($dst>=8);
1303 $rxb&=~(0x01<<5) if($src1>=8);
1304 $rxb&=~(0x02<<5) if($src2>=8);
1309 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1311 rxb(\@opcode,$3,$2,-1,0x08);
1312 push @opcode,0x78,0xc2;
1313 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1315 push @opcode,$c=~/^0/?oct($c):$c;
1323 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1325 rxb(\@opcode,$3,$2,-1,0x08);
1326 push @opcode,0x78,0xc3;
1327 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1329 push @opcode,$c=~/^0/?oct($c):$c;
1336 # Intel Control-flow Enforcement Technology extension. All functions and
1337 # indirect branch targets will have to start with this instruction...
1339 my $endbranch = sub {
1340 (0xf3,0x0f,0x1e,0xfa);
1343 ########################################################################
1357 while(defined(my $line=<>)) {
1359 $line =~ s|\R$||; # Better chomp
1361 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1362 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1363 $line =~ s|^\s+||; # ... and skip whitespaces in beginning
1364 $line =~ s|\s+$||; # ... and at the end
1366 if (my $label=label->re(\$line)) { print $label->out(); }
1368 if (my $directive=directive->re(\$line)) {
1369 printf "%s",$directive->out();
1370 } elsif (my $opcode=opcode->re(\$line)) {
1371 my $asm = eval("\$".$opcode->mnemonic());
1373 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1374 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1379 ARGUMENT: while (1) {
1382 ($arg=register->re(\$line, $opcode))||
1383 ($arg=const->re(\$line)) ||
1384 ($arg=ea->re(\$line, $opcode)) ||
1385 ($arg=expr->re(\$line, $opcode)) ||
1390 last ARGUMENT if ($line !~ /^,/);
1397 my $sz=$opcode->size();
1400 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1401 @args = map($_->out($sz),@args);
1402 printf "\t%s\t%s",$insn,join(",",@args);
1404 $insn = $opcode->out();
1406 my $arg = $_->out();
1407 # $insn.=$sz compensates for movq, pinsrw, ...
1408 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1409 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1410 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1411 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1413 @args = reverse(@args);
1414 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1415 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1418 printf "\t%s",$opcode->out();
1425 print "$cet_property" if ($cet_property);
1426 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1427 print "END\n" if ($masm);
1429 close STDOUT or die "error closing STDOUT: $!;"
1431 \f#################################################
1432 # Cross-reference x86_64 ABI "card"
1452 # (*) volatile register
1453 # (-) preserved by callee
1454 # (#) Nth argument, volatile
1456 # In Unix terms top of stack is argument transfer area for arguments
1457 # which could not be accommodated in registers. Or in other words 7th
1458 # [integer] argument resides at 8(%rsp) upon function entry point.
1459 # 128 bytes above %rsp constitute a "red zone" which is not touched
1460 # by signal handlers and can be used as temporal storage without
1461 # allocating a frame.
1463 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1464 # which belongs to/can be overwritten by callee. N is the number of
1465 # arguments passed to callee, *but* not less than 4! This means that
1466 # upon function entry point 5th argument resides at 40(%rsp), as well
1467 # as that 32 bytes from 8(%rsp) can always be used as temporal
1468 # storage [without allocating a frame]. One can actually argue that
1469 # one can assume a "red zone" above stack pointer under Win64 as well.
1470 # Point is that at apparently no occasion Windows kernel would alter
1471 # the area above user stack pointer in true asynchronous manner...
1473 # All the above means that if assembler programmer adheres to Unix
1474 # register and stack layout, but disregards the "red zone" existence,
1475 # it's possible to use following prologue and epilogue to "gear" from
1476 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1478 # omnipotent_function:
1481 # movq %rsi,16(%rsp)
1482 # movq %rcx,%rdi ; if 1st argument is actually present
1483 # movq %rdx,%rsi ; if 2nd argument is actually ...
1484 # movq %r8,%rdx ; if 3rd argument is ...
1485 # movq %r9,%rcx ; if 4th argument ...
1486 # movq 40(%rsp),%r8 ; if 5th ...
1487 # movq 48(%rsp),%r9 ; if 6th ...
1492 # movq 16(%rsp),%rsi
1496 \f#################################################
1497 # Win64 SEH, Structured Exception Handling.
1499 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1500 # has undesired side-effect at run-time: if an exception is raised in
1501 # assembler subroutine such as those in question (basically we're
1502 # referring to segmentation violations caused by malformed input
1503 # parameters), the application is briskly terminated without invoking
1504 # any exception handlers, most notably without generating memory dump
1505 # or any user notification whatsoever. This poses a problem. It's
1506 # possible to address it by registering custom language-specific
1507 # handler that would restore processor context to the state at
1508 # subroutine entry point and return "exception is not handled, keep
1509 # unwinding" code. Writing such handler can be a challenge... But it's
1510 # doable, though requires certain coding convention. Consider following
1513 # .type function,@function
1515 # movq %rsp,%rax # copy rsp to volatile register
1516 # pushq %r15 # save non-volatile registers
1520 # subq %rdi,%r11 # prepare [variable] stack frame
1522 # movq %rax,0(%r11) # check for exceptions
1523 # movq %r11,%rsp # allocate [variable] stack frame
1524 # movq %rax,0(%rsp) # save original rsp value
1527 # movq 0(%rsp),%rcx # pull original rsp value
1528 # movq -24(%rcx),%rbp # restore non-volatile registers
1529 # movq -16(%rcx),%rbx
1530 # movq -8(%rcx),%r15
1531 # movq %rcx,%rsp # restore original rsp
1534 # .size function,.-function
1536 # The key is that up to magic_point copy of original rsp value remains
1537 # in chosen volatile register and no non-volatile register, except for
1538 # rsp, is modified. While past magic_point rsp remains constant till
1539 # the very end of the function. In this case custom language-specific
1540 # exception handler would look like this:
1542 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1543 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1544 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1545 # ULONG64 rip = context->Rip;
1547 # if (rip >= magic_point)
1548 # { rsp = (ULONG64 *)context->Rsp;
1549 # if (rip < magic_epilogue)
1550 # { rsp = (ULONG64 *)rsp[0];
1551 # context->Rbp = rsp[-3];
1552 # context->Rbx = rsp[-2];
1553 # context->R15 = rsp[-1];
1556 # context->Rsp = (ULONG64)rsp;
1557 # context->Rdi = rsp[1];
1558 # context->Rsi = rsp[2];
1560 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1561 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1562 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1563 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1564 # return ExceptionContinueSearch;
1567 # It's appropriate to implement this handler in assembler, directly in
1568 # function's module. In order to do that one has to know members'
1569 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1570 # values. Here they are:
1590 # sizeof(CONTEXT) 1232
1591 # DISPATCHER_CONTEXT.ControlPc 0
1592 # DISPATCHER_CONTEXT.ImageBase 8
1593 # DISPATCHER_CONTEXT.FunctionEntry 16
1594 # DISPATCHER_CONTEXT.EstablisherFrame 24
1595 # DISPATCHER_CONTEXT.TargetIp 32
1596 # DISPATCHER_CONTEXT.ContextRecord 40
1597 # DISPATCHER_CONTEXT.LanguageHandler 48
1598 # DISPATCHER_CONTEXT.HandlerData 56
1599 # UNW_FLAG_NHANDLER 0
1600 # ExceptionContinueSearch 1
1602 # In order to tie the handler to the function one has to compose
1603 # couple of structures: one for .xdata segment and one for .pdata.
1605 # UNWIND_INFO structure for .xdata segment would be
1607 # function_unwind_info:
1611 # This structure designates exception handler for a function with
1612 # zero-length prologue, no stack frame or frame register.
1614 # To facilitate composing of .pdata structures, auto-generated "gear"
1615 # prologue copies rsp value to rax and denotes next instruction with
1616 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1617 # styling rule mentioned in the beginning. Position of this label is
1618 # chosen in such manner that possible exceptions raised in the "gear"
1619 # prologue would be accounted to caller and unwound from latter's frame.
1620 # End of function is marked with respective .LSEH_end_{function_name}
1621 # label. To summarize, .pdata segment would contain
1623 # .rva .LSEH_begin_function
1624 # .rva .LSEH_end_function
1625 # .rva function_unwind_info
1627 # Reference to function_unwind_info from .xdata segment is the anchor.
1628 # In case you wonder why references are 32-bit .rvas and not 64-bit
1629 # .quads. References put into these two segments are required to be
1630 # *relative* to the base address of the current binary module, a.k.a.
1631 # image base. No Win64 module, be it .exe or .dll, can be larger than
1632 # 2GB and thus such relative references can be and are accommodated in
1635 # Having reviewed the example function code, one can argue that "movq
1636 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1637 # rax would contain an undefined value. If this "offends" you, use
1638 # another register and refrain from modifying rax till magic_point is
1639 # reached, i.e. as if it was a non-volatile register. If more registers
1640 # are required prior [variable] frame setup is completed, note that
1641 # nobody says that you can have only one "magic point." You can
1642 # "liberate" non-volatile registers by denoting last stack off-load
1643 # instruction and reflecting it in finer grade unwind logic in handler.
1644 # After all, isn't it why it's called *language-specific* handler...
1646 # SE handlers are also involved in unwinding stack when executable is
1647 # profiled or debugged. Profiling implies additional limitations that
1648 # are too subtle to discuss here. For now it's sufficient to say that
1649 # in order to simplify handlers one should either a) offload original
1650 # %rsp to stack (like discussed above); or b) if you have a register to
1651 # spare for frame pointer, choose volatile one.
1653 # (*) Note that we're talking about run-time, not debug-time. Lack of
1654 # unwind information makes debugging hard on both Windows and
1655 # Unix. "Unlike" refers to the fact that on Unix signal handler
1656 # will always be invoked, core dumped and appropriate exit code
1657 # returned to parent (for user notification).