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