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