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