VirtualBox

source: vbox/trunk/src/libs/openssl-3.0.1/crypto/perlasm/x86_64-xlate.pl@ 94083

Last change on this file since 94083 was 94083, checked in by vboxsync, 3 years ago

libs/openssl-3.0.1: Recreate asm files, bugref:10128

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette