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