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