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