x86_64-xlate.pl revision 312826
1#!/usr/bin/env perl
2
3# Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
4#
5# Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6# format is way easier to parse. Because it's simpler to "gear" from
7# Unix ABI to Windows one [see cross-reference "card" at the end of
8# file]. Because Linux targets were available first...
9#
10# In addition the script also "distills" code suitable for GNU
11# assembler, so that it can be compiled with more rigid assemblers,
12# such as Solaris /usr/ccs/bin/as.
13#
14# This translator is not designed to convert *arbitrary* assembler
15# code from AT&T format to MASM one. It's designed to convert just
16# enough to provide for dual-ABI OpenSSL modules development...
17# There *are* limitations and you might have to modify your assembler
18# code or this script to achieve the desired result...
19#
20# Currently recognized limitations:
21#
22# - can't use multiple ops per line;
23#
24# Dual-ABI styling rules.
25#
26# 1. Adhere to Unix register and stack layout [see cross-reference
27#    ABI "card" at the end for explanation].
28# 2. Forget about "red zone," stick to more traditional blended
29#    stack frame allocation. If volatile storage is actually required
30#    that is. If not, just leave the stack as is.
31# 3. Functions tagged with ".type name,@function" get crafted with
32#    unified Win64 prologue and epilogue automatically. If you want
33#    to take care of ABI differences yourself, tag functions as
34#    ".type name,@abi-omnipotent" instead.
35# 4. To optimize the Win64 prologue you can specify number of input
36#    arguments as ".type name,@function,N." Keep in mind that if N is
37#    larger than 6, then you *have to* write "abi-omnipotent" code,
38#    because >6 cases can't be addressed with unified prologue.
39# 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
40#    (sorry about latter).
41# 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
42#    required to identify the spots, where to inject Win64 epilogue!
43#    But on the pros, it's then prefixed with rep automatically:-)
44# 7. Stick to explicit ip-relative addressing. If you have to use
45#    GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
46#    Both are recognized and translated to proper Win64 addressing
47#    modes. To support legacy code a synthetic directive, .picmeup,
48#    is implemented. It puts address of the *next* instruction into
49#    target register, e.g.:
50#
51#		.picmeup	%rax
52#		lea		.Label-.(%rax),%rax
53#
54# 8. In order to provide for structured exception handling unified
55#    Win64 prologue copies %rsp value to %rax. For further details
56#    see SEH paragraph at the end.
57# 9. .init segment is allowed to contain calls to functions only.
58# a. If function accepts more than 4 arguments *and* >4th argument
59#    is declared as non 64-bit value, do clear its upper part.
60
61my $flavour = shift;
62my $output  = shift;
63if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
64
65open STDOUT,">$output" || die "can't open $output: $!"
66	if (defined($output));
67
68my $gas=1;	$gas=0 if ($output =~ /\.asm$/);
69my $elf=1;	$elf=0 if (!$gas);
70my $win64=0;
71my $prefix="";
72my $decor=".L";
73
74my $masmref=8 + 50727*2**-32;	# 8.00.50727 shipped with VS2005
75my $masm=0;
76my $PTR=" PTR";
77
78my $nasmref=2.03;
79my $nasm=0;
80
81if    ($flavour eq "mingw64")	{ $gas=1; $elf=0; $win64=1;
82				  $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
83				  chomp($prefix);
84				}
85elsif ($flavour eq "macosx")	{ $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
86elsif ($flavour eq "masm")	{ $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
87elsif ($flavour eq "nasm")	{ $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
88elsif (!$gas)
89{   if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
90    {	$nasm = $1 + $2*0.01; $PTR="";  }
91    elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
92    {	$masm = $1 + $2*2**-16 + $4*2**-32;   }
93    die "no assembler found on %PATH" if (!($nasm || $masm));
94    $win64=1;
95    $elf=0;
96    $decor="\$L\$";
97}
98
99my $current_segment;
100my $current_function;
101my %globals;
102
103{ package opcode;	# pick up opcodes
104    sub re {
105	my	$self = shift;	# single instance in enough...
106	local	*line = shift;
107	undef	$ret;
108
109	if ($line =~ /^([a-z][a-z0-9]*)/i) {
110	    $self->{op} = $1;
111	    $ret = $self;
112	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
113
114	    undef $self->{sz};
115	    if ($self->{op} =~ /^(movz)x?([bw]).*/) {	# movz is pain...
116		$self->{op} = $1;
117		$self->{sz} = $2;
118	    } elsif ($self->{op} =~ /call|jmp/) {
119		$self->{sz} = "";
120	    } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
121		$self->{sz} = "";
122	    } elsif ($self->{op} =~ /^v/) { # VEX
123		$self->{sz} = "";
124	    } elsif ($self->{op} =~ /mov[dq]/ && $line =~ /%xmm/) {
125		$self->{sz} = "";
126	    } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
127		$self->{op} = $1;
128		$self->{sz} = $2;
129	    }
130	}
131	$ret;
132    }
133    sub size {
134	my $self = shift;
135	my $sz   = shift;
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=shift;
177	my $op=shift;
178	$self->{op}=$op if (defined($op));
179	$self->{op};
180    }
181}
182{ package const;	# pick up constants, which start with $
183    sub re {
184	my	$self = shift;	# single instance in enough...
185	local	*line = shift;
186	undef	$ret;
187
188	if ($line =~ /^\$([^,]+)/) {
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	    $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
204	    if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) {
205		$self->{value} = $value;
206	    }
207	    sprintf "\$%s",$self->{value};
208	} else {
209	    $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
210	    sprintf "%s",$self->{value};
211	}
212    }
213}
214{ package ea;		# pick up effective addresses: expr(%reg,%reg,scale)
215    sub re {
216	my	$self = shift;	# single instance in enough...
217	local	*line = shift;
218	undef	$ret;
219
220	# optional * ---vvv--- appears in indirect jmp/call
221	if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
222	    $self->{asterisk} = $1;
223	    $self->{label} = $2;
224	    ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
225	    $self->{scale} = 1 if (!defined($self->{scale}));
226	    $ret = $self;
227	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
228
229	    if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
230		die if (opcode->mnemonic() ne "mov");
231		opcode->mnemonic("lea");
232	    }
233	    $self->{base}  =~ s/^%//;
234	    $self->{index} =~ s/^%// if (defined($self->{index}));
235	}
236	$ret;
237    }
238    sub size {}
239    sub out {
240    	my $self = shift;
241	my $sz = shift;
242
243	$self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
244	$self->{label} =~ s/\.L/$decor/g;
245
246	# Silently convert all EAs to 64-bit. This is required for
247	# elder GNU assembler and results in more compact code,
248	# *but* most importantly AES module depends on this feature!
249	$self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
250	$self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
251
252	# Solaris /usr/ccs/bin/as can't handle multiplications
253	# in $self->{label}...
254	use integer;
255	$self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
256	$self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
257
258	# Some assemblers insist on signed presentation of 32-bit
259	# offsets, but sign extension is a tricky business in perl...
260	if ((1<<31)<<1) {
261	    $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
262	} else {
263	    $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
264	}
265
266	if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
267	    $self->{base} =~ /(rbp|r13)/) {
268		$self->{base} = $self->{index}; $self->{index} = $1;
269	}
270
271	if ($gas) {
272	    $self->{label} =~ s/^___imp_/__imp__/   if ($flavour eq "mingw64");
273
274	    if (defined($self->{index})) {
275		sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
276					$self->{label},
277					$self->{base}?"%$self->{base}":"",
278					$self->{index},$self->{scale};
279	    } else {
280		sprintf "%s%s(%%%s)",	$self->{asterisk},$self->{label},$self->{base};
281	    }
282	} else {
283	    %szmap = (	b=>"BYTE$PTR",  w=>"WORD$PTR",
284			l=>"DWORD$PTR", d=>"DWORD$PTR",
285	    		q=>"QWORD$PTR", o=>"OWORD$PTR",
286			x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
287
288	    $self->{label} =~ s/\./\$/g;
289	    $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
290	    $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
291
292	    ($self->{asterisk})					&& ($sz="q") ||
293	    (opcode->mnemonic() =~ /^v?mov([qd])$/)		&& ($sz=$1)  ||
294	    (opcode->mnemonic() =~ /^v?pinsr([qdwb])$/)		&& ($sz=$1)  ||
295	    (opcode->mnemonic() =~ /^vpbroadcast([qdwb])$/)	&& ($sz=$1)  ||
296	    (opcode->mnemonic() =~ /^vinsert[fi]128$/)		&& ($sz="x");
297
298	    if (defined($self->{index})) {
299		sprintf "%s[%s%s*%d%s]",$szmap{$sz},
300					$self->{label}?"$self->{label}+":"",
301					$self->{index},$self->{scale},
302					$self->{base}?"+$self->{base}":"";
303	    } elsif ($self->{base} eq "rip") {
304		sprintf "%s[%s]",$szmap{$sz},$self->{label};
305	    } else {
306		sprintf "%s[%s%s]",$szmap{$sz},
307					$self->{label}?"$self->{label}+":"",
308					$self->{base};
309	    }
310	}
311    }
312}
313{ package register;	# pick up registers, which start with %.
314    sub re {
315	my	$class = shift;	# muliple instances...
316	my	$self = {};
317	local	*line = shift;
318	undef	$ret;
319
320	# optional * ---vvv--- appears in indirect jmp/call
321	if ($line =~ /^(\*?)%(\w+)/) {
322	    bless $self,$class;
323	    $self->{asterisk} = $1;
324	    $self->{value} = $2;
325	    $ret = $self;
326	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
327	}
328	$ret;
329    }
330    sub size {
331	my	$self = shift;
332	undef	$ret;
333
334	if    ($self->{value} =~ /^r[\d]+b$/i)	{ $ret="b"; }
335	elsif ($self->{value} =~ /^r[\d]+w$/i)	{ $ret="w"; }
336	elsif ($self->{value} =~ /^r[\d]+d$/i)	{ $ret="l"; }
337	elsif ($self->{value} =~ /^r[\w]+$/i)	{ $ret="q"; }
338	elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
339	elsif ($self->{value} =~ /^[\w]{2}l$/i)	{ $ret="b"; }
340	elsif ($self->{value} =~ /^[\w]{2}$/i)	{ $ret="w"; }
341	elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
342
343	$ret;
344    }
345    sub out {
346    	my $self = shift;
347	if ($gas)	{ sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
348	else		{ $self->{value}; }
349    }
350}
351{ package label;	# pick up labels, which end with :
352    sub re {
353	my	$self = shift;	# single instance is enough...
354	local	*line = shift;
355	undef	$ret;
356
357	if ($line =~ /(^[\.\w]+)\:/) {
358	    $self->{value} = $1;
359	    $ret = $self;
360	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
361
362	    $self->{value} =~ s/^\.L/$decor/;
363	}
364	$ret;
365    }
366    sub out {
367	my $self = shift;
368
369	if ($gas) {
370	    my $func = ($globals{$self->{value}} or $self->{value}) . ":";
371	    if ($win64	&&
372			$current_function->{name} eq $self->{value} &&
373			$current_function->{abi} eq "svr4") {
374		$func .= "\n";
375		$func .= "	movq	%rdi,8(%rsp)\n";
376		$func .= "	movq	%rsi,16(%rsp)\n";
377		$func .= "	movq	%rsp,%rax\n";
378		$func .= "${decor}SEH_begin_$current_function->{name}:\n";
379		my $narg = $current_function->{narg};
380		$narg=6 if (!defined($narg));
381		$func .= "	movq	%rcx,%rdi\n" if ($narg>0);
382		$func .= "	movq	%rdx,%rsi\n" if ($narg>1);
383		$func .= "	movq	%r8,%rdx\n"  if ($narg>2);
384		$func .= "	movq	%r9,%rcx\n"  if ($narg>3);
385		$func .= "	movq	40(%rsp),%r8\n" if ($narg>4);
386		$func .= "	movq	48(%rsp),%r9\n" if ($narg>5);
387	    }
388	    $func;
389	} elsif ($self->{value} ne "$current_function->{name}") {
390	    $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
391	    $self->{value} . ":";
392	} elsif ($win64 && $current_function->{abi} eq "svr4") {
393	    my $func =	"$current_function->{name}" .
394			($nasm ? ":" : "\tPROC $current_function->{scope}") .
395			"\n";
396	    $func .= "	mov	QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
397	    $func .= "	mov	QWORD${PTR}[16+rsp],rsi\n";
398	    $func .= "	mov	rax,rsp\n";
399	    $func .= "${decor}SEH_begin_$current_function->{name}:";
400	    $func .= ":" if ($masm);
401	    $func .= "\n";
402	    my $narg = $current_function->{narg};
403	    $narg=6 if (!defined($narg));
404	    $func .= "	mov	rdi,rcx\n" if ($narg>0);
405	    $func .= "	mov	rsi,rdx\n" if ($narg>1);
406	    $func .= "	mov	rdx,r8\n"  if ($narg>2);
407	    $func .= "	mov	rcx,r9\n"  if ($narg>3);
408	    $func .= "	mov	r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
409	    $func .= "	mov	r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
410	    $func .= "\n";
411	} else {
412	   "$current_function->{name}".
413			($nasm ? ":" : "\tPROC $current_function->{scope}");
414	}
415    }
416}
417{ package expr;		# pick up expressioins
418    sub re {
419	my	$self = shift;	# single instance is enough...
420	local	*line = shift;
421	undef	$ret;
422
423	if ($line =~ /(^[^,]+)/) {
424	    $self->{value} = $1;
425	    $ret = $self;
426	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
427
428	    $self->{value} =~ s/\@PLT// if (!$elf);
429	    $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
430	    $self->{value} =~ s/\.L/$decor/g;
431	}
432	$ret;
433    }
434    sub out {
435	my $self = shift;
436	if ($nasm && opcode->mnemonic()=~m/^j(?![re]cxz)/) {
437	    "NEAR ".$self->{value};
438	} else {
439	    $self->{value};
440	}
441    }
442}
443{ package directive;	# pick up directives, which start with .
444    sub re {
445	my	$self = shift;	# single instance is enough...
446	local	*line = shift;
447	undef	$ret;
448	my	$dir;
449	my	%opcode =	# lea 2f-1f(%rip),%dst; 1: nop; 2:
450		(	"%rax"=>0x01058d48,	"%rcx"=>0x010d8d48,
451			"%rdx"=>0x01158d48,	"%rbx"=>0x011d8d48,
452			"%rsp"=>0x01258d48,	"%rbp"=>0x012d8d48,
453			"%rsi"=>0x01358d48,	"%rdi"=>0x013d8d48,
454			"%r8" =>0x01058d4c,	"%r9" =>0x010d8d4c,
455			"%r10"=>0x01158d4c,	"%r11"=>0x011d8d4c,
456			"%r12"=>0x01258d4c,	"%r13"=>0x012d8d4c,
457			"%r14"=>0x01358d4c,	"%r15"=>0x013d8d4c	);
458
459	if ($line =~ /^\s*(\.\w+)/) {
460	    $dir = $1;
461	    $ret = $self;
462	    undef $self->{value};
463	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
464
465	    SWITCH: for ($dir) {
466		/\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
467			    		$dir="\t.long";
468					$line=sprintf "0x%x,0x90000000",$opcode{$1};
469				    }
470				    last;
471				  };
472		/\.global|\.globl|\.extern/
473			    && do { $globals{$line} = $prefix . $line;
474				    $line = $globals{$line} if ($prefix);
475				    last;
476				  };
477		/\.type/    && do { ($sym,$type,$narg) = split(',',$line);
478				    if ($type eq "\@function") {
479					undef $current_function;
480					$current_function->{name} = $sym;
481					$current_function->{abi}  = "svr4";
482					$current_function->{narg} = $narg;
483					$current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
484				    } elsif ($type eq "\@abi-omnipotent") {
485					undef $current_function;
486					$current_function->{name} = $sym;
487					$current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
488				    }
489				    $line =~ s/\@abi\-omnipotent/\@function/;
490				    $line =~ s/\@function.*/\@function/;
491				    last;
492				  };
493		/\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
494					$dir  = ".byte";
495					$line = join(",",unpack("C*",$1),0);
496				    }
497				    last;
498				  };
499		/\.rva|\.long|\.quad/
500			    && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
501				    $line =~ s/\.L/$decor/g;
502				    last;
503				  };
504	    }
505
506	    if ($gas) {
507		$self->{value} = $dir . "\t" . $line;
508
509		if ($dir =~ /\.extern/) {
510		    $self->{value} = ""; # swallow extern
511		} elsif (!$elf && $dir =~ /\.type/) {
512		    $self->{value} = "";
513		    $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
514				(defined($globals{$1})?".scl 2;":".scl 3;") .
515				"\t.type 32;\t.endef"
516				if ($win64 && $line =~ /([^,]+),\@function/);
517		} elsif (!$elf && $dir =~ /\.size/) {
518		    $self->{value} = "";
519		    if (defined($current_function)) {
520			$self->{value} .= "${decor}SEH_end_$current_function->{name}:"
521				if ($win64 && $current_function->{abi} eq "svr4");
522			undef $current_function;
523		    }
524		} elsif (!$elf && $dir =~ /\.align/) {
525		    $self->{value} = ".p2align\t" . (log($line)/log(2));
526		} elsif ($dir eq ".section") {
527		    $current_segment=$line;
528		    if (!$elf && $current_segment eq ".init") {
529			if	($flavour eq "macosx")	{ $self->{value} = ".mod_init_func"; }
530			elsif	($flavour eq "mingw64")	{ $self->{value} = ".section\t.ctors"; }
531		    }
532		} elsif ($dir =~ /\.(text|data)/) {
533		    $current_segment=".$1";
534		} elsif ($dir =~ /\.hidden/) {
535		    if    ($flavour eq "macosx")  { $self->{value} = ".private_extern\t$prefix$line"; }
536		    elsif ($flavour eq "mingw64") { $self->{value} = ""; }
537		} elsif ($dir =~ /\.comm/) {
538		    $self->{value} = "$dir\t$prefix$line";
539		    $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
540		}
541		$line = "";
542		return $self;
543	    }
544
545	    # non-gas case or nasm/masm
546	    SWITCH: for ($dir) {
547		/\.text/    && do { my $v=undef;
548				    if ($nasm) {
549					$v="section	.text code align=64\n";
550				    } else {
551					$v="$current_segment\tENDS\n" if ($current_segment);
552					$current_segment = ".text\$";
553					$v.="$current_segment\tSEGMENT ";
554					$v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
555					$v.=" 'CODE'";
556				    }
557				    $self->{value} = $v;
558				    last;
559				  };
560		/\.data/    && do { my $v=undef;
561				    if ($nasm) {
562					$v="section	.data data align=8\n";
563				    } else {
564					$v="$current_segment\tENDS\n" if ($current_segment);
565					$current_segment = "_DATA";
566					$v.="$current_segment\tSEGMENT";
567				    }
568				    $self->{value} = $v;
569				    last;
570				  };
571		/\.section/ && do { my $v=undef;
572				    $line =~ s/([^,]*).*/$1/;
573				    $line = ".CRT\$XCU" if ($line eq ".init");
574				    if ($nasm) {
575					$v="section	$line";
576					if ($line=~/\.([px])data/) {
577					    $v.=" rdata align=";
578					    $v.=$1 eq "p"? 4 : 8;
579					} elsif ($line=~/\.CRT\$/i) {
580					    $v.=" rdata align=8";
581					}
582				    } else {
583					$v="$current_segment\tENDS\n" if ($current_segment);
584					$v.="$line\tSEGMENT";
585					if ($line=~/\.([px])data/) {
586					    $v.=" READONLY";
587					    $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
588					} elsif ($line=~/\.CRT\$/i) {
589					    $v.=" READONLY ";
590					    $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
591					}
592				    }
593				    $current_segment = $line;
594				    $self->{value} = $v;
595				    last;
596				  };
597		/\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
598				    $self->{value} .= ":NEAR" if ($masm);
599				    last;
600				  };
601		/\.globl|.global/
602			    && do { $self->{value}  = $masm?"PUBLIC":"global";
603				    $self->{value} .= "\t".$line;
604				    last;
605				  };
606		/\.size/    && do { if (defined($current_function)) {
607					undef $self->{value};
608					if ($current_function->{abi} eq "svr4") {
609					    $self->{value}="${decor}SEH_end_$current_function->{name}:";
610					    $self->{value}.=":\n" if($masm);
611					}
612					$self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
613					undef $current_function;
614				    }
615				    last;
616				  };
617		/\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
618		/\.(value|long|rva|quad)/
619			    && do { my $sz  = substr($1,0,1);
620				    my @arr = split(/,\s*/,$line);
621				    my $last = pop(@arr);
622				    my $conv = sub  {	my $var=shift;
623							$var=~s/^(0b[0-1]+)/oct($1)/eig;
624							$var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
625							if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
626							{ $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
627							$var;
628						    };
629
630				    $sz =~ tr/bvlrq/BWDDQ/;
631				    $self->{value} = "\tD$sz\t";
632				    for (@arr) { $self->{value} .= &$conv($_).","; }
633				    $self->{value} .= &$conv($last);
634				    last;
635				  };
636		/\.byte/    && do { my @str=split(/,\s*/,$line);
637				    map(s/(0b[0-1]+)/oct($1)/eig,@str);
638				    map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
639				    while ($#str>15) {
640					$self->{value}.="DB\t"
641						.join(",",@str[0..15])."\n";
642					foreach (0..15) { shift @str; }
643				    }
644				    $self->{value}.="DB\t"
645						.join(",",@str) if (@str);
646				    last;
647				  };
648		/\.comm/    && do { my @str=split(/,\s*/,$line);
649				    my $v=undef;
650				    if ($nasm) {
651					$v.="common	$prefix@str[0] @str[1]";
652				    } else {
653					$v="$current_segment\tENDS\n" if ($current_segment);
654					$current_segment = "_DATA";
655					$v.="$current_segment\tSEGMENT\n";
656					$v.="COMM	@str[0]:DWORD:".@str[1]/4;
657				    }
658				    $self->{value} = $v;
659				    last;
660				  };
661	    }
662	    $line = "";
663	}
664
665	$ret;
666    }
667    sub out {
668	my $self = shift;
669	$self->{value};
670    }
671}
672
673sub rex {
674 local *opcode=shift;
675 my ($dst,$src,$rex)=@_;
676
677   $rex|=0x04 if($dst>=8);
678   $rex|=0x01 if($src>=8);
679   push @opcode,($rex|0x40) if ($rex);
680}
681
682# older gas and ml64 don't handle SSE>2 instructions
683my %regrm = (	"%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
684		"%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7	);
685
686my $movq = sub {	# elderly gas can't handle inter-register movq
687  my $arg = shift;
688  my @opcode=(0x66);
689    if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
690	my ($src,$dst)=($1,$2);
691	if ($dst !~ /[0-9]+/)	{ $dst = $regrm{"%e$dst"}; }
692	rex(\@opcode,$src,$dst,0x8);
693	push @opcode,0x0f,0x7e;
694	push @opcode,0xc0|(($src&7)<<3)|($dst&7);	# ModR/M
695	@opcode;
696    } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
697	my ($src,$dst)=($2,$1);
698	if ($dst !~ /[0-9]+/)	{ $dst = $regrm{"%e$dst"}; }
699	rex(\@opcode,$src,$dst,0x8);
700	push @opcode,0x0f,0x6e;
701	push @opcode,0xc0|(($src&7)<<3)|($dst&7);	# ModR/M
702	@opcode;
703    } else {
704	();
705    }
706};
707
708my $pextrd = sub {
709    if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
710      my @opcode=(0x66);
711	$imm=$1;
712	$src=$2;
713	$dst=$3;
714	if ($dst =~ /%r([0-9]+)d/)	{ $dst = $1; }
715	elsif ($dst =~ /%e/)		{ $dst = $regrm{$dst}; }
716	rex(\@opcode,$src,$dst);
717	push @opcode,0x0f,0x3a,0x16;
718	push @opcode,0xc0|(($src&7)<<3)|($dst&7);	# ModR/M
719	push @opcode,$imm;
720	@opcode;
721    } else {
722	();
723    }
724};
725
726my $pinsrd = sub {
727    if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
728      my @opcode=(0x66);
729	$imm=$1;
730	$src=$2;
731	$dst=$3;
732	if ($src =~ /%r([0-9]+)/)	{ $src = $1; }
733	elsif ($src =~ /%e/)		{ $src = $regrm{$src}; }
734	rex(\@opcode,$dst,$src);
735	push @opcode,0x0f,0x3a,0x22;
736	push @opcode,0xc0|(($dst&7)<<3)|($src&7);	# ModR/M
737	push @opcode,$imm;
738	@opcode;
739    } else {
740	();
741    }
742};
743
744my $pshufb = sub {
745    if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
746      my @opcode=(0x66);
747	rex(\@opcode,$2,$1);
748	push @opcode,0x0f,0x38,0x00;
749	push @opcode,0xc0|($1&7)|(($2&7)<<3);		# ModR/M
750	@opcode;
751    } else {
752	();
753    }
754};
755
756my $palignr = sub {
757    if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
758      my @opcode=(0x66);
759	rex(\@opcode,$3,$2);
760	push @opcode,0x0f,0x3a,0x0f;
761	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
762	push @opcode,$1;
763	@opcode;
764    } else {
765	();
766    }
767};
768
769my $pclmulqdq = sub {
770    if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
771      my @opcode=(0x66);
772	rex(\@opcode,$3,$2);
773	push @opcode,0x0f,0x3a,0x44;
774	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
775	my $c=$1;
776	push @opcode,$c=~/^0/?oct($c):$c;
777	@opcode;
778    } else {
779	();
780    }
781};
782
783my $rdrand = sub {
784    if (shift =~ /%[er](\w+)/) {
785      my @opcode=();
786      my $dst=$1;
787	if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
788	rex(\@opcode,0,$1,8);
789	push @opcode,0x0f,0xc7,0xf0|($dst&7);
790	@opcode;
791    } else {
792	();
793    }
794};
795
796my $rdseed = sub {
797    if (shift =~ /%[er](\w+)/) {
798      my @opcode=();
799      my $dst=$1;
800	if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
801	rex(\@opcode,0,$1,8);
802	push @opcode,0x0f,0xc7,0xf8|($dst&7);
803	@opcode;
804    } else {
805	();
806    }
807};
808
809sub rxb {
810 local *opcode=shift;
811 my ($dst,$src1,$src2,$rxb)=@_;
812
813   $rxb|=0x7<<5;
814   $rxb&=~(0x04<<5) if($dst>=8);
815   $rxb&=~(0x01<<5) if($src1>=8);
816   $rxb&=~(0x02<<5) if($src2>=8);
817   push @opcode,$rxb;
818}
819
820my $vprotd = sub {
821    if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
822      my @opcode=(0x8f);
823	rxb(\@opcode,$3,$2,-1,0x08);
824	push @opcode,0x78,0xc2;
825	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
826	my $c=$1;
827	push @opcode,$c=~/^0/?oct($c):$c;
828	@opcode;
829    } else {
830	();
831    }
832};
833
834my $vprotq = sub {
835    if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
836      my @opcode=(0x8f);
837	rxb(\@opcode,$3,$2,-1,0x08);
838	push @opcode,0x78,0xc3;
839	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
840	my $c=$1;
841	push @opcode,$c=~/^0/?oct($c):$c;
842	@opcode;
843    } else {
844	();
845    }
846};
847
848if ($nasm) {
849    print <<___;
850default	rel
851%define XMMWORD
852%define YMMWORD
853%define ZMMWORD
854___
855} elsif ($masm) {
856    print <<___;
857OPTION	DOTNAME
858___
859}
860while($line=<>) {
861
862    chomp($line);
863
864    $line =~ s|[#!].*$||;	# get rid of asm-style comments...
865    $line =~ s|/\*.*\*/||;	# ... and C-style comments...
866    $line =~ s|^\s+||;		# ... and skip white spaces in beginning
867    $line =~ s|\s+$||;		# ... and at the end
868
869    undef $label;
870    undef $opcode;
871    undef @args;
872
873    if ($label=label->re(\$line))	{ print $label->out(); }
874
875    if (directive->re(\$line)) {
876	printf "%s",directive->out();
877    } elsif ($opcode=opcode->re(\$line)) {
878	my $asm = eval("\$".$opcode->mnemonic());
879	undef @bytes;
880
881	if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
882	    print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
883	    next;
884	}
885
886	ARGUMENT: while (1) {
887	my $arg;
888
889	if ($arg=register->re(\$line))	{ opcode->size($arg->size()); }
890	elsif ($arg=const->re(\$line))	{ }
891	elsif ($arg=ea->re(\$line))	{ }
892	elsif ($arg=expr->re(\$line))	{ }
893	else				{ last ARGUMENT; }
894
895	push @args,$arg;
896
897	last ARGUMENT if ($line !~ /^,/);
898
899	$line =~ s/^,\s*//;
900	} # ARGUMENT:
901
902	if ($#args>=0) {
903	    my $insn;
904	    my $sz=opcode->size();
905
906	    if ($gas) {
907		$insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
908		@args = map($_->out($sz),@args);
909		printf "\t%s\t%s",$insn,join(",",@args);
910	    } else {
911		$insn = $opcode->out();
912		foreach (@args) {
913		    my $arg = $_->out();
914		    # $insn.=$sz compensates for movq, pinsrw, ...
915		    if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
916		    if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
917		    if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
918		    if ($arg =~ /^mm[0-9]+$/)  { $insn.=$sz; $sz="q" if(!$sz); last; }
919		}
920		@args = reverse(@args);
921		undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
922		printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
923	    }
924	} else {
925	    printf "\t%s",$opcode->out();
926	}
927    }
928
929    print $line,"\n";
930}
931
932print "\n$current_segment\tENDS\n"	if ($current_segment && $masm);
933print "END\n"				if ($masm);
934
935close STDOUT;
936
937#################################################
938# Cross-reference x86_64 ABI "card"
939#
940# 		Unix		Win64
941# %rax		*		*
942# %rbx		-		-
943# %rcx		#4		#1
944# %rdx		#3		#2
945# %rsi		#2		-
946# %rdi		#1		-
947# %rbp		-		-
948# %rsp		-		-
949# %r8		#5		#3
950# %r9		#6		#4
951# %r10		*		*
952# %r11		*		*
953# %r12		-		-
954# %r13		-		-
955# %r14		-		-
956# %r15		-		-
957#
958# (*)	volatile register
959# (-)	preserved by callee
960# (#)	Nth argument, volatile
961#
962# In Unix terms top of stack is argument transfer area for arguments
963# which could not be accomodated in registers. Or in other words 7th
964# [integer] argument resides at 8(%rsp) upon function entry point.
965# 128 bytes above %rsp constitute a "red zone" which is not touched
966# by signal handlers and can be used as temporal storage without
967# allocating a frame.
968#
969# In Win64 terms N*8 bytes on top of stack is argument transfer area,
970# which belongs to/can be overwritten by callee. N is the number of
971# arguments passed to callee, *but* not less than 4! This means that
972# upon function entry point 5th argument resides at 40(%rsp), as well
973# as that 32 bytes from 8(%rsp) can always be used as temporal
974# storage [without allocating a frame]. One can actually argue that
975# one can assume a "red zone" above stack pointer under Win64 as well.
976# Point is that at apparently no occasion Windows kernel would alter
977# the area above user stack pointer in true asynchronous manner...
978#
979# All the above means that if assembler programmer adheres to Unix
980# register and stack layout, but disregards the "red zone" existense,
981# it's possible to use following prologue and epilogue to "gear" from
982# Unix to Win64 ABI in leaf functions with not more than 6 arguments.
983#
984# omnipotent_function:
985# ifdef WIN64
986#	movq	%rdi,8(%rsp)
987#	movq	%rsi,16(%rsp)
988#	movq	%rcx,%rdi	; if 1st argument is actually present
989#	movq	%rdx,%rsi	; if 2nd argument is actually ...
990#	movq	%r8,%rdx	; if 3rd argument is ...
991#	movq	%r9,%rcx	; if 4th argument ...
992#	movq	40(%rsp),%r8	; if 5th ...
993#	movq	48(%rsp),%r9	; if 6th ...
994# endif
995#	...
996# ifdef WIN64
997#	movq	8(%rsp),%rdi
998#	movq	16(%rsp),%rsi
999# endif
1000#	ret
1001#
1002#################################################
1003# Win64 SEH, Structured Exception Handling.
1004#
1005# Unlike on Unix systems(*) lack of Win64 stack unwinding information
1006# has undesired side-effect at run-time: if an exception is raised in
1007# assembler subroutine such as those in question (basically we're
1008# referring to segmentation violations caused by malformed input
1009# parameters), the application is briskly terminated without invoking
1010# any exception handlers, most notably without generating memory dump
1011# or any user notification whatsoever. This poses a problem. It's
1012# possible to address it by registering custom language-specific
1013# handler that would restore processor context to the state at
1014# subroutine entry point and return "exception is not handled, keep
1015# unwinding" code. Writing such handler can be a challenge... But it's
1016# doable, though requires certain coding convention. Consider following
1017# snippet:
1018#
1019# .type	function,@function
1020# function:
1021#	movq	%rsp,%rax	# copy rsp to volatile register
1022#	pushq	%r15		# save non-volatile registers
1023#	pushq	%rbx
1024#	pushq	%rbp
1025#	movq	%rsp,%r11
1026#	subq	%rdi,%r11	# prepare [variable] stack frame
1027#	andq	$-64,%r11
1028#	movq	%rax,0(%r11)	# check for exceptions
1029#	movq	%r11,%rsp	# allocate [variable] stack frame
1030#	movq	%rax,0(%rsp)	# save original rsp value
1031# magic_point:
1032#	...
1033#	movq	0(%rsp),%rcx	# pull original rsp value
1034#	movq	-24(%rcx),%rbp	# restore non-volatile registers
1035#	movq	-16(%rcx),%rbx
1036#	movq	-8(%rcx),%r15
1037#	movq	%rcx,%rsp	# restore original rsp
1038#	ret
1039# .size function,.-function
1040#
1041# The key is that up to magic_point copy of original rsp value remains
1042# in chosen volatile register and no non-volatile register, except for
1043# rsp, is modified. While past magic_point rsp remains constant till
1044# the very end of the function. In this case custom language-specific
1045# exception handler would look like this:
1046#
1047# EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1048#		CONTEXT *context,DISPATCHER_CONTEXT *disp)
1049# {	ULONG64 *rsp = (ULONG64 *)context->Rax;
1050#	if (context->Rip >= magic_point)
1051#	{   rsp = ((ULONG64 **)context->Rsp)[0];
1052#	    context->Rbp = rsp[-3];
1053#	    context->Rbx = rsp[-2];
1054#	    context->R15 = rsp[-1];
1055#	}
1056#	context->Rsp = (ULONG64)rsp;
1057#	context->Rdi = rsp[1];
1058#	context->Rsi = rsp[2];
1059#
1060#	memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1061#	RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1062#		dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1063#		&disp->HandlerData,&disp->EstablisherFrame,NULL);
1064#	return ExceptionContinueSearch;
1065# }
1066#
1067# It's appropriate to implement this handler in assembler, directly in
1068# function's module. In order to do that one has to know members'
1069# offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1070# values. Here they are:
1071#
1072#	CONTEXT.Rax				120
1073#	CONTEXT.Rcx				128
1074#	CONTEXT.Rdx				136
1075#	CONTEXT.Rbx				144
1076#	CONTEXT.Rsp				152
1077#	CONTEXT.Rbp				160
1078#	CONTEXT.Rsi				168
1079#	CONTEXT.Rdi				176
1080#	CONTEXT.R8				184
1081#	CONTEXT.R9				192
1082#	CONTEXT.R10				200
1083#	CONTEXT.R11				208
1084#	CONTEXT.R12				216
1085#	CONTEXT.R13				224
1086#	CONTEXT.R14				232
1087#	CONTEXT.R15				240
1088#	CONTEXT.Rip				248
1089#	CONTEXT.Xmm6				512
1090#	sizeof(CONTEXT)				1232
1091#	DISPATCHER_CONTEXT.ControlPc		0
1092#	DISPATCHER_CONTEXT.ImageBase		8
1093#	DISPATCHER_CONTEXT.FunctionEntry	16
1094#	DISPATCHER_CONTEXT.EstablisherFrame	24
1095#	DISPATCHER_CONTEXT.TargetIp		32
1096#	DISPATCHER_CONTEXT.ContextRecord	40
1097#	DISPATCHER_CONTEXT.LanguageHandler	48
1098#	DISPATCHER_CONTEXT.HandlerData		56
1099#	UNW_FLAG_NHANDLER			0
1100#	ExceptionContinueSearch			1
1101#
1102# In order to tie the handler to the function one has to compose
1103# couple of structures: one for .xdata segment and one for .pdata.
1104#
1105# UNWIND_INFO structure for .xdata segment would be
1106#
1107# function_unwind_info:
1108#	.byte	9,0,0,0
1109#	.rva	handler
1110#
1111# This structure designates exception handler for a function with
1112# zero-length prologue, no stack frame or frame register.
1113#
1114# To facilitate composing of .pdata structures, auto-generated "gear"
1115# prologue copies rsp value to rax and denotes next instruction with
1116# .LSEH_begin_{function_name} label. This essentially defines the SEH
1117# styling rule mentioned in the beginning. Position of this label is
1118# chosen in such manner that possible exceptions raised in the "gear"
1119# prologue would be accounted to caller and unwound from latter's frame.
1120# End of function is marked with respective .LSEH_end_{function_name}
1121# label. To summarize, .pdata segment would contain
1122#
1123#	.rva	.LSEH_begin_function
1124#	.rva	.LSEH_end_function
1125#	.rva	function_unwind_info
1126#
1127# Reference to functon_unwind_info from .xdata segment is the anchor.
1128# In case you wonder why references are 32-bit .rvas and not 64-bit
1129# .quads. References put into these two segments are required to be
1130# *relative* to the base address of the current binary module, a.k.a.
1131# image base. No Win64 module, be it .exe or .dll, can be larger than
1132# 2GB and thus such relative references can be and are accommodated in
1133# 32 bits.
1134#
1135# Having reviewed the example function code, one can argue that "movq
1136# %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1137# rax would contain an undefined value. If this "offends" you, use
1138# another register and refrain from modifying rax till magic_point is
1139# reached, i.e. as if it was a non-volatile register. If more registers
1140# are required prior [variable] frame setup is completed, note that
1141# nobody says that you can have only one "magic point." You can
1142# "liberate" non-volatile registers by denoting last stack off-load
1143# instruction and reflecting it in finer grade unwind logic in handler.
1144# After all, isn't it why it's called *language-specific* handler...
1145#
1146# Attentive reader can notice that exceptions would be mishandled in
1147# auto-generated "gear" epilogue. Well, exception effectively can't
1148# occur there, because if memory area used by it was subject to
1149# segmentation violation, then it would be raised upon call to the
1150# function (and as already mentioned be accounted to caller, which is
1151# not a problem). If you're still not comfortable, then define tail
1152# "magic point" just prior ret instruction and have handler treat it...
1153#
1154# (*)	Note that we're talking about run-time, not debug-time. Lack of
1155#	unwind information makes debugging hard on both Windows and
1156#	Unix. "Unlike" referes to the fact that on Unix signal handler
1157#	will always be invoked, core dumped and appropriate exit code
1158#	returned to parent (for user notification).
1159