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