]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/perlasm/x86_64-xlate.pl
a2d870bb434e05ce37549dfa38e05aa9e2f63283
[thirdparty/openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
4 #
5 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6 # format is way easier to parse. Because it's simpler to "gear" from
7 # Unix ABI to Windows one [see cross-reference "card" at the end of
8 # file]. Because Linux targets were available first...
9 #
10 # In addition the script also "distills" code suitable for GNU
11 # assembler, so that it can be compiled with more rigid assemblers,
12 # such as Solaris /usr/ccs/bin/as.
13 #
14 # This translator is not designed to convert *arbitrary* assembler
15 # code from AT&T format to MASM one. It's designed to convert just
16 # enough to provide for dual-ABI OpenSSL modules development...
17 # There *are* limitations and you might have to modify your assembler
18 # code or this script to achieve the desired result...
19 #
20 # Currently recognized limitations:
21 #
22 # - can't use multiple ops per line;
23 #
24 # Dual-ABI styling rules.
25 #
26 # 1. Adhere to Unix register and stack layout [see cross-reference
27 # ABI "card" at the end for explanation].
28 # 2. Forget about "red zone," stick to more traditional blended
29 # stack frame allocation. If volatile storage is actually required
30 # that is. If not, just leave the stack as is.
31 # 3. Functions tagged with ".type name,@function" get crafted with
32 # unified Win64 prologue and epilogue automatically. If you want
33 # to take care of ABI differences yourself, tag functions as
34 # ".type name,@abi-omnipotent" instead.
35 # 4. To optimize the Win64 prologue you can specify number of input
36 # arguments as ".type name,@function,N." Keep in mind that if N is
37 # larger than 6, then you *have to* write "abi-omnipotent" code,
38 # because >6 cases can't be addressed with unified prologue.
39 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
40 # (sorry about latter).
41 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
42 # required to identify the spots, where to inject Win64 epilogue!
43 # But on the pros, it's then prefixed with rep automatically:-)
44 # 7. Stick to explicit ip-relative addressing. If you have to use
45 # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
46 # Both are recognized and translated to proper Win64 addressing
47 # modes. To support legacy code a synthetic directive, .picmeup,
48 # is implemented. It puts address of the *next* instruction into
49 # target register, e.g.:
50 #
51 # .picmeup %rax
52 # lea .Label-.(%rax),%rax
53 #
54 # 8. In order to provide for structured exception handling unified
55 # Win64 prologue copies %rsp value to %rax. For further details
56 # see SEH paragraph at the end.
57 # 9. .init segment is allowed to contain calls to functions only.
58 # a. If function accepts more than 4 arguments *and* >4th argument
59 # is declared as non 64-bit value, do clear its upper part.
60 \f
61 my $flavour = shift;
62 my $output = shift;
63 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
64
65 open STDOUT,">$output" || die "can't open $output: $!"
66 if (defined($output));
67
68 my $gas=1; $gas=0 if ($output =~ /\.asm$/);
69 my $elf=1; $elf=0 if (!$gas);
70 my $win64=0;
71 my $prefix="";
72 my $decor=".L";
73
74 my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
75 my $masm=0;
76 my $PTR=" PTR";
77
78 my $nasmref=2.03;
79 my $nasm=0;
80
81 if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
82 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
83 chomp($prefix);
84 }
85 elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
86 elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
87 elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
88 elsif (!$gas)
89 { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
90 { $nasm = $1 + $2*0.01; $PTR=""; }
91 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
92 { $masm = $1 + $2*2**-16 + $4*2**-32; }
93 die "no assembler found on %PATH" if (!($nasm || $masm));
94 $win64=1;
95 $elf=0;
96 $decor="\$L\$";
97 }
98
99 my $current_segment;
100 my $current_function;
101 my %globals;
102
103 { package opcode; # pick up opcodes
104 sub re {
105 my $self = shift; # single instance in enough...
106 local *line = shift;
107 undef $ret;
108
109 if ($line =~ /^([a-z][a-z0-9]*)/i) {
110 $self->{op} = $1;
111 $ret = $self;
112 $line = substr($line,@+[0]); $line =~ s/^\s+//;
113
114 undef $self->{sz};
115 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
116 $self->{op} = $1;
117 $self->{sz} = $2;
118 } elsif ($self->{op} =~ /call|jmp/) {
119 $self->{sz} = "";
120 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
121 $self->{sz} = "";
122 } elsif ($self->{op} =~ /^v/) { # VEX
123 $self->{sz} = "";
124 } elsif ($self->{op} =~ /movq/ && $line =~ /%xmm/) {
125 $self->{sz} = "";
126 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
127 $self->{op} = $1;
128 $self->{sz} = $2;
129 }
130 }
131 $ret;
132 }
133 sub size {
134 my $self = shift;
135 my $sz = shift;
136 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
137 $self->{sz};
138 }
139 sub out {
140 my $self = shift;
141 if ($gas) {
142 if ($self->{op} eq "movz") { # movz is pain...
143 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
144 } elsif ($self->{op} =~ /^set/) {
145 "$self->{op}";
146 } elsif ($self->{op} eq "ret") {
147 my $epilogue = "";
148 if ($win64 && $current_function->{abi} eq "svr4") {
149 $epilogue = "movq 8(%rsp),%rdi\n\t" .
150 "movq 16(%rsp),%rsi\n\t";
151 }
152 $epilogue . ".byte 0xf3,0xc3";
153 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
154 ".p2align\t3\n\t.quad";
155 } else {
156 "$self->{op}$self->{sz}";
157 }
158 } else {
159 $self->{op} =~ s/^movz/movzx/;
160 if ($self->{op} eq "ret") {
161 $self->{op} = "";
162 if ($win64 && $current_function->{abi} eq "svr4") {
163 $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
164 "mov rsi,QWORD${PTR}[16+rsp]\n\t";
165 }
166 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
167 } elsif ($self->{op} =~ /^(pop|push)f/) {
168 $self->{op} .= $self->{sz};
169 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
170 $self->{op} = "\tDQ";
171 }
172 $self->{op};
173 }
174 }
175 sub mnemonic {
176 my $self=shift;
177 my $op=shift;
178 $self->{op}=$op if (defined($op));
179 $self->{op};
180 }
181 }
182 { package const; # pick up constants, which start with $
183 sub re {
184 my $self = shift; # single instance in enough...
185 local *line = shift;
186 undef $ret;
187
188 if ($line =~ /^\$([^,]+)/) {
189 $self->{value} = $1;
190 $ret = $self;
191 $line = substr($line,@+[0]); $line =~ s/^\s+//;
192 }
193 $ret;
194 }
195 sub out {
196 my $self = shift;
197
198 if ($gas) {
199 # Solaris /usr/ccs/bin/as can't handle multiplications
200 # in $self->{value}
201 $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
202 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
203 sprintf "\$%s",$self->{value};
204 } else {
205 $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
206 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
207 sprintf "%s",$self->{value};
208 }
209 }
210 }
211 { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
212 sub re {
213 my $self = shift; # single instance in enough...
214 local *line = shift;
215 undef $ret;
216
217 # optional * ---vvv--- appears in indirect jmp/call
218 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
219 $self->{asterisk} = $1;
220 $self->{label} = $2;
221 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
222 $self->{scale} = 1 if (!defined($self->{scale}));
223 $ret = $self;
224 $line = substr($line,@+[0]); $line =~ s/^\s+//;
225
226 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
227 die if (opcode->mnemonic() ne "mov");
228 opcode->mnemonic("lea");
229 }
230 $self->{base} =~ s/^%//;
231 $self->{index} =~ s/^%// if (defined($self->{index}));
232 }
233 $ret;
234 }
235 sub size {}
236 sub out {
237 my $self = shift;
238 my $sz = shift;
239
240 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
241 $self->{label} =~ s/\.L/$decor/g;
242
243 # Silently convert all EAs to 64-bit. This is required for
244 # elder GNU assembler and results in more compact code,
245 # *but* most importantly AES module depends on this feature!
246 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
247 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
248
249 # Solaris /usr/ccs/bin/as can't handle multiplications
250 # in $self->{label}, new gas requires sign extension...
251 use integer;
252 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
253 $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
254 $self->{label} =~ s/([0-9]+)/$1<<32>>32/eg;
255
256 if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
257 $self->{base} =~ /(rbp|r13)/) {
258 $self->{base} = $self->{index}; $self->{index} = $1;
259 }
260
261 if ($gas) {
262 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
263
264 if (defined($self->{index})) {
265 sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
266 $self->{label},
267 $self->{base}?"%$self->{base}":"",
268 $self->{index},$self->{scale};
269 } else {
270 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
271 }
272 } else {
273 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR",
274 q=>"QWORD$PTR",o=>"OWORD$PTR",x=>"XMMWORD$PTR",
275 y=>"" );
276
277 $self->{label} =~ s/\./\$/g;
278 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
279 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
280 $sz="q" if ($self->{asterisk} || opcode->mnemonic() =~ /^v?movq$/);
281 $sz="l" if (opcode->mnemonic() =~ /^v?movd$/);
282
283 if (defined($self->{index})) {
284 sprintf "%s[%s%s*%d%s]",$szmap{$sz},
285 $self->{label}?"$self->{label}+":"",
286 $self->{index},$self->{scale},
287 $self->{base}?"+$self->{base}":"";
288 } elsif ($self->{base} eq "rip") {
289 sprintf "%s[%s]",$szmap{$sz},$self->{label};
290 } else {
291 sprintf "%s[%s%s]",$szmap{$sz},
292 $self->{label}?"$self->{label}+":"",
293 $self->{base};
294 }
295 }
296 }
297 }
298 { package register; # pick up registers, which start with %.
299 sub re {
300 my $class = shift; # muliple instances...
301 my $self = {};
302 local *line = shift;
303 undef $ret;
304
305 # optional * ---vvv--- appears in indirect jmp/call
306 if ($line =~ /^(\*?)%(\w+)/) {
307 bless $self,$class;
308 $self->{asterisk} = $1;
309 $self->{value} = $2;
310 $ret = $self;
311 $line = substr($line,@+[0]); $line =~ s/^\s+//;
312 }
313 $ret;
314 }
315 sub size {
316 my $self = shift;
317 undef $ret;
318
319 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
320 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
321 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
322 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
323 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
324 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
325 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
326 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
327
328 $ret;
329 }
330 sub out {
331 my $self = shift;
332 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
333 else { $self->{value}; }
334 }
335 }
336 { package label; # pick up labels, which end with :
337 sub re {
338 my $self = shift; # single instance is enough...
339 local *line = shift;
340 undef $ret;
341
342 if ($line =~ /(^[\.\w]+)\:/) {
343 $self->{value} = $1;
344 $ret = $self;
345 $line = substr($line,@+[0]); $line =~ s/^\s+//;
346
347 $self->{value} =~ s/^\.L/$decor/;
348 }
349 $ret;
350 }
351 sub out {
352 my $self = shift;
353
354 if ($gas) {
355 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
356 if ($win64 &&
357 $current_function->{name} eq $self->{value} &&
358 $current_function->{abi} eq "svr4") {
359 $func .= "\n";
360 $func .= " movq %rdi,8(%rsp)\n";
361 $func .= " movq %rsi,16(%rsp)\n";
362 $func .= " movq %rsp,%rax\n";
363 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
364 my $narg = $current_function->{narg};
365 $narg=6 if (!defined($narg));
366 $func .= " movq %rcx,%rdi\n" if ($narg>0);
367 $func .= " movq %rdx,%rsi\n" if ($narg>1);
368 $func .= " movq %r8,%rdx\n" if ($narg>2);
369 $func .= " movq %r9,%rcx\n" if ($narg>3);
370 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
371 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
372 }
373 $func;
374 } elsif ($self->{value} ne "$current_function->{name}") {
375 $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
376 $self->{value} . ":";
377 } elsif ($win64 && $current_function->{abi} eq "svr4") {
378 my $func = "$current_function->{name}" .
379 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
380 "\n";
381 $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
382 $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
383 $func .= " mov rax,rsp\n";
384 $func .= "${decor}SEH_begin_$current_function->{name}:";
385 $func .= ":" if ($masm);
386 $func .= "\n";
387 my $narg = $current_function->{narg};
388 $narg=6 if (!defined($narg));
389 $func .= " mov rdi,rcx\n" if ($narg>0);
390 $func .= " mov rsi,rdx\n" if ($narg>1);
391 $func .= " mov rdx,r8\n" if ($narg>2);
392 $func .= " mov rcx,r9\n" if ($narg>3);
393 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
394 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
395 $func .= "\n";
396 } else {
397 "$current_function->{name}".
398 ($nasm ? ":" : "\tPROC $current_function->{scope}");
399 }
400 }
401 }
402 { package expr; # pick up expressioins
403 sub re {
404 my $self = shift; # single instance is enough...
405 local *line = shift;
406 undef $ret;
407
408 if ($line =~ /(^[^,]+)/) {
409 $self->{value} = $1;
410 $ret = $self;
411 $line = substr($line,@+[0]); $line =~ s/^\s+//;
412
413 $self->{value} =~ s/\@PLT// if (!$elf);
414 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
415 $self->{value} =~ s/\.L/$decor/g;
416 }
417 $ret;
418 }
419 sub out {
420 my $self = shift;
421 if ($nasm && opcode->mnemonic()=~m/^j/) {
422 "NEAR ".$self->{value};
423 } else {
424 $self->{value};
425 }
426 }
427 }
428 { package directive; # pick up directives, which start with .
429 sub re {
430 my $self = shift; # single instance is enough...
431 local *line = shift;
432 undef $ret;
433 my $dir;
434 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
435 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
436 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
437 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
438 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
439 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
440 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
441 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
442 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
443
444 if ($line =~ /^\s*(\.\w+)/) {
445 $dir = $1;
446 $ret = $self;
447 undef $self->{value};
448 $line = substr($line,@+[0]); $line =~ s/^\s+//;
449
450 SWITCH: for ($dir) {
451 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
452 $dir="\t.long";
453 $line=sprintf "0x%x,0x90000000",$opcode{$1};
454 }
455 last;
456 };
457 /\.global|\.globl|\.extern/
458 && do { $globals{$line} = $prefix . $line;
459 $line = $globals{$line} if ($prefix);
460 last;
461 };
462 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
463 if ($type eq "\@function") {
464 undef $current_function;
465 $current_function->{name} = $sym;
466 $current_function->{abi} = "svr4";
467 $current_function->{narg} = $narg;
468 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
469 } elsif ($type eq "\@abi-omnipotent") {
470 undef $current_function;
471 $current_function->{name} = $sym;
472 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
473 }
474 $line =~ s/\@abi\-omnipotent/\@function/;
475 $line =~ s/\@function.*/\@function/;
476 last;
477 };
478 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
479 $dir = ".byte";
480 $line = join(",",unpack("C*",$1),0);
481 }
482 last;
483 };
484 /\.rva|\.long|\.quad/
485 && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
486 $line =~ s/\.L/$decor/g;
487 last;
488 };
489 }
490
491 if ($gas) {
492 $self->{value} = $dir . "\t" . $line;
493
494 if ($dir =~ /\.extern/) {
495 $self->{value} = ""; # swallow extern
496 } elsif (!$elf && $dir =~ /\.type/) {
497 $self->{value} = "";
498 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
499 (defined($globals{$1})?".scl 2;":".scl 3;") .
500 "\t.type 32;\t.endef"
501 if ($win64 && $line =~ /([^,]+),\@function/);
502 } elsif (!$elf && $dir =~ /\.size/) {
503 $self->{value} = "";
504 if (defined($current_function)) {
505 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
506 if ($win64 && $current_function->{abi} eq "svr4");
507 undef $current_function;
508 }
509 } elsif (!$elf && $dir =~ /\.align/) {
510 $self->{value} = ".p2align\t" . (log($line)/log(2));
511 } elsif ($dir eq ".section") {
512 $current_segment=$line;
513 if (!$elf && $current_segment eq ".init") {
514 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
515 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
516 }
517 } elsif ($dir =~ /\.(text|data)/) {
518 $current_segment=".$1";
519 } elsif ($dir =~ /\.hidden/) {
520 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$line"; }
521 elsif ($flavour eq "mingw64") { $self->{value} = ""; }
522 } elsif ($dir =~ /\.comm/) {
523 $self->{value} = "$dir\t$prefix$line";
524 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
525 }
526 $line = "";
527 return $self;
528 }
529
530 # non-gas case or nasm/masm
531 SWITCH: for ($dir) {
532 /\.text/ && do { my $v=undef;
533 if ($nasm) {
534 $v="section .text code align=64\n";
535 } else {
536 $v="$current_segment\tENDS\n" if ($current_segment);
537 $current_segment = ".text\$";
538 $v.="$current_segment\tSEGMENT ";
539 $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
540 $v.=" 'CODE'";
541 }
542 $self->{value} = $v;
543 last;
544 };
545 /\.data/ && do { my $v=undef;
546 if ($nasm) {
547 $v="section .data data align=8\n";
548 } else {
549 $v="$current_segment\tENDS\n" if ($current_segment);
550 $current_segment = "_DATA";
551 $v.="$current_segment\tSEGMENT";
552 }
553 $self->{value} = $v;
554 last;
555 };
556 /\.section/ && do { my $v=undef;
557 $line =~ s/([^,]*).*/$1/;
558 $line = ".CRT\$XCU" if ($line eq ".init");
559 if ($nasm) {
560 $v="section $line";
561 if ($line=~/\.([px])data/) {
562 $v.=" rdata align=";
563 $v.=$1 eq "p"? 4 : 8;
564 } elsif ($line=~/\.CRT\$/i) {
565 $v.=" rdata align=8";
566 }
567 } else {
568 $v="$current_segment\tENDS\n" if ($current_segment);
569 $v.="$line\tSEGMENT";
570 if ($line=~/\.([px])data/) {
571 $v.=" READONLY";
572 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
573 } elsif ($line=~/\.CRT\$/i) {
574 $v.=" READONLY ";
575 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
576 }
577 }
578 $current_segment = $line;
579 $self->{value} = $v;
580 last;
581 };
582 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
583 $self->{value} .= ":NEAR" if ($masm);
584 last;
585 };
586 /\.globl|.global/
587 && do { $self->{value} = $masm?"PUBLIC":"global";
588 $self->{value} .= "\t".$line;
589 last;
590 };
591 /\.size/ && do { if (defined($current_function)) {
592 undef $self->{value};
593 if ($current_function->{abi} eq "svr4") {
594 $self->{value}="${decor}SEH_end_$current_function->{name}:";
595 $self->{value}.=":\n" if($masm);
596 }
597 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
598 undef $current_function;
599 }
600 last;
601 };
602 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
603 /\.(value|long|rva|quad)/
604 && do { my $sz = substr($1,0,1);
605 my @arr = split(/,\s*/,$line);
606 my $last = pop(@arr);
607 my $conv = sub { my $var=shift;
608 $var=~s/^(0b[0-1]+)/oct($1)/eig;
609 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
610 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
611 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
612 $var;
613 };
614
615 $sz =~ tr/bvlrq/BWDDQ/;
616 $self->{value} = "\tD$sz\t";
617 for (@arr) { $self->{value} .= &$conv($_).","; }
618 $self->{value} .= &$conv($last);
619 last;
620 };
621 /\.byte/ && do { my @str=split(/,\s*/,$line);
622 map(s/(0b[0-1]+)/oct($1)/eig,@str);
623 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
624 while ($#str>15) {
625 $self->{value}.="DB\t"
626 .join(",",@str[0..15])."\n";
627 foreach (0..15) { shift @str; }
628 }
629 $self->{value}.="DB\t"
630 .join(",",@str) if (@str);
631 last;
632 };
633 /\.comm/ && do { my @str=split(/,\s*/,$line);
634 my $v=undef;
635 if ($nasm) {
636 $v.="common $prefix@str[0] @str[1]";
637 } else {
638 $v="$current_segment\tENDS\n" if ($current_segment);
639 $current_segment = "_DATA";
640 $v.="$current_segment\tSEGMENT\n";
641 $v.="COMM @str[0]:DWORD:".@str[1]/4;
642 }
643 $self->{value} = $v;
644 last;
645 };
646 }
647 $line = "";
648 }
649
650 $ret;
651 }
652 sub out {
653 my $self = shift;
654 $self->{value};
655 }
656 }
657
658 sub rex {
659 local *opcode=shift;
660 my ($dst,$src,$rex)=@_;
661
662 $rex|=0x04 if($dst>=8);
663 $rex|=0x01 if($src>=8);
664 push @opcode,($rex|0x40) if ($rex);
665 }
666
667 # older gas and ml64 don't handle SSE>2 instructions
668 my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
669 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
670
671 my $movq = sub { # elderly gas can't handle inter-register movq
672 my $arg = shift;
673 my @opcode=(0x66);
674 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
675 my ($src,$dst)=($1,$2);
676 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
677 rex(\@opcode,$src,$dst,0x8);
678 push @opcode,0x0f,0x7e;
679 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
680 @opcode;
681 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
682 my ($src,$dst)=($2,$1);
683 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
684 rex(\@opcode,$src,$dst,0x8);
685 push @opcode,0x0f,0x6e;
686 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
687 @opcode;
688 } else {
689 ();
690 }
691 };
692
693 my $pextrd = sub {
694 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
695 my @opcode=(0x66);
696 $imm=$1;
697 $src=$2;
698 $dst=$3;
699 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
700 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
701 rex(\@opcode,$src,$dst);
702 push @opcode,0x0f,0x3a,0x16;
703 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
704 push @opcode,$imm;
705 @opcode;
706 } else {
707 ();
708 }
709 };
710
711 my $pinsrd = sub {
712 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
713 my @opcode=(0x66);
714 $imm=$1;
715 $src=$2;
716 $dst=$3;
717 if ($src =~ /%r([0-9]+)/) { $src = $1; }
718 elsif ($src =~ /%e/) { $src = $regrm{$src}; }
719 rex(\@opcode,$dst,$src);
720 push @opcode,0x0f,0x3a,0x22;
721 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
722 push @opcode,$imm;
723 @opcode;
724 } else {
725 ();
726 }
727 };
728
729 my $pshufb = sub {
730 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
731 my @opcode=(0x66);
732 rex(\@opcode,$2,$1);
733 push @opcode,0x0f,0x38,0x00;
734 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
735 @opcode;
736 } else {
737 ();
738 }
739 };
740
741 my $palignr = sub {
742 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
743 my @opcode=(0x66);
744 rex(\@opcode,$3,$2);
745 push @opcode,0x0f,0x3a,0x0f;
746 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
747 push @opcode,$1;
748 @opcode;
749 } else {
750 ();
751 }
752 };
753
754 my $pclmulqdq = sub {
755 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
756 my @opcode=(0x66);
757 rex(\@opcode,$3,$2);
758 push @opcode,0x0f,0x3a,0x44;
759 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
760 my $c=$1;
761 push @opcode,$c=~/^0/?oct($c):$c;
762 @opcode;
763 } else {
764 ();
765 }
766 };
767
768 my $rdrand = sub {
769 if (shift =~ /%[er](\w+)/) {
770 my @opcode=();
771 my $dst=$1;
772 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
773 rex(\@opcode,0,$1,8);
774 push @opcode,0x0f,0xc7,0xf0|($dst&7);
775 @opcode;
776 } else {
777 ();
778 }
779 };
780
781 sub rxb {
782 local *opcode=shift;
783 my ($dst,$src1,$src2,$rxb)=@_;
784
785 $rxb|=0x7<<5;
786 $rxb&=~(0x04<<5) if($dst>=8);
787 $rxb&=~(0x01<<5) if($src1>=8);
788 $rxb&=~(0x02<<5) if($src2>=8);
789 push @opcode,$rxb;
790 }
791
792 my $vprotd = sub {
793 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
794 my @opcode=(0x8f);
795 rxb(\@opcode,$3,$2,-1,0x08);
796 push @opcode,0x78,0xc2;
797 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
798 my $c=$1;
799 push @opcode,$c=~/^0/?oct($c):$c;
800 @opcode;
801 } else {
802 ();
803 }
804 };
805
806 my $vprotq = sub {
807 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
808 my @opcode=(0x8f);
809 rxb(\@opcode,$3,$2,-1,0x08);
810 push @opcode,0x78,0xc3;
811 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
812 my $c=$1;
813 push @opcode,$c=~/^0/?oct($c):$c;
814 @opcode;
815 } else {
816 ();
817 }
818 };
819
820 if ($nasm) {
821 print <<___;
822 default rel
823 %define XMMWORD
824 ___
825 } elsif ($masm) {
826 print <<___;
827 OPTION DOTNAME
828 ___
829 }
830 while($line=<>) {
831
832 chomp($line);
833
834 $line =~ s|[#!].*$||; # get rid of asm-style comments...
835 $line =~ s|/\*.*\*/||; # ... and C-style comments...
836 $line =~ s|^\s+||; # ... and skip white spaces in beginning
837
838 undef $label;
839 undef $opcode;
840 undef @args;
841
842 if ($label=label->re(\$line)) { print $label->out(); }
843
844 if (directive->re(\$line)) {
845 printf "%s",directive->out();
846 } elsif ($opcode=opcode->re(\$line)) {
847 my $asm = eval("\$".$opcode->mnemonic());
848 undef @bytes;
849
850 if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
851 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
852 next;
853 }
854
855 ARGUMENT: while (1) {
856 my $arg;
857
858 if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
859 elsif ($arg=const->re(\$line)) { }
860 elsif ($arg=ea->re(\$line)) { }
861 elsif ($arg=expr->re(\$line)) { }
862 else { last ARGUMENT; }
863
864 push @args,$arg;
865
866 last ARGUMENT if ($line !~ /^,/);
867
868 $line =~ s/^,\s*//;
869 } # ARGUMENT:
870
871 if ($#args>=0) {
872 my $insn;
873 my $sz=opcode->size();
874
875 if ($gas) {
876 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
877 @args = map($_->out($sz),@args);
878 printf "\t%s\t%s",$insn,join(",",@args);
879 } else {
880 $insn = $opcode->out();
881 foreach (@args) {
882 my $arg = $_->out();
883 # $insn.=$sz compensates for movq, pinsrw, ...
884 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
885 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
886 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
887 }
888 @args = reverse(@args);
889 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
890 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
891 }
892 } else {
893 printf "\t%s",$opcode->out();
894 }
895 }
896
897 print $line,"\n";
898 }
899
900 print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
901 print "END\n" if ($masm);
902
903 close STDOUT;
904
905 \f#################################################
906 # Cross-reference x86_64 ABI "card"
907 #
908 # Unix Win64
909 # %rax * *
910 # %rbx - -
911 # %rcx #4 #1
912 # %rdx #3 #2
913 # %rsi #2 -
914 # %rdi #1 -
915 # %rbp - -
916 # %rsp - -
917 # %r8 #5 #3
918 # %r9 #6 #4
919 # %r10 * *
920 # %r11 * *
921 # %r12 - -
922 # %r13 - -
923 # %r14 - -
924 # %r15 - -
925 #
926 # (*) volatile register
927 # (-) preserved by callee
928 # (#) Nth argument, volatile
929 #
930 # In Unix terms top of stack is argument transfer area for arguments
931 # which could not be accomodated in registers. Or in other words 7th
932 # [integer] argument resides at 8(%rsp) upon function entry point.
933 # 128 bytes above %rsp constitute a "red zone" which is not touched
934 # by signal handlers and can be used as temporal storage without
935 # allocating a frame.
936 #
937 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
938 # which belongs to/can be overwritten by callee. N is the number of
939 # arguments passed to callee, *but* not less than 4! This means that
940 # upon function entry point 5th argument resides at 40(%rsp), as well
941 # as that 32 bytes from 8(%rsp) can always be used as temporal
942 # storage [without allocating a frame]. One can actually argue that
943 # one can assume a "red zone" above stack pointer under Win64 as well.
944 # Point is that at apparently no occasion Windows kernel would alter
945 # the area above user stack pointer in true asynchronous manner...
946 #
947 # All the above means that if assembler programmer adheres to Unix
948 # register and stack layout, but disregards the "red zone" existense,
949 # it's possible to use following prologue and epilogue to "gear" from
950 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
951 #
952 # omnipotent_function:
953 # ifdef WIN64
954 # movq %rdi,8(%rsp)
955 # movq %rsi,16(%rsp)
956 # movq %rcx,%rdi ; if 1st argument is actually present
957 # movq %rdx,%rsi ; if 2nd argument is actually ...
958 # movq %r8,%rdx ; if 3rd argument is ...
959 # movq %r9,%rcx ; if 4th argument ...
960 # movq 40(%rsp),%r8 ; if 5th ...
961 # movq 48(%rsp),%r9 ; if 6th ...
962 # endif
963 # ...
964 # ifdef WIN64
965 # movq 8(%rsp),%rdi
966 # movq 16(%rsp),%rsi
967 # endif
968 # ret
969 #
970 \f#################################################
971 # Win64 SEH, Structured Exception Handling.
972 #
973 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
974 # has undesired side-effect at run-time: if an exception is raised in
975 # assembler subroutine such as those in question (basically we're
976 # referring to segmentation violations caused by malformed input
977 # parameters), the application is briskly terminated without invoking
978 # any exception handlers, most notably without generating memory dump
979 # or any user notification whatsoever. This poses a problem. It's
980 # possible to address it by registering custom language-specific
981 # handler that would restore processor context to the state at
982 # subroutine entry point and return "exception is not handled, keep
983 # unwinding" code. Writing such handler can be a challenge... But it's
984 # doable, though requires certain coding convention. Consider following
985 # snippet:
986 #
987 # .type function,@function
988 # function:
989 # movq %rsp,%rax # copy rsp to volatile register
990 # pushq %r15 # save non-volatile registers
991 # pushq %rbx
992 # pushq %rbp
993 # movq %rsp,%r11
994 # subq %rdi,%r11 # prepare [variable] stack frame
995 # andq $-64,%r11
996 # movq %rax,0(%r11) # check for exceptions
997 # movq %r11,%rsp # allocate [variable] stack frame
998 # movq %rax,0(%rsp) # save original rsp value
999 # magic_point:
1000 # ...
1001 # movq 0(%rsp),%rcx # pull original rsp value
1002 # movq -24(%rcx),%rbp # restore non-volatile registers
1003 # movq -16(%rcx),%rbx
1004 # movq -8(%rcx),%r15
1005 # movq %rcx,%rsp # restore original rsp
1006 # ret
1007 # .size function,.-function
1008 #
1009 # The key is that up to magic_point copy of original rsp value remains
1010 # in chosen volatile register and no non-volatile register, except for
1011 # rsp, is modified. While past magic_point rsp remains constant till
1012 # the very end of the function. In this case custom language-specific
1013 # exception handler would look like this:
1014 #
1015 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1016 # CONTEXT *context,DISPATCHER_CONTEXT *disp)
1017 # { ULONG64 *rsp = (ULONG64 *)context->Rax;
1018 # if (context->Rip >= magic_point)
1019 # { rsp = ((ULONG64 **)context->Rsp)[0];
1020 # context->Rbp = rsp[-3];
1021 # context->Rbx = rsp[-2];
1022 # context->R15 = rsp[-1];
1023 # }
1024 # context->Rsp = (ULONG64)rsp;
1025 # context->Rdi = rsp[1];
1026 # context->Rsi = rsp[2];
1027 #
1028 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1029 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1030 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1031 # &disp->HandlerData,&disp->EstablisherFrame,NULL);
1032 # return ExceptionContinueSearch;
1033 # }
1034 #
1035 # It's appropriate to implement this handler in assembler, directly in
1036 # function's module. In order to do that one has to know members'
1037 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1038 # values. Here they are:
1039 #
1040 # CONTEXT.Rax 120
1041 # CONTEXT.Rcx 128
1042 # CONTEXT.Rdx 136
1043 # CONTEXT.Rbx 144
1044 # CONTEXT.Rsp 152
1045 # CONTEXT.Rbp 160
1046 # CONTEXT.Rsi 168
1047 # CONTEXT.Rdi 176
1048 # CONTEXT.R8 184
1049 # CONTEXT.R9 192
1050 # CONTEXT.R10 200
1051 # CONTEXT.R11 208
1052 # CONTEXT.R12 216
1053 # CONTEXT.R13 224
1054 # CONTEXT.R14 232
1055 # CONTEXT.R15 240
1056 # CONTEXT.Rip 248
1057 # CONTEXT.Xmm6 512
1058 # sizeof(CONTEXT) 1232
1059 # DISPATCHER_CONTEXT.ControlPc 0
1060 # DISPATCHER_CONTEXT.ImageBase 8
1061 # DISPATCHER_CONTEXT.FunctionEntry 16
1062 # DISPATCHER_CONTEXT.EstablisherFrame 24
1063 # DISPATCHER_CONTEXT.TargetIp 32
1064 # DISPATCHER_CONTEXT.ContextRecord 40
1065 # DISPATCHER_CONTEXT.LanguageHandler 48
1066 # DISPATCHER_CONTEXT.HandlerData 56
1067 # UNW_FLAG_NHANDLER 0
1068 # ExceptionContinueSearch 1
1069 #
1070 # In order to tie the handler to the function one has to compose
1071 # couple of structures: one for .xdata segment and one for .pdata.
1072 #
1073 # UNWIND_INFO structure for .xdata segment would be
1074 #
1075 # function_unwind_info:
1076 # .byte 9,0,0,0
1077 # .rva handler
1078 #
1079 # This structure designates exception handler for a function with
1080 # zero-length prologue, no stack frame or frame register.
1081 #
1082 # To facilitate composing of .pdata structures, auto-generated "gear"
1083 # prologue copies rsp value to rax and denotes next instruction with
1084 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1085 # styling rule mentioned in the beginning. Position of this label is
1086 # chosen in such manner that possible exceptions raised in the "gear"
1087 # prologue would be accounted to caller and unwound from latter's frame.
1088 # End of function is marked with respective .LSEH_end_{function_name}
1089 # label. To summarize, .pdata segment would contain
1090 #
1091 # .rva .LSEH_begin_function
1092 # .rva .LSEH_end_function
1093 # .rva function_unwind_info
1094 #
1095 # Reference to functon_unwind_info from .xdata segment is the anchor.
1096 # In case you wonder why references are 32-bit .rvas and not 64-bit
1097 # .quads. References put into these two segments are required to be
1098 # *relative* to the base address of the current binary module, a.k.a.
1099 # image base. No Win64 module, be it .exe or .dll, can be larger than
1100 # 2GB and thus such relative references can be and are accommodated in
1101 # 32 bits.
1102 #
1103 # Having reviewed the example function code, one can argue that "movq
1104 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1105 # rax would contain an undefined value. If this "offends" you, use
1106 # another register and refrain from modifying rax till magic_point is
1107 # reached, i.e. as if it was a non-volatile register. If more registers
1108 # are required prior [variable] frame setup is completed, note that
1109 # nobody says that you can have only one "magic point." You can
1110 # "liberate" non-volatile registers by denoting last stack off-load
1111 # instruction and reflecting it in finer grade unwind logic in handler.
1112 # After all, isn't it why it's called *language-specific* handler...
1113 #
1114 # Attentive reader can notice that exceptions would be mishandled in
1115 # auto-generated "gear" epilogue. Well, exception effectively can't
1116 # occur there, because if memory area used by it was subject to
1117 # segmentation violation, then it would be raised upon call to the
1118 # function (and as already mentioned be accounted to caller, which is
1119 # not a problem). If you're still not comfortable, then define tail
1120 # "magic point" just prior ret instruction and have handler treat it...
1121 #
1122 # (*) Note that we're talking about run-time, not debug-time. Lack of
1123 # unwind information makes debugging hard on both Windows and
1124 # Unix. "Unlike" referes to the fact that on Unix signal handler
1125 # will always be invoked, core dumped and appropriate exit code
1126 # returned to parent (for user notification).