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