Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/perlasm/x86_64-xlate.pl

raw
1 #! /usr/bin/env perl
2 # Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
3 # SPDX-License-Identifier: Apache-2.0
4
5
6 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
7 #
8 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
9 # format is way easier to parse. Because it's simpler to "gear" from
10 # Unix ABI to Windows one [see cross-reference "card" at the end of
11 # file]. Because Linux targets were available first...
12 #
13 # In addition the script also "distills" code suitable for GNU
14 # assembler, so that it can be compiled with more rigid assemblers,
15 # such as Solaris /usr/ccs/bin/as.
16 #
17 # This translator is not designed to convert *arbitrary* assembler
18 # code from AT&T format to MASM one. It's designed to convert just
19 # enough to provide for dual-ABI OpenSSL modules development...
20 # There *are* limitations and you might have to modify your assembler
21 # code or this script to achieve the desired result...
22 #
23 # Currently recognized limitations:
24 #
25 # - can't use multiple ops per line;
26 #
27 # Dual-ABI styling rules.
28 #
29 # 1. Adhere to Unix register and stack layout [see cross-reference
30 # ABI "card" at the end for explanation].
31 # 2. Forget about "red zone," stick to more traditional blended
32 # stack frame allocation. If volatile storage is actually required
33 # that is. If not, just leave the stack as is.
34 # 3. Functions tagged with ".type name,@function" get crafted with
35 # unified Win64 prologue and epilogue automatically. If you want
36 # to take care of ABI differences yourself, tag functions as
37 # ".type name,@abi-omnipotent" instead.
38 # 4. To optimize the Win64 prologue you can specify number of input
39 # arguments as ".type name,@function,N." Keep in mind that if N is
40 # larger than 6, then you *have to* write "abi-omnipotent" code,
41 # because >6 cases can't be addressed with unified prologue.
42 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
43 # (sorry about latter).
44 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
45 # required to identify the spots, where to inject Win64 epilogue!
46 # But on the pros, it's then prefixed with rep automatically:-)
47 # 7. Stick to explicit ip-relative addressing. If you have to use
48 # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
49 # Both are recognized and translated to proper Win64 addressing
50 # modes.
51 #
52 # 8. In order to provide for structured exception handling unified
53 # Win64 prologue copies %rsp value to %rax. For further details
54 # see SEH paragraph at the end.
55 # 9. .init segment is allowed to contain calls to functions only.
56 # a. If function accepts more than 4 arguments *and* >4th argument
57 # is declared as non 64-bit value, do clear its upper part.
58 #
59 # TODO(https://crbug.com/boringssl/259): The dual-ABI mechanism described here
60 # does not quite unwind correctly on Windows. The seh_directive logic below has
61 # the start of a new mechanism.
62
63
64 use strict;
65
66 my $flavour = shift;
67 my $output = shift;
68 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
69
70 open STDOUT,">$output" || die "can't open $output: $!"
71 if (defined($output));
72
73 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
74 my $elf=1; $elf=0 if (!$gas);
75 my $apple=0;
76 my $win64=0;
77 my $prefix="";
78 my $decor=".L";
79
80 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
81 my $masm=0;
82 my $PTR=" PTR";
83
84 my $nasmref=2.03;
85 my $nasm=0;
86
87 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
88 # TODO(davidben): Before supporting the
89 # mingw64 perlasm flavour, do away with this
90 # environment variable check.
91 die "mingw64 not supported";
92 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
93 $prefix =~ s|\R$||; # Better chomp
94 }
95 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $apple=1; $prefix="_"; $decor="L\$"; }
96 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
97 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
98 elsif (!$gas) { die "unknown flavour $flavour"; }
99
100 my $current_segment;
101 my $current_function;
102 my %globals;
103
104 { package opcode; # pick up opcodes
105 sub re {
106 my ($class, $line) = @_;
107 my $self = {};
108 my $ret;
109
110 if ($$line =~ /^([a-z][a-z0-9]*)/i) {
111 bless $self,$class;
112 $self->{op} = $1;
113 $ret = $self;
114 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
115
116 undef $self->{sz};
117 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
118 $self->{op} = $1;
119 $self->{sz} = $2;
120 } elsif ($self->{op} =~ /call|jmp/) {
121 $self->{sz} = "";
122 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
123 $self->{sz} = "";
124 } elsif ($self->{op} =~ /^[vk]/) { # VEX or k* such as kmov
125 $self->{sz} = "";
126 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) {
127 $self->{sz} = "";
128 } elsif ($self->{op} =~ /^or([qlwb])$/) {
129 $self->{op} = "or";
130 $self->{sz} = $1;
131 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
132 $self->{op} = $1;
133 $self->{sz} = $2;
134 }
135 }
136 $ret;
137 }
138 sub size {
139 my ($self, $sz) = @_;
140 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
141 $self->{sz};
142 }
143 sub out {
144 my $self = shift;
145 if ($gas) {
146 if ($self->{op} eq "movz") { # movz is pain...
147 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
148 } elsif ($self->{op} =~ /^set/) {
149 "$self->{op}";
150 } elsif ($self->{op} eq "ret") {
151 my $epilogue = "";
152 if ($win64 && $current_function->{abi} eq "svr4") {
153 $epilogue = "movq 8(%rsp),%rdi\n\t" .
154 "movq 16(%rsp),%rsi\n\t";
155 }
156 $epilogue . ".byte 0xf3,0xc3";
157 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
158 ".p2align\t3\n\t.quad";
159 } else {
160 "$self->{op}$self->{sz}";
161 }
162 } else {
163 $self->{op} =~ s/^movz/movzx/;
164 if ($self->{op} eq "ret") {
165 $self->{op} = "";
166 if ($win64 && $current_function->{abi} eq "svr4") {
167 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t".
168 "mov rsi,QWORD$PTR\[16+rsp\]\n\t";
169 }
170 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
171 } elsif ($self->{op} =~ /^(pop|push)f/) {
172 $self->{op} .= $self->{sz};
173 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
174 $self->{op} = "\tDQ";
175 }
176 $self->{op};
177 }
178 }
179 sub mnemonic {
180 my ($self, $op) = @_;
181 $self->{op}=$op if (defined($op));
182 $self->{op};
183 }
184 }
185 { package const; # pick up constants, which start with $
186 sub re {
187 my ($class, $line) = @_;
188 my $self = {};
189 my $ret;
190
191 if ($$line =~ /^\$([^,]+)/) {
192 bless $self, $class;
193 $self->{value} = $1;
194 $ret = $self;
195 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
196 }
197 $ret;
198 }
199 sub out {
200 my $self = shift;
201
202 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
203 if ($gas) {
204 # Solaris /usr/ccs/bin/as can't handle multiplications
205 # in $self->{value}
206 my $value = $self->{value};
207 no warnings; # oct might complain about overflow, ignore here...
208 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
209 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
210 $self->{value} = $value;
211 }
212 sprintf "\$%s",$self->{value};
213 } else {
214 my $value = $self->{value};
215 $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
216 sprintf "%s",$value;
217 }
218 }
219 }
220 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
221
222 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
223 l=>"DWORD$PTR", d=>"DWORD$PTR",
224 q=>"QWORD$PTR", o=>"OWORD$PTR",
225 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR",
226 z=>"ZMMWORD$PTR" ) if (!$gas);
227
228 sub re {
229 my ($class, $line, $opcode) = @_;
230 my $self = {};
231 my $ret;
232
233 # optional * ----vvv--- appears in indirect jmp/call
234 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) {
235 bless $self, $class;
236 $self->{asterisk} = $1;
237 $self->{label} = $2;
238 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
239 $self->{scale} = 1 if (!defined($self->{scale}));
240 $self->{opmask} = $4;
241 $ret = $self;
242 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
243
244 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
245 die if ($opcode->mnemonic() ne "mov");
246 $opcode->mnemonic("lea");
247 }
248 $self->{base} =~ s/^%//;
249 $self->{index} =~ s/^%// if (defined($self->{index}));
250 $self->{opcode} = $opcode;
251 }
252 $ret;
253 }
254 sub size {}
255 sub out {
256 my ($self, $sz) = @_;
257
258 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
259 $self->{label} =~ s/\.L/$decor/g;
260
261 # Silently convert all EAs to 64-bit. This is required for
262 # elder GNU assembler and results in more compact code,
263 # *but* most importantly AES module depends on this feature!
264 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
265 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
266
267 # Solaris /usr/ccs/bin/as can't handle multiplications
268 # in $self->{label}...
269 use integer;
270 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
271 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
272
273 # Some assemblers insist on signed presentation of 32-bit
274 # offsets, but sign extension is a tricky business in perl...
275 if ((1<<31)<<1) {
276 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
277 } else {
278 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
279 }
280
281 # if base register is %rbp or %r13, see if it's possible to
282 # flip base and index registers [for better performance]
283 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
284 $self->{base} =~ /(rbp|r13)/) {
285 $self->{base} = $self->{index}; $self->{index} = $1;
286 }
287
288 if ($gas) {
289 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
290
291 if (defined($self->{index})) {
292 sprintf "%s%s(%s,%%%s,%d)%s",
293 $self->{asterisk},$self->{label},
294 $self->{base}?"%$self->{base}":"",
295 $self->{index},$self->{scale},
296 $self->{opmask};
297 } else {
298 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label},
299 $self->{base},$self->{opmask};
300 }
301 } else {
302 $self->{label} =~ s/\./\$/g;
303 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
304 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
305
306 my $mnemonic = $self->{opcode}->mnemonic();
307 ($self->{asterisk}) && ($sz="q") ||
308 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) ||
309 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
310 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
311 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x");
312
313 $self->{opmask} =~ s/%(k[0-7])/$1/;
314
315 if (defined($self->{index})) {
316 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz},
317 $self->{label}?"$self->{label}+":"",
318 $self->{index},$self->{scale},
319 $self->{base}?"+$self->{base}":"",
320 $self->{opmask};
321 } elsif ($self->{base} eq "rip") {
322 sprintf "%s[%s]",$szmap{$sz},$self->{label};
323 } else {
324 sprintf "%s[%s%s]%s", $szmap{$sz},
325 $self->{label}?"$self->{label}+":"",
326 $self->{base},$self->{opmask};
327 }
328 }
329 }
330 }
331 { package register; # pick up registers, which start with %.
332 sub re {
333 my ($class, $line, $opcode) = @_;
334 my $self = {};
335 my $ret;
336
337 # optional * ----vvv--- appears in indirect jmp/call
338 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) {
339 bless $self,$class;
340 $self->{asterisk} = $1;
341 $self->{value} = $2;
342 $self->{opmask} = $3;
343 $opcode->size($self->size());
344 $ret = $self;
345 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
346 }
347 $ret;
348 }
349 sub size {
350 my $self = shift;
351 my $ret;
352
353 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
354 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
355 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
356 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
357 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
358 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
359 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
360 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
361
362 $ret;
363 }
364 sub out {
365 my $self = shift;
366 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk},
367 $self->{value},
368 $self->{opmask}; }
369 else { $self->{opmask} =~ s/%(k[0-7])/$1/;
370 $self->{value}.$self->{opmask}; }
371 }
372 }
373 { package label; # pick up labels, which end with :
374 sub re {
375 my ($class, $line) = @_;
376 my $self = {};
377 my $ret;
378
379 if ($$line =~ /(^[\.\w]+)\:/) {
380 bless $self,$class;
381 $self->{value} = $1;
382 $ret = $self;
383 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
384
385 $self->{value} =~ s/^\.L/$decor/;
386 }
387 $ret;
388 }
389 sub out {
390 my $self = shift;
391
392 if ($gas) {
393 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
394 if ($win64 && $current_function->{name} eq $self->{value}
395 && $current_function->{abi} eq "svr4") {
396 $func .= "\n";
397 $func .= " movq %rdi,8(%rsp)\n";
398 $func .= " movq %rsi,16(%rsp)\n";
399 $func .= " movq %rsp,%rax\n";
400 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
401 my $narg = $current_function->{narg};
402 $narg=6 if (!defined($narg));
403 $func .= " movq %rcx,%rdi\n" if ($narg>0);
404 $func .= " movq %rdx,%rsi\n" if ($narg>1);
405 $func .= " movq %r8,%rdx\n" if ($narg>2);
406 $func .= " movq %r9,%rcx\n" if ($narg>3);
407 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
408 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
409 }
410 $func;
411 } elsif ($self->{value} ne "$current_function->{name}") {
412 # Make all labels in masm global.
413 $self->{value} .= ":" if ($masm);
414 $self->{value} . ":";
415 } elsif ($win64 && $current_function->{abi} eq "svr4") {
416 my $func = "$current_function->{name}" .
417 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
418 "\n";
419 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n";
420 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n";
421 $func .= " mov rax,rsp\n";
422 $func .= "${decor}SEH_begin_$current_function->{name}:";
423 $func .= ":" if ($masm);
424 $func .= "\n";
425 my $narg = $current_function->{narg};
426 $narg=6 if (!defined($narg));
427 $func .= " mov rdi,rcx\n" if ($narg>0);
428 $func .= " mov rsi,rdx\n" if ($narg>1);
429 $func .= " mov rdx,r8\n" if ($narg>2);
430 $func .= " mov rcx,r9\n" if ($narg>3);
431 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4);
432 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5);
433 $func .= "\n";
434 } else {
435 "$current_function->{name}".
436 ($nasm ? ":" : "\tPROC $current_function->{scope}");
437 }
438 }
439 }
440 { package expr; # pick up expressions
441 sub re {
442 my ($class, $line, $opcode) = @_;
443 my $self = {};
444 my $ret;
445
446 if ($$line =~ /(^[^,]+)/) {
447 bless $self,$class;
448 $self->{value} = $1;
449 $ret = $self;
450 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
451
452 $self->{value} =~ s/\@PLT// if (!$elf);
453 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
454 $self->{value} =~ s/\.L/$decor/g;
455 $self->{opcode} = $opcode;
456 }
457 $ret;
458 }
459 sub out {
460 my $self = shift;
461 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) {
462 "NEAR ".$self->{value};
463 } else {
464 $self->{value};
465 }
466 }
467 }
468 { package cfi_directive;
469 # CFI directives annotate instructions that are significant for
470 # stack unwinding procedure compliant with DWARF specification,
471 # see http://dwarfstd.org/. Besides naturally expected for this
472 # script platform-specific filtering function, this module adds
473 # three auxiliary synthetic directives not recognized by [GNU]
474 # assembler:
475 #
476 # - .cfi_push to annotate push instructions in prologue, which
477 # translates to .cfi_adjust_cfa_offset (if needed) and
478 # .cfi_offset;
479 # - .cfi_pop to annotate pop instructions in epilogue, which
480 # translates to .cfi_adjust_cfa_offset (if needed) and
481 # .cfi_restore;
482 # - [and most notably] .cfi_cfa_expression which encodes
483 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as
484 # byte vector;
485 #
486 # CFA expressions were introduced in DWARF specification version
487 # 3 and describe how to deduce CFA, Canonical Frame Address. This
488 # becomes handy if your stack frame is variable and you can't
489 # spare register for [previous] frame pointer. Suggested directive
490 # syntax is made-up mix of DWARF operator suffixes [subset of]
491 # and references to registers with optional bias. Following example
492 # describes offloaded *original* stack pointer at specific offset
493 # from *current* stack pointer:
494 #
495 # .cfi_cfa_expression %rsp+40,deref,+8
496 #
497 # Final +8 has everything to do with the fact that CFA is defined
498 # as reference to top of caller's stack, and on x86_64 call to
499 # subroutine pushes 8-byte return address. In other words original
500 # stack pointer upon entry to a subroutine is 8 bytes off from CFA.
501
502 # Below constants are taken from "DWARF Expressions" section of the
503 # DWARF specification, section is numbered 7.7 in versions 3 and 4.
504 my %DW_OP_simple = ( # no-arg operators, mapped directly
505 deref => 0x06, dup => 0x12,
506 drop => 0x13, over => 0x14,
507 pick => 0x15, swap => 0x16,
508 rot => 0x17, xderef => 0x18,
509
510 abs => 0x19, and => 0x1a,
511 div => 0x1b, minus => 0x1c,
512 mod => 0x1d, mul => 0x1e,
513 neg => 0x1f, not => 0x20,
514 or => 0x21, plus => 0x22,
515 shl => 0x24, shr => 0x25,
516 shra => 0x26, xor => 0x27,
517 );
518
519 my %DW_OP_complex = ( # used in specific subroutines
520 constu => 0x10, # uleb128
521 consts => 0x11, # sleb128
522 plus_uconst => 0x23, # uleb128
523 lit0 => 0x30, # add 0-31 to opcode
524 reg0 => 0x50, # add 0-31 to opcode
525 breg0 => 0x70, # add 0-31 to opcole, sleb128
526 regx => 0x90, # uleb28
527 fbreg => 0x91, # sleb128
528 bregx => 0x92, # uleb128, sleb128
529 piece => 0x93, # uleb128
530 );
531
532 # Following constants are defined in x86_64 ABI supplement, for
533 # example available at https://www.uclibc.org/docs/psABI-x86_64.pdf,
534 # see section 3.7 "Stack Unwind Algorithm".
535 my %DW_reg_idx = (
536 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3,
537 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7,
538 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11,
539 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15
540 );
541
542 my ($cfa_reg, $cfa_rsp);
543 my @cfa_stack;
544
545 # [us]leb128 format is variable-length integer representation base
546 # 2^128, with most significant bit of each byte being 0 denoting
547 # *last* most significant digit. See "Variable Length Data" in the
548 # DWARF specification, numbered 7.6 at least in versions 3 and 4.
549 sub sleb128 {
550 use integer; # get right shift extend sign
551
552 my $val = shift;
553 my $sign = ($val < 0) ? -1 : 0;
554 my @ret = ();
555
556 while(1) {
557 push @ret, $val&0x7f;
558
559 # see if remaining bits are same and equal to most
560 # significant bit of the current digit, if so, it's
561 # last digit...
562 last if (($val>>6) == $sign);
563
564 @ret[-1] |= 0x80;
565 $val >>= 7;
566 }
567
568 return @ret;
569 }
570 sub uleb128 {
571 my $val = shift;
572 my @ret = ();
573
574 while(1) {
575 push @ret, $val&0x7f;
576
577 # see if it's last significant digit...
578 last if (($val >>= 7) == 0);
579
580 @ret[-1] |= 0x80;
581 }
582
583 return @ret;
584 }
585 sub const {
586 my $val = shift;
587
588 if ($val >= 0 && $val < 32) {
589 return ($DW_OP_complex{lit0}+$val);
590 }
591 return ($DW_OP_complex{consts}, sleb128($val));
592 }
593 sub reg {
594 my $val = shift;
595
596 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/);
597
598 my $reg = $DW_reg_idx{$1};
599 my $off = eval ("0 $2 $3");
600
601 return (($DW_OP_complex{breg0} + $reg), sleb128($off));
602 # Yes, we use DW_OP_bregX+0 to push register value and not
603 # DW_OP_regX, because latter would require even DW_OP_piece,
604 # which would be a waste under the circumstances. If you have
605 # to use DWP_OP_reg, use "regx:N"...
606 }
607 sub cfa_expression {
608 my $line = shift;
609 my @ret;
610
611 foreach my $token (split(/,\s*/,$line)) {
612 if ($token =~ /^%r/) {
613 push @ret,reg($token);
614 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) {
615 push @ret,reg("$2+$1");
616 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) {
617 my $i = 1*eval($2);
618 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i));
619 } elsif (my $i = 1*eval($token) or $token eq "0") {
620 if ($token =~ /^\+/) {
621 push @ret,$DW_OP_complex{plus_uconst},uleb128($i);
622 } else {
623 push @ret,const($i);
624 }
625 } else {
626 push @ret,$DW_OP_simple{$token};
627 }
628 }
629
630 # Finally we return DW_CFA_def_cfa_expression, 15, followed by
631 # length of the expression and of course the expression itself.
632 return (15,scalar(@ret),@ret);
633 }
634 sub re {
635 my ($class, $line) = @_;
636 my $self = {};
637 my $ret;
638
639 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) {
640 bless $self,$class;
641 $ret = $self;
642 undef $self->{value};
643 my $dir = $1;
644
645 SWITCH: for ($dir) {
646 # What is $cfa_rsp? Effectively it's difference between %rsp
647 # value and current CFA, Canonical Frame Address, which is
648 # why it starts with -8. Recall that CFA is top of caller's
649 # stack...
650 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; };
651 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0); last; };
652 /def_cfa_register/
653 && do { $cfa_reg = $$line; last; };
654 /def_cfa_offset/
655 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp");
656 last;
657 };
658 /adjust_cfa_offset/
659 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp");
660 last;
661 };
662 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) {
663 $cfa_reg = $1;
664 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp");
665 }
666 last;
667 };
668 /push/ && do { $dir = undef;
669 $cfa_rsp -= 8;
670 if ($cfa_reg eq "%rsp") {
671 $self->{value} = ".cfi_adjust_cfa_offset\t8\n";
672 }
673 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp";
674 last;
675 };
676 /pop/ && do { $dir = undef;
677 $cfa_rsp += 8;
678 if ($cfa_reg eq "%rsp") {
679 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n";
680 }
681 $self->{value} .= ".cfi_restore\t$$line";
682 last;
683 };
684 /cfa_expression/
685 && do { $dir = undef;
686 $self->{value} = ".cfi_escape\t" .
687 join(",", map(sprintf("0x%02x", $_),
688 cfa_expression($$line)));
689 last;
690 };
691 /remember_state/
692 && do { push @cfa_stack, [$cfa_reg, $cfa_rsp];
693 last;
694 };
695 /restore_state/
696 && do { ($cfa_reg, $cfa_rsp) = @{pop @cfa_stack};
697 last;
698 };
699 }
700
701 $self->{value} = ".cfi_$dir\t$$line" if ($dir);
702
703 $$line = "";
704 }
705
706 return $ret;
707 }
708 sub out {
709 my $self = shift;
710 return ($elf ? $self->{value} : undef);
711 }
712 }
713 { package seh_directive;
714 # This implements directives, like MASM's, for specifying Windows unwind
715 # codes. See https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-170
716 # for details on the Windows unwind mechanism. Unlike MASM's directives, we
717 # have no .seh_endprolog directive. Instead, the last prolog directive is
718 # implicitly the end of the prolog.
719 #
720 # TODO(https://crbug.com/boringssl/259): For now, SEH directives are ignored
721 # on non-Windows platforms. This means functions need to specify both CFI
722 # and SEH directives, often redundantly. Ideally we'd abstract between the
723 # two. E.g., we can synthesize CFI from SEH prologs, but SEH does not
724 # annotate epilogs, so we'd need to combine parts from both. Or we can
725 # restrict ourselves to a subset of CFI and synthesize SEH from CFI.
726 #
727 # Additionally, this only supports @abi-omnipotent functions. It is
728 # incompatible with the automatic calling convention conversion. The main
729 # complication is the current scheme modifies RDI and RSI (non-volatile on
730 # Windows) at the start of the function, and saves them in the parameter
731 # stack area. This can be expressed with .seh_savereg, but .seh_savereg is
732 # only usable late in the prolog. However, unwind information gives enough
733 # information to locate the parameter stack area at any point in the
734 # function, so we can defer conversion or implement other schemes.
735
736 my $UWOP_PUSH_NONVOL = 0;
737 my $UWOP_ALLOC_LARGE = 1;
738 my $UWOP_ALLOC_SMALL = 2;
739 my $UWOP_SET_FPREG = 3;
740 my $UWOP_SAVE_NONVOL = 4;
741 my $UWOP_SAVE_NONVOL_FAR = 5;
742 my $UWOP_SAVE_XMM128 = 8;
743 my $UWOP_SAVE_XMM128_FAR = 9;
744
745 my %UWOP_REG_TO_NUMBER = ("%rax" => 0, "%rcx" => 1, "%rdx" => 2, "%rbx" => 3,
746 "%rsp" => 4, "%rbp" => 5, "%rsi" => 6, "%rdi" => 7,
747 map(("%r$_" => $_), (8..15)));
748 my %UWOP_NUMBER_TO_REG = reverse %UWOP_REG_TO_NUMBER;
749
750 # The contents of the pdata and xdata sections so far.
751 my ($xdata, $pdata) = ("", "");
752
753 my %info;
754
755 my $next_label = 0;
756 my $current_label_func = "";
757
758 # _new_unwind_label allocates a new label, unique to the file.
759 sub _new_unwind_label {
760 my ($name) = (@_);
761 # Labels only need to be unique, but to make diffs easier to read, scope
762 # them all under the current function.
763 my $func = $current_function->{name};
764 if ($func ne $current_label_func) {
765 $current_label_func = $func;
766 $next_label = 0;
767 }
768
769 my $num = $next_label++;
770 return ".LSEH_${name}_${func}_${num}";
771 }
772
773 sub _check_in_proc {
774 die "Missing .seh_startproc directive" unless %info;
775 }
776
777 sub _check_not_in_proc {
778 die "Missing .seh_endproc directive" if %info;
779 }
780
781 sub _startproc {
782 _check_not_in_proc();
783 if ($current_function->{abi} eq "svr4") {
784 die "SEH directives can only be used with \@abi-omnipotent";
785 }
786
787 my $info_label = _new_unwind_label("info");
788 my $start_label = _new_unwind_label("begin");
789 %info = (
790 # info_label is the label of the function's entry in .xdata.
791 info_label => $info_label,
792 # start_label is the start of the function.
793 start_label => $start_label,
794 # endprolog is the label of the last unwind code in the function.
795 endprolog => $start_label,
796 # unwind_codes contains the textual representation of the
797 # unwind codes in the function so far.
798 unwind_codes => "",
799 # num_codes is the number of 16-bit words in unwind_codes.
800 num_codes => 0,
801 # frame_reg is the number of the frame register, or zero if
802 # there is none.
803 frame_reg => 0,
804 # frame_offset is the offset into the fixed part of the stack that
805 # the frame register points into.
806 frame_offset => 0,
807 # has_offset is whether directives taking an offset have
808 # been used. This is used to check that such directives
809 # come after the fixed portion of the stack frame is established.
810 has_offset => 0,
811 # has_nonpushreg is whether directives other than
812 # .seh_pushreg have been used. This is used to check that
813 # .seh_pushreg directives are first.
814 has_nonpushreg => 0,
815 );
816 return $start_label;
817 }
818
819 sub _add_unwind_code {
820 my ($op, $value, @extra) = @_;
821 _check_in_proc();
822 if ($op != $UWOP_PUSH_NONVOL) {
823 $info{has_nonpushreg} = 1;
824 } elsif ($info{has_nonpushreg}) {
825 die ".seh_pushreg directives must appear first in the prolog";
826 }
827
828 my $label = _new_unwind_label("prolog");
829 # Encode an UNWIND_CODE structure. See
830 # https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-170#struct-unwind_code
831 my $encoded = $op | ($value << 4);
832 my $codes = <<____;
833 .byte $label-$info{start_label}
834 .byte $encoded
835 ____
836 # Some opcodes need additional values to encode themselves.
837 foreach (@extra) {
838 $codes .= "\t.value\t$_\n";
839 }
840
841 $info{num_codes} += 1 + scalar(@extra);
842 # Unwind codes are listed in reverse order.
843 $info{unwind_codes} = $codes . $info{unwind_codes};
844 # Track the label of the last unwind code. It implicitly is the end of
845 # the prolog. MASM has an endprolog directive, but it seems to be
846 # unnecessary.
847 $info{endprolog} = $label;
848 return $label;
849 }
850
851 sub _updating_fixed_allocation {
852 _check_in_proc();
853 if ($info{frame_reg} != 0) {
854 # Windows documentation does not explicitly forbid .seh_allocstack
855 # after .seh_setframe, but it appears to have no effect. Offsets are
856 # still relative to the fixed allocation when the frame register was
857 # established.
858 die "fixed allocation may not be increased after .seh_setframe";
859 }
860 if ($info{has_offset}) {
861 # Windows documentation does not explicitly forbid .seh_savereg
862 # before .seh_allocstack, but it does not work very well. Offsets
863 # are relative to the top of the final fixed allocation, not where
864 # RSP currently is.
865 die "directives with an offset must come after the fixed allocation is established.";
866 }
867 }
868
869 sub _endproc {
870 _check_in_proc();
871 if ($info{num_codes} == 0) {
872 # If a Windows function has no directives (i.e. it doesn't touch the
873 # stack), it is a leaf function and is not expected to appear in
874 # .pdata or .xdata.
875 die ".seh_endproc found with no unwind codes";
876 }
877
878 my $end_label = _new_unwind_label("end");
879 # Encode a RUNTIME_FUNCTION. See
880 # https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-170#struct-runtime_function
881 $pdata .= <<____;
882 .rva $info{start_label}
883 .rva $end_label
884 .rva $info{info_label}
885
886 ____
887
888 # Encode an UNWIND_INFO. See
889 # https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-170#struct-unwind_info
890 my $frame_encoded = $info{frame_reg} | (($info{frame_offset} / 16) << 4);
891 $xdata .= <<____;
892 .align 4
893 $info{info_label}:
894 .byte 1 # version 1, no flags
895 .byte $info{endprolog}-$info{start_label}
896 .byte $info{num_codes}
897 .byte $frame_encoded
898 $info{unwind_codes}
899 ____
900
901 %info = ();
902 return $end_label;
903 }
904
905 sub re {
906 my ($class, $line) = @_;
907 if ($$line =~ s/^\s*\.seh_(\w+)\s*//) {
908 my $dir = $1;
909 if (!$win64) {
910 $$line = "";
911 return;
912 }
913
914 my $label;
915 SWITCH: for ($dir) {
916 /^startproc$/ && do {
917 $label = _startproc();
918 last;
919 };
920 /^pushreg$/ && do {
921 $$line =~ /^(%\w+)\s*$/ or die "could not parse .seh_$dir";
922 my $reg_num = $UWOP_REG_TO_NUMBER{$1} or die "unknown register $1";
923 _updating_fixed_allocation();
924 $label = _add_unwind_code($UWOP_PUSH_NONVOL, $reg_num);
925 last;
926 };
927 /^allocstack$/ && do {
928 my $num = eval($$line);
929 if ($num <= 0 || $num % 8 != 0) {
930 die "invalid stack allocation: $num";
931 }
932 _updating_fixed_allocation();
933 if ($num <= 128) {
934 $label = _add_unwind_code($UWOP_ALLOC_SMALL, ($num - 8) / 8);
935 } elsif ($num < 512 * 1024) {
936 $label = _add_unwind_code($UWOP_ALLOC_LARGE, 0, $num / 8);
937 } elsif ($num < 4 * 1024 * 1024 * 1024) {
938 $label = _add_unwind_code($UWOP_ALLOC_LARGE, 1, $num >> 16, $num & 0xffff);
939 } else {
940 die "stack allocation too large: $num"
941 }
942 last;
943 };
944 /^setframe$/ && do {
945 if ($info{frame_reg} != 0) {
946 die "duplicate .seh_setframe directive";
947 }
948 if ($info{has_offset}) {
949 die "directives with with an offset must come after .seh_setframe.";
950 }
951 $$line =~ /(%\w+)\s*,\s*(.+)/ or die "could not parse .seh_$dir";
952 my $reg_num = $UWOP_REG_TO_NUMBER{$1} or die "unknown register $1";
953 my $offset = eval($2);
954 if ($offset < 0 || $offset % 16 != 0 || $offset > 240) {
955 die "invalid offset: $offset";
956 }
957 $info{frame_reg} = $reg_num;
958 $info{frame_offset} = $offset;
959 $label = _add_unwind_code($UWOP_SET_FPREG, 0);
960 last;
961 };
962 /^savereg$/ && do {
963 $$line =~ /(%\w+)\s*,\s*(.+)/ or die "could not parse .seh_$dir";
964 my $reg_num = $UWOP_REG_TO_NUMBER{$1} or die "unknown register $1";
965 my $offset = eval($2);
966 if ($offset < 0 || $offset % 8 != 0) {
967 die "invalid offset: $offset";
968 }
969 if ($offset < 8 * 65536) {
970 $label = _add_unwind_code($UWOP_SAVE_NONVOL, $reg_num, $offset / 8);
971 } else {
972 $label = _add_unwind_code($UWOP_SAVE_NONVOL_FAR, $reg_num, $offset >> 16, $offset & 0xffff);
973 }
974 $info{has_offset} = 1;
975 last;
976 };
977 /^savexmm128$/ && do {
978 $$line =~ /%xmm(\d+)\s*,\s*(.+)/ or die "could not parse .seh_$dir";
979 my $reg_num = $1;
980 my $offset = eval($2);
981 if ($offset < 0 || $offset % 16 != 0) {
982 die "invalid offset: $offset";
983 }
984 if ($offset < 16 * 65536) {
985 $label = _add_unwind_code($UWOP_SAVE_XMM128, $reg_num, $offset / 16);
986 } else {
987 $label = _add_unwind_code($UWOP_SAVE_XMM128_FAR, $reg_num, $offset >> 16, $offset & 0xffff);
988 }
989 $info{has_offset} = 1;
990 last;
991 };
992 /^endproc$/ && do {
993 $label = _endproc();
994 last;
995 };
996 die "unknown SEH directive .seh_$dir";
997 }
998
999 # All SEH directives compile to labels inline. The other data is
1000 # emitted later.
1001 $$line = "";
1002 $label .= ":";
1003 return label->re(\$label);
1004 }
1005 }
1006
1007 sub pdata_and_xdata {
1008 return "" unless $win64;
1009
1010 my $ret = "";
1011 if ($pdata ne "") {
1012 $ret .= <<____;
1013 .section .pdata
1014 .align 4
1015 $pdata
1016 ____
1017 }
1018 if ($xdata ne "") {
1019 $ret .= <<____;
1020 .section .xdata
1021 $xdata
1022 ____
1023 }
1024 return $ret;
1025 }
1026 }
1027 { package directive; # pick up directives, which start with .
1028 my %sections;
1029 sub nasm_section {
1030 my ($name, $qualifiers) = @_;
1031 my $ret = "section\t$name";
1032 if (exists $sections{$name}) {
1033 # Work around https://bugzilla.nasm.us/show_bug.cgi?id=3392701. Only
1034 # emit section qualifiers the first time a section is referenced.
1035 # For all subsequent references, require the qualifiers match and
1036 # omit them.
1037 #
1038 # See also https://crbug.com/1422018 and b/270643835.
1039 my $old = $sections{$name};
1040 die "Inconsistent qualifiers: $qualifiers vs $old" if ($qualifiers ne "" && $qualifiers ne $old);
1041 } else {
1042 $sections{$name} = $qualifiers;
1043 if ($qualifiers ne "") {
1044 $ret .= " $qualifiers";
1045 }
1046 }
1047 return $ret;
1048 }
1049 sub re {
1050 my ($class, $line) = @_;
1051 my $self = {};
1052 my $ret;
1053 my $dir;
1054
1055 # chain-call to cfi_directive and seh_directive.
1056 $ret = cfi_directive->re($line) and return $ret;
1057 $ret = seh_directive->re($line) and return $ret;
1058
1059 if ($$line =~ /^\s*(\.\w+)/) {
1060 bless $self,$class;
1061 $dir = $1;
1062 $ret = $self;
1063 undef $self->{value};
1064 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//;
1065
1066 SWITCH: for ($dir) {
1067 /\.global|\.globl|\.extern/
1068 && do { $globals{$$line} = $prefix . $$line;
1069 $$line = $globals{$$line} if ($prefix);
1070 last;
1071 };
1072 /\.type/ && do { my ($sym,$type,$narg) = split(/\s*,\s*/,$$line);
1073 if ($type eq "\@function") {
1074 undef $current_function;
1075 $current_function->{name} = $sym;
1076 $current_function->{abi} = "svr4";
1077 $current_function->{narg} = $narg;
1078 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
1079 } elsif ($type eq "\@abi-omnipotent") {
1080 undef $current_function;
1081 $current_function->{name} = $sym;
1082 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
1083 }
1084 $$line =~ s/\@abi\-omnipotent/\@function/;
1085 $$line =~ s/\@function.*/\@function/;
1086 last;
1087 };
1088 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) {
1089 $dir = ".byte";
1090 $$line = join(",",unpack("C*",$1),0);
1091 }
1092 last;
1093 };
1094 /\.rva|\.long|\.quad|\.byte/
1095 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
1096 $$line =~ s/\.L/$decor/g;
1097 last;
1098 };
1099 }
1100
1101 if ($gas) {
1102 $self->{value} = $dir . "\t" . $$line;
1103
1104 if ($dir =~ /\.extern/) {
1105 if ($flavour eq "elf") {
1106 $self->{value} .= "\n.hidden $$line";
1107 } else {
1108 $self->{value} = "";
1109 }
1110 } elsif (!$elf && $dir =~ /\.type/) {
1111 $self->{value} = "";
1112 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
1113 (defined($globals{$1})?".scl 2;":".scl 3;") .
1114 "\t.type 32;\t.endef"
1115 if ($win64 && $$line =~ /([^,]+),\@function/);
1116 } elsif (!$elf && $dir =~ /\.size/) {
1117 $self->{value} = "";
1118 if (defined($current_function)) {
1119 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
1120 if ($win64 && $current_function->{abi} eq "svr4");
1121 undef $current_function;
1122 }
1123 } elsif (!$elf && $dir =~ /\.align/) {
1124 $self->{value} = ".p2align\t" . (log($$line)/log(2));
1125 } elsif ($dir eq ".section") {
1126 $current_segment=$$line;
1127 if (!$elf && $current_segment eq ".rodata") {
1128 if ($flavour eq "macosx") { $self->{value} = ".section\t__DATA,__const"; }
1129 }
1130 if (!$elf && $current_segment eq ".init") {
1131 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
1132 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
1133 }
1134 } elsif ($dir =~ /\.(text|data)/) {
1135 $current_segment=".$1";
1136 } elsif ($dir =~ /\.global|\.globl|\.extern/) {
1137 if ($flavour eq "macosx") {
1138 $self->{value} .= "\n.private_extern $$line";
1139 } else {
1140 $self->{value} .= "\n.hidden $$line";
1141 }
1142 } elsif ($dir =~ /\.hidden/) {
1143 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
1144 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
1145 } elsif ($dir =~ /\.comm/) {
1146 $self->{value} = "$dir\t$prefix$$line";
1147 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
1148 }
1149 $$line = "";
1150 return $self;
1151 }
1152
1153 # non-gas case or nasm/masm
1154 SWITCH: for ($dir) {
1155 /\.text/ && do { my $v=undef;
1156 if ($nasm) {
1157 $v=nasm_section(".text", "code align=64")."\n";
1158 } else {
1159 $v="$current_segment\tENDS\n" if ($current_segment);
1160 $current_segment = ".text\$";
1161 $v.="$current_segment\tSEGMENT ";
1162 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
1163 $v.=" 'CODE'";
1164 }
1165 $self->{value} = $v;
1166 last;
1167 };
1168 /\.data/ && do { my $v=undef;
1169 if ($nasm) {
1170 $v=nasm_section(".data", "data align=8")."\n";
1171 } else {
1172 $v="$current_segment\tENDS\n" if ($current_segment);
1173 $current_segment = "_DATA";
1174 $v.="$current_segment\tSEGMENT";
1175 }
1176 $self->{value} = $v;
1177 last;
1178 };
1179 /\.section/ && do { my $v=undef;
1180 $$line =~ s/([^,]*).*/$1/;
1181 $$line = ".CRT\$XCU" if ($$line eq ".init");
1182 $$line = ".rdata" if ($$line eq ".rodata");
1183 if ($nasm) {
1184 my $qualifiers = "";
1185 if ($$line=~/\.([prx])data/) {
1186 $qualifiers = "rdata align=";
1187 $qualifiers .= ($1 eq "p" || $1 eq "x")? 4 : 8;
1188 } elsif ($$line=~/\.CRT\$/i) {
1189 $qualifiers = "rdata align=8";
1190 }
1191 $v = nasm_section($$line, $qualifiers);
1192 } else {
1193 $v="$current_segment\tENDS\n" if ($current_segment);
1194 $v.="$$line\tSEGMENT";
1195 if ($$line=~/\.([prx])data/) {
1196 $v.=" READONLY";
1197 $v.=" ALIGN(".(($1 eq "p" || $1 eq "x") ? 4 : 8).")" if ($masm>=$masmref);
1198 } elsif ($$line=~/\.CRT\$/i) {
1199 $v.=" READONLY ";
1200 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
1201 }
1202 }
1203 $current_segment = $$line;
1204 $self->{value} = $v;
1205 last;
1206 };
1207 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
1208 $self->{value} .= ":NEAR" if ($masm);
1209 last;
1210 };
1211 /\.globl|.global/
1212 && do { $self->{value} = $masm?"PUBLIC":"global";
1213 $self->{value} .= "\t".$$line;
1214 last;
1215 };
1216 /\.size/ && do { if (defined($current_function)) {
1217 undef $self->{value};
1218 if ($current_function->{abi} eq "svr4") {
1219 $self->{value}="${decor}SEH_end_$current_function->{name}:";
1220 $self->{value}.=":\n" if($masm);
1221 }
1222 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
1223 undef $current_function;
1224 }
1225 last;
1226 };
1227 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
1228 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
1229 last;
1230 };
1231 /\.(value|long|rva|quad)/
1232 && do { my $sz = substr($1,0,1);
1233 my @arr = split(/,\s*/,$$line);
1234 my $last = pop(@arr);
1235 my $conv = sub { my $var=shift;
1236 $var=~s/^(0b[0-1]+)/oct($1)/eig;
1237 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
1238 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
1239 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
1240 $var;
1241 };
1242
1243 $sz =~ tr/bvlrq/BWDDQ/;
1244 $self->{value} = "\tD$sz\t";
1245 for (@arr) { $self->{value} .= &$conv($_).","; }
1246 $self->{value} .= &$conv($last);
1247 last;
1248 };
1249 /\.byte/ && do { my @str=split(/,\s*/,$$line);
1250 map(s/(0b[0-1]+)/oct($1)/eig,@str);
1251 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
1252 while ($#str>15) {
1253 $self->{value}.="\tDB\t"
1254 .join(",",@str[0..15])."\n";
1255 foreach (0..15) { shift @str; }
1256 }
1257 $self->{value}.="\tDB\t"
1258 .join(",",@str) if (@str);
1259 last;
1260 };
1261 /\.comm/ && do { my @str=split(/,\s*/,$$line);
1262 my $v=undef;
1263 if ($nasm) {
1264 $v.="common $prefix@str[0] @str[1]";
1265 } else {
1266 $v="$current_segment\tENDS\n" if ($current_segment);
1267 $current_segment = "_DATA";
1268 $v.="$current_segment\tSEGMENT\n";
1269 $v.="COMM @str[0]:DWORD:".@str[1]/4;
1270 }
1271 $self->{value} = $v;
1272 last;
1273 };
1274 }
1275 $$line = "";
1276 }
1277
1278 $ret;
1279 }
1280 sub out {
1281 my $self = shift;
1282 $self->{value};
1283 }
1284 }
1285
1286 # Upon initial x86_64 introduction SSE>2 extensions were not introduced
1287 # yet. In order not to be bothered by tracing exact assembler versions,
1288 # but at the same time to provide a bare security minimum of AES-NI, we
1289 # hard-code some instructions. Extensions past AES-NI on the other hand
1290 # are traced by examining assembler version in individual perlasm
1291 # modules...
1292
1293 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
1294 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
1295
1296 sub rex {
1297 my $opcode=shift;
1298 my ($dst,$src,$rex)=@_;
1299
1300 $rex|=0x04 if($dst>=8);
1301 $rex|=0x01 if($src>=8);
1302 push @$opcode,($rex|0x40) if ($rex);
1303 }
1304
1305 my $movq = sub { # elderly gas can't handle inter-register movq
1306 my $arg = shift;
1307 my @opcode=(0x66);
1308 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
1309 my ($src,$dst)=($1,$2);
1310 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1311 rex(\@opcode,$src,$dst,0x8);
1312 push @opcode,0x0f,0x7e;
1313 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1314 @opcode;
1315 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
1316 my ($src,$dst)=($2,$1);
1317 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1318 rex(\@opcode,$src,$dst,0x8);
1319 push @opcode,0x0f,0x6e;
1320 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1321 @opcode;
1322 } else {
1323 ();
1324 }
1325 };
1326
1327 my $pextrd = sub {
1328 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
1329 my @opcode=(0x66);
1330 my $imm=$1;
1331 my $src=$2;
1332 my $dst=$3;
1333 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
1334 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
1335 rex(\@opcode,$src,$dst);
1336 push @opcode,0x0f,0x3a,0x16;
1337 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
1338 push @opcode,$imm;
1339 @opcode;
1340 } else {
1341 ();
1342 }
1343 };
1344
1345 my $pinsrd = sub {
1346 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
1347 my @opcode=(0x66);
1348 my $imm=$1;
1349 my $src=$2;
1350 my $dst=$3;
1351 if ($src =~ /%r([0-9]+)/) { $src = $1; }
1352 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
1353 rex(\@opcode,$dst,$src);
1354 push @opcode,0x0f,0x3a,0x22;
1355 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
1356 push @opcode,$imm;
1357 @opcode;
1358 } else {
1359 ();
1360 }
1361 };
1362
1363 my $pshufb = sub {
1364 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1365 my @opcode=(0x66);
1366 rex(\@opcode,$2,$1);
1367 push @opcode,0x0f,0x38,0x00;
1368 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
1369 @opcode;
1370 } else {
1371 ();
1372 }
1373 };
1374
1375 my $palignr = sub {
1376 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1377 my @opcode=(0x66);
1378 rex(\@opcode,$3,$2);
1379 push @opcode,0x0f,0x3a,0x0f;
1380 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1381 push @opcode,$1;
1382 @opcode;
1383 } else {
1384 ();
1385 }
1386 };
1387
1388 my $pclmulqdq = sub {
1389 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1390 my @opcode=(0x66);
1391 rex(\@opcode,$3,$2);
1392 push @opcode,0x0f,0x3a,0x44;
1393 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1394 my $c=$1;
1395 push @opcode,$c=~/^0/?oct($c):$c;
1396 @opcode;
1397 } else {
1398 ();
1399 }
1400 };
1401
1402 my $rdrand = sub {
1403 if (shift =~ /%[er](\w+)/) {
1404 my @opcode=();
1405 my $dst=$1;
1406 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1407 rex(\@opcode,0,$dst,8);
1408 push @opcode,0x0f,0xc7,0xf0|($dst&7);
1409 @opcode;
1410 } else {
1411 ();
1412 }
1413 };
1414
1415 my $rdseed = sub {
1416 if (shift =~ /%[er](\w+)/) {
1417 my @opcode=();
1418 my $dst=$1;
1419 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
1420 rex(\@opcode,0,$dst,8);
1421 push @opcode,0x0f,0xc7,0xf8|($dst&7);
1422 @opcode;
1423 } else {
1424 ();
1425 }
1426 };
1427
1428 # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
1429 # are using only two instructions hand-code them in order to be excused
1430 # from chasing assembler versions...
1431
1432 sub rxb {
1433 my $opcode=shift;
1434 my ($dst,$src1,$src2,$rxb)=@_;
1435
1436 $rxb|=0x7<<5;
1437 $rxb&=~(0x04<<5) if($dst>=8);
1438 $rxb&=~(0x01<<5) if($src1>=8);
1439 $rxb&=~(0x02<<5) if($src2>=8);
1440 push @$opcode,$rxb;
1441 }
1442
1443 my $vprotd = sub {
1444 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1445 my @opcode=(0x8f);
1446 rxb(\@opcode,$3,$2,-1,0x08);
1447 push @opcode,0x78,0xc2;
1448 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1449 my $c=$1;
1450 push @opcode,$c=~/^0/?oct($c):$c;
1451 @opcode;
1452 } else {
1453 ();
1454 }
1455 };
1456
1457 my $vprotq = sub {
1458 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
1459 my @opcode=(0x8f);
1460 rxb(\@opcode,$3,$2,-1,0x08);
1461 push @opcode,0x78,0xc3;
1462 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
1463 my $c=$1;
1464 push @opcode,$c=~/^0/?oct($c):$c;
1465 @opcode;
1466 } else {
1467 ();
1468 }
1469 };
1470
1471 # Intel Control-flow Enforcement Technology extension. All functions and
1472 # indirect branch targets will have to start with this instruction...
1473
1474 my $endbranch = sub {
1475 (0xf3,0x0f,0x1e,0xfa);
1476 };
1477
1478 ########################################################################
1479
1480 {
1481 my $comment = "//";
1482 $comment = ";" if ($masm || $nasm);
1483 print <<___;
1484 $comment This file is generated from a similarly-named Perl script in the BoringSSL
1485 $comment source tree. Do not edit by hand.
1486
1487 ___
1488 }
1489
1490 if ($nasm) {
1491 die "unknown target" unless ($win64);
1492 print <<___;
1493 \%ifidn __OUTPUT_FORMAT__, win64
1494 default rel
1495 \%define XMMWORD
1496 \%define YMMWORD
1497 \%define ZMMWORD
1498 \%define _CET_ENDBR
1499
1500 \%include "openssl/boringssl_prefix_symbols_nasm.inc"
1501 ___
1502 } elsif ($masm) {
1503 print <<___;
1504 OPTION DOTNAME
1505 ___
1506 }
1507
1508 if ($gas) {
1509 my $target;
1510 if ($elf) {
1511 # The "elf" target is really ELF with SysV ABI, but every ELF platform
1512 # uses the SysV ABI.
1513 $target = "defined(__ELF__)";
1514 } elsif ($apple) {
1515 $target = "defined(__APPLE__)";
1516 } else {
1517 die "unknown target: $flavour";
1518 }
1519 print <<___;
1520 #include <openssl/asm_base.h>
1521
1522 #if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && $target
1523 ___
1524 }
1525
1526 sub process_line {
1527 my $line = shift;
1528 $line =~ s|\R$||; # Better chomp
1529
1530 if ($nasm) {
1531 $line =~ s|^#ifdef |%ifdef |;
1532 $line =~ s|^#ifndef |%ifndef |;
1533 $line =~ s|^#endif|%endif|;
1534 $line =~ s|[#!].*$||; # get rid of asm-style comments...
1535 } else {
1536 # Get rid of asm-style comments but not preprocessor directives. The
1537 # former are identified by having a letter after the '#' and starting in
1538 # the first column.
1539 $line =~ s|!.*$||;
1540 $line =~ s|(?<=.)#.*$||;
1541 $line =~ s|^#([^a-z].*)?$||;
1542 }
1543
1544 $line =~ s|/\*.*\*/||; # ... and C-style comments...
1545 $line =~ s|^\s+||; # ... and skip white spaces in beginning
1546 $line =~ s|\s+$||; # ... and at the end
1547
1548 if (my $label=label->re(\$line)) { print $label->out(); }
1549
1550 if (my $directive=directive->re(\$line)) {
1551 printf "%s",$directive->out();
1552 } elsif (my $opcode=opcode->re(\$line)) {
1553 my $asm = eval("\$".$opcode->mnemonic());
1554
1555 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
1556 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
1557 next;
1558 }
1559
1560 my @args;
1561 ARGUMENT: while (1) {
1562 my $arg;
1563
1564 ($arg=register->re(\$line, $opcode))||
1565 ($arg=const->re(\$line)) ||
1566 ($arg=ea->re(\$line, $opcode)) ||
1567 ($arg=expr->re(\$line, $opcode)) ||
1568 last ARGUMENT;
1569
1570 push @args,$arg;
1571
1572 last ARGUMENT if ($line !~ /^,/);
1573
1574 $line =~ s/^,\s*//;
1575 } # ARGUMENT:
1576
1577 if ($#args>=0) {
1578 my $insn;
1579 my $sz=$opcode->size();
1580
1581 if ($gas) {
1582 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
1583 @args = map($_->out($sz),@args);
1584 printf "\t%s\t%s",$insn,join(",",@args);
1585 } else {
1586 $insn = $opcode->out();
1587 foreach (@args) {
1588 my $arg = $_->out();
1589 # $insn.=$sz compensates for movq, pinsrw, ...
1590 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
1591 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
1592 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
1593 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
1594 }
1595 @args = reverse(@args);
1596 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
1597 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
1598 }
1599 } else {
1600 printf "\t%s",$opcode->out();
1601 }
1602 }
1603
1604 print $line,"\n";
1605 }
1606
1607 while(defined(my $line=<>)) {
1608 process_line($line);
1609 }
1610 foreach my $line (split(/\n/, seh_directive->pdata_and_xdata())) {
1611 process_line($line);
1612 }
1613
1614 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
1615 if ($masm) {
1616 print "END\n";
1617 } elsif ($gas) {
1618 print "#endif\n";
1619 } elsif ($nasm) {
1620 print <<___;
1621 \%else
1622 ; Work around https://bugzilla.nasm.us/show_bug.cgi?id=3392738
1623 ret
1624 \%endif
1625 ___
1626 } else {
1627 die "unknown assembler";
1628 }
1629
1630 close STDOUT or die "error closing STDOUT: $!";
1631
1632 #################################################
1633 # Cross-reference x86_64 ABI "card"
1634 #
1635 # Unix Win64
1636 # %rax * *
1637 # %rbx - -
1638 # %rcx #4 #1
1639 # %rdx #3 #2
1640 # %rsi #2 -
1641 # %rdi #1 -
1642 # %rbp - -
1643 # %rsp - -
1644 # %r8 #5 #3
1645 # %r9 #6 #4
1646 # %r10 * *
1647 # %r11 * *
1648 # %r12 - -
1649 # %r13 - -
1650 # %r14 - -
1651 # %r15 - -
1652 #
1653 # (*) volatile register
1654 # (-) preserved by callee
1655 # (#) Nth argument, volatile
1656 #
1657 # In Unix terms top of stack is argument transfer area for arguments
1658 # which could not be accommodated in registers. Or in other words 7th
1659 # [integer] argument resides at 8(%rsp) upon function entry point.
1660 # 128 bytes above %rsp constitute a "red zone" which is not touched
1661 # by signal handlers and can be used as temporal storage without
1662 # allocating a frame.
1663 #
1664 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
1665 # which belongs to/can be overwritten by callee. N is the number of
1666 # arguments passed to callee, *but* not less than 4! This means that
1667 # upon function entry point 5th argument resides at 40(%rsp), as well
1668 # as that 32 bytes from 8(%rsp) can always be used as temporal
1669 # storage [without allocating a frame]. One can actually argue that
1670 # one can assume a "red zone" above stack pointer under Win64 as well.
1671 # Point is that at apparently no occasion Windows kernel would alter
1672 # the area above user stack pointer in true asynchronous manner...
1673 #
1674 # All the above means that if assembler programmer adheres to Unix
1675 # register and stack layout, but disregards the "red zone" existence,
1676 # it's possible to use following prologue and epilogue to "gear" from
1677 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
1678 #
1679 # omnipotent_function:
1680 # ifdef WIN64
1681 # movq %rdi,8(%rsp)
1682 # movq %rsi,16(%rsp)
1683 # movq %rcx,%rdi ; if 1st argument is actually present
1684 # movq %rdx,%rsi ; if 2nd argument is actually ...
1685 # movq %r8,%rdx ; if 3rd argument is ...
1686 # movq %r9,%rcx ; if 4th argument ...
1687 # movq 40(%rsp),%r8 ; if 5th ...
1688 # movq 48(%rsp),%r9 ; if 6th ...
1689 # endif
1690 # ...
1691 # ifdef WIN64
1692 # movq 8(%rsp),%rdi
1693 # movq 16(%rsp),%rsi
1694 # endif
1695 # ret
1696 #
1697 #################################################
1698 # Win64 SEH, Structured Exception Handling.
1699 #
1700 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
1701 # has undesired side-effect at run-time: if an exception is raised in
1702 # assembler subroutine such as those in question (basically we're
1703 # referring to segmentation violations caused by malformed input
1704 # parameters), the application is briskly terminated without invoking
1705 # any exception handlers, most notably without generating memory dump
1706 # or any user notification whatsoever. This poses a problem. It's
1707 # possible to address it by registering custom language-specific
1708 # handler that would restore processor context to the state at
1709 # subroutine entry point and return "exception is not handled, keep
1710 # unwinding" code. Writing such handler can be a challenge... But it's
1711 # doable, though requires certain coding convention. Consider following
1712 # snippet:
1713 #
1714 # .type function,@function
1715 # function:
1716 # movq %rsp,%rax # copy rsp to volatile register
1717 # pushq %r15 # save non-volatile registers
1718 # pushq %rbx
1719 # pushq %rbp
1720 # movq %rsp,%r11
1721 # subq %rdi,%r11 # prepare [variable] stack frame
1722 # andq $-64,%r11
1723 # movq %rax,0(%r11) # check for exceptions
1724 # movq %r11,%rsp # allocate [variable] stack frame
1725 # movq %rax,0(%rsp) # save original rsp value
1726 # magic_point:
1727 # ...
1728 # movq 0(%rsp),%rcx # pull original rsp value
1729 # movq -24(%rcx),%rbp # restore non-volatile registers
1730 # movq -16(%rcx),%rbx
1731 # movq -8(%rcx),%r15
1732 # movq %rcx,%rsp # restore original rsp
1733 # magic_epilogue:
1734 # ret
1735 # .size function,.-function
1736 #
1737 # The key is that up to magic_point copy of original rsp value remains
1738 # in chosen volatile register and no non-volatile register, except for
1739 # rsp, is modified. While past magic_point rsp remains constant till
1740 # the very end of the function. In this case custom language-specific
1741 # exception handler would look like this:
1742 #
1743 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1744 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1745 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1746 # ULONG64 rip = context->Rip;
1747 #
1748 # if (rip >= magic_point)
1749 # { rsp = (ULONG64 *)context->Rsp;
1750 # if (rip < magic_epilogue)
1751 # { rsp = (ULONG64 *)rsp[0];
1752 # context->Rbp = rsp[-3];
1753 # context->Rbx = rsp[-2];
1754 # context->R15 = rsp[-1];
1755 # }
1756 # }
1757 # context->Rsp = (ULONG64)rsp;
1758 # context->Rdi = rsp[1];
1759 # context->Rsi = rsp[2];
1760 #
1761 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1762 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1763 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1764 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1765 # return ExceptionContinueSearch;
1766 # }
1767 #
1768 # It's appropriate to implement this handler in assembler, directly in
1769 # function's module. In order to do that one has to know members'
1770 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1771 # values. Here they are:
1772 #
1773 # CONTEXT.Rax 120
1774 # CONTEXT.Rcx 128
1775 # CONTEXT.Rdx 136
1776 # CONTEXT.Rbx 144
1777 # CONTEXT.Rsp 152
1778 # CONTEXT.Rbp 160
1779 # CONTEXT.Rsi 168
1780 # CONTEXT.Rdi 176
1781 # CONTEXT.R8 184
1782 # CONTEXT.R9 192
1783 # CONTEXT.R10 200
1784 # CONTEXT.R11 208
1785 # CONTEXT.R12 216
1786 # CONTEXT.R13 224
1787 # CONTEXT.R14 232
1788 # CONTEXT.R15 240
1789 # CONTEXT.Rip 248
1790 # CONTEXT.Xmm6 512
1791 # sizeof(CONTEXT) 1232
1792 # DISPATCHER_CONTEXT.ControlPc 0
1793 # DISPATCHER_CONTEXT.ImageBase 8
1794 # DISPATCHER_CONTEXT.FunctionEntry 16
1795 # DISPATCHER_CONTEXT.EstablisherFrame 24
1796 # DISPATCHER_CONTEXT.TargetIp 32
1797 # DISPATCHER_CONTEXT.ContextRecord 40
1798 # DISPATCHER_CONTEXT.LanguageHandler 48
1799 # DISPATCHER_CONTEXT.HandlerData 56
1800 # UNW_FLAG_NHANDLER 0
1801 # ExceptionContinueSearch 1
1802 #
1803 # In order to tie the handler to the function one has to compose
1804 # couple of structures: one for .xdata segment and one for .pdata.
1805 #
1806 # UNWIND_INFO structure for .xdata segment would be
1807 #
1808 # function_unwind_info:
1809 # .byte 9,0,0,0
1810 # .rva handler
1811 #
1812 # This structure designates exception handler for a function with
1813 # zero-length prologue, no stack frame or frame register.
1814 #
1815 # To facilitate composing of .pdata structures, auto-generated "gear"
1816 # prologue copies rsp value to rax and denotes next instruction with
1817 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1818 # styling rule mentioned in the beginning. Position of this label is
1819 # chosen in such manner that possible exceptions raised in the "gear"
1820 # prologue would be accounted to caller and unwound from latter's frame.
1821 # End of function is marked with respective .LSEH_end_{function_name}
1822 # label. To summarize, .pdata segment would contain
1823 #
1824 # .rva .LSEH_begin_function
1825 # .rva .LSEH_end_function
1826 # .rva function_unwind_info
1827 #
1828 # Reference to function_unwind_info from .xdata segment is the anchor.
1829 # In case you wonder why references are 32-bit .rvas and not 64-bit
1830 # .quads. References put into these two segments are required to be
1831 # *relative* to the base address of the current binary module, a.k.a.
1832 # image base. No Win64 module, be it .exe or .dll, can be larger than
1833 # 2GB and thus such relative references can be and are accommodated in
1834 # 32 bits.
1835 #
1836 # Having reviewed the example function code, one can argue that "movq
1837 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1838 # rax would contain an undefined value. If this "offends" you, use
1839 # another register and refrain from modifying rax till magic_point is
1840 # reached, i.e. as if it was a non-volatile register. If more registers
1841 # are required prior [variable] frame setup is completed, note that
1842 # nobody says that you can have only one "magic point." You can
1843 # "liberate" non-volatile registers by denoting last stack off-load
1844 # instruction and reflecting it in finer grade unwind logic in handler.
1845 # After all, isn't it why it's called *language-specific* handler...
1846 #
1847 # SE handlers are also involved in unwinding stack when executable is
1848 # profiled or debugged. Profiling implies additional limitations that
1849 # are too subtle to discuss here. For now it's sufficient to say that
1850 # in order to simplify handlers one should either a) offload original
1851 # %rsp to stack (like discussed above); or b) if you have a register to
1852 # spare for frame pointer, choose volatile one.
1853 #
1854 # (*) Note that we're talking about run-time, not debug-time. Lack of
1855 # unwind information makes debugging hard on both Windows and
1856 # Unix. "Unlike" refers to the fact that on Unix signal handler
1857 # will always be invoked, core dumped and appropriate exit code
1858 # returned to parent (for user notification).