summaryrefslogtreecommitdiff
path: root/src/lib/libcrypto/perlasm/x86_64-xlate.pl
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/libcrypto/perlasm/x86_64-xlate.pl')
-rwxr-xr-xsrc/lib/libcrypto/perlasm/x86_64-xlate.pl625
1 files changed, 492 insertions, 133 deletions
diff --git a/src/lib/libcrypto/perlasm/x86_64-xlate.pl b/src/lib/libcrypto/perlasm/x86_64-xlate.pl
index 74153b017d..8153a92a7b 100755
--- a/src/lib/libcrypto/perlasm/x86_64-xlate.pl
+++ b/src/lib/libcrypto/perlasm/x86_64-xlate.pl
@@ -1,6 +1,6 @@
1#!/usr/bin/env perl 1#!/usr/bin/env perl
2 2
3# Ascetic x86_64 AT&T to MASM assembler translator by <appro>. 3# Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
4# 4#
5# Why AT&T to MASM and not vice versa? Several reasons. Because AT&T 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 6# format is way easier to parse. Because it's simpler to "gear" from
@@ -20,12 +20,11 @@
20# Currently recognized limitations: 20# Currently recognized limitations:
21# 21#
22# - can't use multiple ops per line; 22# - can't use multiple ops per line;
23# - indirect calls and jumps are not supported;
24# 23#
25# Dual-ABI styling rules. 24# Dual-ABI styling rules.
26# 25#
27# 1. Adhere to Unix register and stack layout [see the end for 26# 1. Adhere to Unix register and stack layout [see cross-reference
28# explanation]. 27# ABI "card" at the end for explanation].
29# 2. Forget about "red zone," stick to more traditional blended 28# 2. Forget about "red zone," stick to more traditional blended
30# stack frame allocation. If volatile storage is actually required 29# stack frame allocation. If volatile storage is actually required
31# that is. If not, just leave the stack as is. 30# that is. If not, just leave the stack as is.
@@ -42,21 +41,26 @@
42# 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is 41# 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
43# required to identify the spots, where to inject Win64 epilogue! 42# required to identify the spots, where to inject Win64 epilogue!
44# But on the pros, it's then prefixed with rep automatically:-) 43# But on the pros, it's then prefixed with rep automatically:-)
45# 7. Due to MASM limitations [and certain general counter-intuitivity 44# 7. Stick to explicit ip-relative addressing. If you have to use
46# of ip-relative addressing] generation of position-independent 45# GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
47# code is assisted by synthetic directive, .picmeup, which puts 46# Both are recognized and translated to proper Win64 addressing
48# address of the *next* instruction into target register. 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.:
49# 50#
50# Example 1:
51# .picmeup %rax 51# .picmeup %rax
52# lea .Label-.(%rax),%rax 52# lea .Label-.(%rax),%rax
53# Example 2: 53#
54# .picmeup %rcx 54# 8. In order to provide for structured exception handling unified
55# .Lpic_point: 55# Win64 prologue copies %rsp value to %rax. For further details
56# ... 56# see SEH paragraph at the end.
57# lea .Label-.Lpic_point(%rcx),%rbp 57# 9. .init segment is allowed to contain calls to functions only.
58 58# a. If function accepts more than 4 arguments *and* >4th argument
59my $output = shift; 59# is declared as non 64-bit value, do clear its upper part.
60
61my $flavour = shift;
62my $output = shift;
63if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
60 64
61{ my ($stddev,$stdino,@junk)=stat(STDOUT); 65{ my ($stddev,$stdino,@junk)=stat(STDOUT);
62 my ($outdev,$outino,@junk)=stat($output); 66 my ($outdev,$outino,@junk)=stat($output);
@@ -65,13 +69,40 @@ my $output = shift;
65 if ($stddev!=$outdev || $stdino!=$outino); 69 if ($stddev!=$outdev || $stdino!=$outino);
66} 70}
67 71
72my $gas=1; $gas=0 if ($output =~ /\.asm$/);
73my $elf=1; $elf=0 if (!$gas);
74my $win64=0;
75my $prefix="";
76my $decor=".L";
77
68my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005 78my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
69my $masm=$masmref if ($output =~ /\.asm/); 79my $masm=0;
70if ($masm && `ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/) 80my $PTR=" PTR";
71{ $masm=$1 + $2*2**-16 + $4*2**-32; } 81
82my $nasmref=2.03;
83my $nasm=0;
84
85if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
86 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
87 chomp($prefix);
88 }
89elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
90elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
91elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
92elsif (!$gas)
93{ if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
94 { $nasm = $1 + $2*0.01; $PTR=""; }
95 elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
96 { $masm = $1 + $2*2**-16 + $4*2**-32; }
97 die "no assembler found on %PATH" if (!($nasm || $masm));
98 $win64=1;
99 $elf=0;
100 $decor="\$L\$";
101}
72 102
73my $current_segment; 103my $current_segment;
74my $current_function; 104my $current_function;
105my %globals;
75 106
76{ package opcode; # pick up opcodes 107{ package opcode; # pick up opcodes
77 sub re { 108 sub re {
@@ -88,8 +119,10 @@ my $current_function;
88 if ($self->{op} =~ /^(movz)b.*/) { # movz is pain... 119 if ($self->{op} =~ /^(movz)b.*/) { # movz is pain...
89 $self->{op} = $1; 120 $self->{op} = $1;
90 $self->{sz} = "b"; 121 $self->{sz} = "b";
91 } elsif ($self->{op} =~ /call/) { 122 } elsif ($self->{op} =~ /call|jmp/) {
92 $self->{sz} = "" 123 $self->{sz} = "";
124 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op)/) { # SSEn
125 $self->{sz} = "";
93 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) { 126 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
94 $self->{op} = $1; 127 $self->{op} = $1;
95 $self->{sz} = $2; 128 $self->{sz} = $2;
@@ -105,13 +138,20 @@ my $current_function;
105 } 138 }
106 sub out { 139 sub out {
107 my $self = shift; 140 my $self = shift;
108 if (!$masm) { 141 if ($gas) {
109 if ($self->{op} eq "movz") { # movz is pain... 142 if ($self->{op} eq "movz") { # movz is pain...
110 sprintf "%s%s%s",$self->{op},$self->{sz},shift; 143 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
111 } elsif ($self->{op} =~ /^set/) { 144 } elsif ($self->{op} =~ /^set/) {
112 "$self->{op}"; 145 "$self->{op}";
113 } elsif ($self->{op} eq "ret") { 146 } elsif ($self->{op} eq "ret") {
114 ".byte 0xf3,0xc3"; 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";
115 } else { 155 } else {
116 "$self->{op}$self->{sz}"; 156 "$self->{op}$self->{sz}";
117 } 157 }
@@ -119,15 +159,25 @@ my $current_function;
119 $self->{op} =~ s/^movz/movzx/; 159 $self->{op} =~ s/^movz/movzx/;
120 if ($self->{op} eq "ret") { 160 if ($self->{op} eq "ret") {
121 $self->{op} = ""; 161 $self->{op} = "";
122 if ($current_function->{abi} eq "svr4") { 162 if ($win64 && $current_function->{abi} eq "svr4") {
123 $self->{op} = "mov rdi,QWORD PTR 8[rsp]\t;WIN64 epilogue\n\t". 163 $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
124 "mov rsi,QWORD PTR 16[rsp]\n\t"; 164 "mov rsi,QWORD${PTR}[16+rsp]\n\t";
125 } 165 }
126 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret"; 166 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
127 } 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} = "ALIGN\t8\n\tDQ";
171 }
128 $self->{op}; 172 $self->{op};
129 } 173 }
130 } 174 }
175 sub mnemonic {
176 my $self=shift;
177 my $op=shift;
178 $self->{op}=$op if (defined($op));
179 $self->{op};
180 }
131} 181}
132{ package const; # pick up constants, which start with $ 182{ package const; # pick up constants, which start with $
133 sub re { 183 sub re {
@@ -145,14 +195,15 @@ my $current_function;
145 sub out { 195 sub out {
146 my $self = shift; 196 my $self = shift;
147 197
148 if (!$masm) { 198 if ($gas) {
149 # Solaris /usr/ccs/bin/as can't handle multiplications 199 # Solaris /usr/ccs/bin/as can't handle multiplications
150 # in $self->{value} 200 # in $self->{value}
151 $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi; 201 $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
152 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg; 202 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
153 sprintf "\$%s",$self->{value}; 203 sprintf "\$%s",$self->{value};
154 } else { 204 } else {
155 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig; 205 $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
206 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
156 sprintf "%s",$self->{value}; 207 sprintf "%s",$self->{value};
157 } 208 }
158 } 209 }
@@ -163,14 +214,20 @@ my $current_function;
163 local *line = shift; 214 local *line = shift;
164 undef $ret; 215 undef $ret;
165 216
166 if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/ && 217 # optional * ---vvv--- appears in indirect jmp/call
218 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/ &&
167 !($line =~ /^PIC_(GOT|PLT)/)) { 219 !($line =~ /^PIC_(GOT|PLT)/)) {
168 $self->{label} = $1; 220 $self->{asterisk} = $1;
169 ($self->{base},$self->{index},$self->{scale})=split(/,/,$2); 221 $self->{label} = $2;
222 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
170 $self->{scale} = 1 if (!defined($self->{scale})); 223 $self->{scale} = 1 if (!defined($self->{scale}));
171 $ret = $self; 224 $ret = $self;
172 $line = substr($line,@+[0]); $line =~ s/^\s+//; 225 $line = substr($line,@+[0]); $line =~ s/^\s+//;
173 226
227 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
228 die if (opcode->mnemonic() ne "mov");
229 opcode->mnemonic("lea");
230 }
174 $self->{base} =~ s/^%//; 231 $self->{base} =~ s/^%//;
175 $self->{index} =~ s/^%// if (defined($self->{index})); 232 $self->{index} =~ s/^%// if (defined($self->{index}));
176 } 233 }
@@ -181,42 +238,50 @@ my $current_function;
181 my $self = shift; 238 my $self = shift;
182 my $sz = shift; 239 my $sz = shift;
183 240
241 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
242 $self->{label} =~ s/\.L/$decor/g;
243
184 # Silently convert all EAs to 64-bit. This is required for 244 # Silently convert all EAs to 64-bit. This is required for
185 # elder GNU assembler and results in more compact code, 245 # elder GNU assembler and results in more compact code,
186 # *but* most importantly AES module depends on this feature! 246 # *but* most importantly AES module depends on this feature!
187 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/; 247 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
188 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/; 248 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
189 249
190 if (!$masm) { 250 if ($gas) {
191 # Solaris /usr/ccs/bin/as can't handle multiplications 251 # Solaris /usr/ccs/bin/as can't handle multiplications
192 # in $self->{label} 252 # in $self->{label}, new gas requires sign extension...
193 $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi; 253 use integer;
254 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
194 $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg; 255 $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
256 $self->{label} =~ s/([0-9]+)/$1<<32>>32/eg;
257 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
195 258
196 if (defined($self->{index})) { 259 if (defined($self->{index})) {
197 sprintf "%s(%%%s,%%%s,%d)", 260 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk},
198 $self->{label},$self->{base}, 261 $self->{label},$self->{base},
199 $self->{index},$self->{scale}; 262 $self->{index},$self->{scale};
200 } else { 263 } else {
201 sprintf "%s(%%%s)", $self->{label},$self->{base}; 264 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
202 } 265 }
203 } else { 266 } else {
204 %szmap = ( b=>"BYTE", w=>"WORD", l=>"DWORD", q=>"QWORD" ); 267 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
205 268
206 $self->{label} =~ s/\./\$/g; 269 $self->{label} =~ s/\./\$/g;
207 $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig; 270 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
208 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/); 271 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
272 $sz="q" if ($self->{asterisk});
209 273
210 if (defined($self->{index})) { 274 if (defined($self->{index})) {
211 sprintf "%s PTR %s[%s*%d+%s]",$szmap{$sz}, 275 sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
212 $self->{label}, 276 $self->{label}?"$self->{label}+":"",
213 $self->{index},$self->{scale}, 277 $self->{index},$self->{scale},
214 $self->{base}; 278 $self->{base};
215 } elsif ($self->{base} eq "rip") { 279 } elsif ($self->{base} eq "rip") {
216 sprintf "%s PTR %s",$szmap{$sz},$self->{label}; 280 sprintf "%s[%s]",$szmap{$sz},$self->{label};
217 } else { 281 } else {
218 sprintf "%s PTR %s[%s]",$szmap{$sz}, 282 sprintf "%s[%s%s]",$szmap{$sz},
219 $self->{label},$self->{base}; 283 $self->{label}?"$self->{label}+":"",
284 $self->{base};
220 } 285 }
221 } 286 }
222 } 287 }
@@ -228,9 +293,11 @@ my $current_function;
228 local *line = shift; 293 local *line = shift;
229 undef $ret; 294 undef $ret;
230 295
231 if ($line =~ /^%(\w+)/) { 296 # optional * ---vvv--- appears in indirect jmp/call
297 if ($line =~ /^(\*?)%(\w+)/) {
232 bless $self,$class; 298 bless $self,$class;
233 $self->{value} = $1; 299 $self->{asterisk} = $1;
300 $self->{value} = $2;
234 $ret = $self; 301 $ret = $self;
235 $line = substr($line,@+[0]); $line =~ s/^\s+//; 302 $line = substr($line,@+[0]); $line =~ s/^\s+//;
236 } 303 }
@@ -253,7 +320,8 @@ my $current_function;
253 } 320 }
254 sub out { 321 sub out {
255 my $self = shift; 322 my $self = shift;
256 sprintf $masm?"%s":"%%%s",$self->{value}; 323 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
324 else { $self->{value}; }
257 } 325 }
258} 326}
259{ package label; # pick up labels, which end with : 327{ package label; # pick up labels, which end with :
@@ -262,37 +330,63 @@ my $current_function;
262 local *line = shift; 330 local *line = shift;
263 undef $ret; 331 undef $ret;
264 332
265 if ($line =~ /(^[\.\w]+\:)/) { 333 if ($line =~ /(^[\.\w]+)\:/) {
266 $self->{value} = $1; 334 $self->{value} = $1;
267 $ret = $self; 335 $ret = $self;
268 $line = substr($line,@+[0]); $line =~ s/^\s+//; 336 $line = substr($line,@+[0]); $line =~ s/^\s+//;
269 337
270 $self->{value} =~ s/\.L/\$L/ if ($masm); 338 $self->{value} =~ s/^\.L/$decor/;
271 } 339 }
272 $ret; 340 $ret;
273 } 341 }
274 sub out { 342 sub out {
275 my $self = shift; 343 my $self = shift;
276 344
277 if (!$masm) { 345 if ($gas) {
278 $self->{value}; 346 my $func = ($globals{$self->{value}} or $self->{value}) . ":";
279 } elsif ($self->{value} ne "$current_function->{name}:") { 347 if ($win64 &&
280 $self->{value}; 348 $current_function->{name} eq $self->{value} &&
281 } elsif ($current_function->{abi} eq "svr4") { 349 $current_function->{abi} eq "svr4") {
282 my $func = "$current_function->{name} PROC\n". 350 $func .= "\n";
283 " mov QWORD PTR 8[rsp],rdi\t;WIN64 prologue\n". 351 $func .= " movq %rdi,8(%rsp)\n";
284 " mov QWORD PTR 16[rsp],rsi\n"; 352 $func .= " movq %rsi,16(%rsp)\n";
353 $func .= " movq %rsp,%rax\n";
354 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
355 my $narg = $current_function->{narg};
356 $narg=6 if (!defined($narg));
357 $func .= " movq %rcx,%rdi\n" if ($narg>0);
358 $func .= " movq %rdx,%rsi\n" if ($narg>1);
359 $func .= " movq %r8,%rdx\n" if ($narg>2);
360 $func .= " movq %r9,%rcx\n" if ($narg>3);
361 $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
362 $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
363 }
364 $func;
365 } elsif ($self->{value} ne "$current_function->{name}") {
366 $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
367 $self->{value} . ":";
368 } elsif ($win64 && $current_function->{abi} eq "svr4") {
369 my $func = "$current_function->{name}" .
370 ($nasm ? ":" : "\tPROC $current_function->{scope}") .
371 "\n";
372 $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
373 $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
374 $func .= " mov rax,rsp\n";
375 $func .= "${decor}SEH_begin_$current_function->{name}:";
376 $func .= ":" if ($masm);
377 $func .= "\n";
285 my $narg = $current_function->{narg}; 378 my $narg = $current_function->{narg};
286 $narg=6 if (!defined($narg)); 379 $narg=6 if (!defined($narg));
287 $func .= " mov rdi,rcx\n" if ($narg>0); 380 $func .= " mov rdi,rcx\n" if ($narg>0);
288 $func .= " mov rsi,rdx\n" if ($narg>1); 381 $func .= " mov rsi,rdx\n" if ($narg>1);
289 $func .= " mov rdx,r8\n" if ($narg>2); 382 $func .= " mov rdx,r8\n" if ($narg>2);
290 $func .= " mov rcx,r9\n" if ($narg>3); 383 $func .= " mov rcx,r9\n" if ($narg>3);
291 $func .= " mov r8,QWORD PTR 40[rsp]\n" if ($narg>4); 384 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
292 $func .= " mov r9,QWORD PTR 48[rsp]\n" if ($narg>5); 385 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
293 $func .= "\n"; 386 $func .= "\n";
294 } else { 387 } else {
295 "$current_function->{name} PROC"; 388 "$current_function->{name}".
389 ($nasm ? ":" : "\tPROC $current_function->{scope}");
296 } 390 }
297 } 391 }
298} 392}
@@ -307,13 +401,19 @@ my $current_function;
307 $ret = $self; 401 $ret = $self;
308 $line = substr($line,@+[0]); $line =~ s/^\s+//; 402 $line = substr($line,@+[0]); $line =~ s/^\s+//;
309 403
310 $self->{value} =~ s/\.L/\$L/g if ($masm); 404 $self->{value} =~ s/\@PLT// if (!$elf);
405 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
406 $self->{value} =~ s/\.L/$decor/g;
311 } 407 }
312 $ret; 408 $ret;
313 } 409 }
314 sub out { 410 sub out {
315 my $self = shift; 411 my $self = shift;
316 $self->{value}; 412 if ($nasm && opcode->mnemonic()=~m/^j/) {
413 "NEAR ".$self->{value};
414 } else {
415 $self->{value};
416 }
317 } 417 }
318} 418}
319{ package directive; # pick up directives, which start with . 419{ package directive; # pick up directives, which start with .
@@ -333,89 +433,181 @@ my $current_function;
333 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c ); 433 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
334 434
335 if ($line =~ /^\s*(\.\w+)/) { 435 if ($line =~ /^\s*(\.\w+)/) {
336 if (!$masm) {
337 $self->{value} = $1;
338 $line =~ s/\@abi\-omnipotent/\@function/;
339 $line =~ s/\@function.*/\@function/;
340 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
341 $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
342 } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
343 $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
344 } elsif ($line =~ /\.extern/) {
345 $self->{value} = ""; # swallow extern
346 } else {
347 $self->{value} = $line;
348 }
349 $line = "";
350 return $self;
351 }
352
353 $dir = $1; 436 $dir = $1;
354 $ret = $self; 437 $ret = $self;
355 undef $self->{value}; 438 undef $self->{value};
356 $line = substr($line,@+[0]); $line =~ s/^\s+//; 439 $line = substr($line,@+[0]); $line =~ s/^\s+//;
440
357 SWITCH: for ($dir) { 441 SWITCH: for ($dir) {
358 /\.(text)/ 442 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
359 && do { my $v=undef; 443 $dir="\t.long";
360 $v="$current_segment\tENDS\n" if ($current_segment); 444 $line=sprintf "0x%x,0x90000000",$opcode{$1};
361 $current_segment = "_$1\$"; 445 }
362 $current_segment =~ tr/[a-z]/[A-Z]/; 446 last;
363 $v.="$current_segment\tSEGMENT "; 447 };
364 $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE"; 448 /\.global|\.globl|\.extern/
365 $v.=" 'CODE'"; 449 && do { $globals{$line} = $prefix . $line;
366 $self->{value} = $v; 450 $line = $globals{$line} if ($prefix);
367 last; 451 last;
368 }; 452 };
369 /\.extern/ && do { $self->{value} = "EXTRN\t".$line.":BYTE"; last; };
370 /\.globl/ && do { $self->{value} = "PUBLIC\t".$line; last; };
371 /\.type/ && do { ($sym,$type,$narg) = split(',',$line); 453 /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
372 if ($type eq "\@function") { 454 if ($type eq "\@function") {
373 undef $current_function; 455 undef $current_function;
374 $current_function->{name} = $sym; 456 $current_function->{name} = $sym;
375 $current_function->{abi} = "svr4"; 457 $current_function->{abi} = "svr4";
376 $current_function->{narg} = $narg; 458 $current_function->{narg} = $narg;
459 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
377 } elsif ($type eq "\@abi-omnipotent") { 460 } elsif ($type eq "\@abi-omnipotent") {
378 undef $current_function; 461 undef $current_function;
379 $current_function->{name} = $sym; 462 $current_function->{name} = $sym;
463 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
464 }
465 $line =~ s/\@abi\-omnipotent/\@function/;
466 $line =~ s/\@function.*/\@function/;
467 last;
468 };
469 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
470 $dir = ".byte";
471 $line = join(",",unpack("C*",$1),0);
380 } 472 }
381 last; 473 last;
382 }; 474 };
475 /\.rva|\.long|\.quad/
476 && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
477 $line =~ s/\.L/$decor/g;
478 last;
479 };
480 }
481
482 if ($gas) {
483 $self->{value} = $dir . "\t" . $line;
484
485 if ($dir =~ /\.extern/) {
486 $self->{value} = ""; # swallow extern
487 } elsif (!$elf && $dir =~ /\.type/) {
488 $self->{value} = "";
489 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
490 (defined($globals{$1})?".scl 2;":".scl 3;") .
491 "\t.type 32;\t.endef"
492 if ($win64 && $line =~ /([^,]+),\@function/);
493 } elsif (!$elf && $dir =~ /\.size/) {
494 $self->{value} = "";
495 if (defined($current_function)) {
496 $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
497 if ($win64 && $current_function->{abi} eq "svr4");
498 undef $current_function;
499 }
500 } elsif (!$elf && $dir =~ /\.align/) {
501 $self->{value} = ".p2align\t" . (log($line)/log(2));
502 } elsif ($dir eq ".section") {
503 $current_segment=$line;
504 if (!$elf && $current_segment eq ".init") {
505 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
506 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
507 }
508 } elsif ($dir =~ /\.(text|data)/) {
509 $current_segment=".$1";
510 }
511 $line = "";
512 return $self;
513 }
514
515 # non-gas case or nasm/masm
516 SWITCH: for ($dir) {
517 /\.text/ && do { my $v=undef;
518 if ($nasm) {
519 $v="section .text code align=64\n";
520 } else {
521 $v="$current_segment\tENDS\n" if ($current_segment);
522 $current_segment = ".text\$";
523 $v.="$current_segment\tSEGMENT ";
524 $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
525 $v.=" 'CODE'";
526 }
527 $self->{value} = $v;
528 last;
529 };
530 /\.data/ && do { my $v=undef;
531 if ($nasm) {
532 $v="section .data data align=8\n";
533 } else {
534 $v="$current_segment\tENDS\n" if ($current_segment);
535 $current_segment = "_DATA";
536 $v.="$current_segment\tSEGMENT";
537 }
538 $self->{value} = $v;
539 last;
540 };
541 /\.section/ && do { my $v=undef;
542 $line =~ s/([^,]*).*/$1/;
543 $line = ".CRT\$XCU" if ($line eq ".init");
544 if ($nasm) {
545 $v="section $line";
546 if ($line=~/\.([px])data/) {
547 $v.=" rdata align=";
548 $v.=$1 eq "p"? 4 : 8;
549 }
550 } else {
551 $v="$current_segment\tENDS\n" if ($current_segment);
552 $v.="$line\tSEGMENT";
553 if ($line=~/\.([px])data/) {
554 $v.=" READONLY";
555 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
556 }
557 }
558 $current_segment = $line;
559 $self->{value} = $v;
560 last;
561 };
562 /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
563 $self->{value} .= ":NEAR" if ($masm);
564 last;
565 };
566 /\.globl|.global/
567 && do { $self->{value} = $masm?"PUBLIC":"global";
568 $self->{value} .= "\t".$line;
569 last;
570 };
383 /\.size/ && do { if (defined($current_function)) { 571 /\.size/ && do { if (defined($current_function)) {
384 $self->{value}="$current_function->{name}\tENDP"; 572 undef $self->{value};
573 if ($current_function->{abi} eq "svr4") {
574 $self->{value}="${decor}SEH_end_$current_function->{name}:";
575 $self->{value}.=":\n" if($masm);
576 }
577 $self->{value}.="$current_function->{name}\tENDP" if($masm);
385 undef $current_function; 578 undef $current_function;
386 } 579 }
387 last; 580 last;
388 }; 581 };
389 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; }; 582 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
390 /\.(byte|value|long|quad)/ 583 /\.(value|long|rva|quad)/
391 && do { my @arr = split(',',$line); 584 && do { my $sz = substr($1,0,1);
392 my $sz = substr($1,0,1); 585 my @arr = split(/,\s*/,$line);
393 my $last = pop(@arr); 586 my $last = pop(@arr);
394 my $conv = sub { my $var=shift; 587 my $conv = sub { my $var=shift;
395 if ($var=~s/0x([0-9a-f]+)/0$1h/i) { $var; } 588 $var=~s/^(0b[0-1]+)/oct($1)/eig;
396 else { sprintf"0%Xh",$var; } 589 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
590 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
591 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
592 $var;
397 }; 593 };
398 594
399 $sz =~ tr/bvlq/BWDQ/; 595 $sz =~ tr/bvlrq/BWDDQ/;
400 $self->{value} = "\tD$sz\t"; 596 $self->{value} = "\tD$sz\t";
401 for (@arr) { $self->{value} .= &$conv($_).","; } 597 for (@arr) { $self->{value} .= &$conv($_).","; }
402 $self->{value} .= &$conv($last); 598 $self->{value} .= &$conv($last);
403 last; 599 last;
404 }; 600 };
405 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t 0%Xh,090000000h",$opcode{$line}; 601 /\.byte/ && do { my @str=split(/,\s*/,$line);
406 last; 602 map(s/(0b[0-1]+)/oct($1)/eig,@str);
407 }; 603 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
408 /\.asciz/ && do { if ($line =~ /^"(.*)"$/) { 604 while ($#str>15) {
409 my @str=unpack("C*",$1);
410 push @str,0;
411 while ($#str>15) {
412 $self->{value}.="DB\t"
413 .join(",",@str[0..15])."\n";
414 foreach (0..15) { shift @str; }
415 }
416 $self->{value}.="DB\t" 605 $self->{value}.="DB\t"
417 .join(",",@str) if (@str); 606 .join(",",@str[0..15])."\n";
607 foreach (0..15) { shift @str; }
418 } 608 }
609 $self->{value}.="DB\t"
610 .join(",",@str) if (@str);
419 last; 611 last;
420 }; 612 };
421 } 613 }
@@ -432,6 +624,15 @@ my $current_function;
432 624
433print "#include <machine/asm.h>\n"; 625print "#include <machine/asm.h>\n";
434 626
627if ($nasm) {
628 print <<___;
629default rel
630___
631} elsif ($masm) {
632 print <<___;
633OPTION DOTNAME
634___
635}
435while($line=<>) { 636while($line=<>) {
436 637
437 chomp($line); 638 chomp($line);
@@ -442,43 +643,42 @@ while($line=<>) {
442 643
443 undef $label; 644 undef $label;
444 undef $opcode; 645 undef $opcode;
445 undef $dst;
446 undef $src;
447 undef $sz; 646 undef $sz;
647 undef @args;
448 648
449 if ($label=label->re(\$line)) { print $label->out(); } 649 if ($label=label->re(\$line)) { print $label->out(); }
450 650
451 if (directive->re(\$line)) { 651 if (directive->re(\$line)) {
452 printf "%s",directive->out(); 652 printf "%s",directive->out();
453 } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: { 653 } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: while (1) {
454 654 my $arg;
455 if ($src=register->re(\$line)) { opcode->size($src->size()); }
456 elsif ($src=const->re(\$line)) { }
457 elsif ($src=ea->re(\$line)) { }
458 elsif ($src=expr->re(\$line)) { }
459 655
460 last ARGUMENT if ($line !~ /^,/); 656 if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
657 elsif ($arg=const->re(\$line)) { }
658 elsif ($arg=ea->re(\$line)) { }
659 elsif ($arg=expr->re(\$line)) { }
660 else { last ARGUMENT; }
461 661
462 $line = substr($line,1); $line =~ s/^\s+//; 662 push @args,$arg;
463 663
464 if ($dst=register->re(\$line)) { opcode->size($dst->size()); } 664 last ARGUMENT if ($line !~ /^,/);
465 elsif ($dst=const->re(\$line)) { }
466 elsif ($dst=ea->re(\$line)) { }
467 665
666 $line =~ s/^,\s*//;
468 } # ARGUMENT: 667 } # ARGUMENT:
469 668
470 $sz=opcode->size(); 669 $sz=opcode->size();
471 670
472 if (defined($dst)) { 671 if ($#args>=0) {
473 if (!$masm) { 672 my $insn;
474 printf "\t%s\t%s,%s", $opcode->out($dst->size()), 673 if ($gas) {
475 $src->out($sz),$dst->out($sz); 674 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
476 } else { 675 } else {
477 printf "\t%s\t%s,%s", $opcode->out(), 676 $insn = $opcode->out();
478 $dst->out($sz),$src->out($sz); 677 $insn .= $sz if (map($_->out() =~ /x?mm/,@args));
678 @args = reverse(@args);
679 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
479 } 680 }
480 } elsif (defined($src)) { 681 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
481 printf "\t%s\t%s",$opcode->out(),$src->out($sz);
482 } else { 682 } else {
483 printf "\t%s",$opcode->out(); 683 printf "\t%s",$opcode->out();
484 } 684 }
@@ -487,11 +687,12 @@ while($line=<>) {
487 print $line,"\n"; 687 print $line,"\n";
488} 688}
489 689
490print "\n$current_segment\tENDS\nEND\n" if ($masm); 690print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
691print "END\n" if ($masm);
491 692
492close STDOUT; 693close STDOUT;
493 694
494################################################# 695 #################################################
495# Cross-reference x86_64 ABI "card" 696# Cross-reference x86_64 ABI "card"
496# 697#
497# Unix Win64 698# Unix Win64
@@ -555,3 +756,161 @@ close STDOUT;
555# movq 16(%rsp),%rsi 756# movq 16(%rsp),%rsi
556# endif 757# endif
557# ret 758# ret
759#
760 #################################################
761# Win64 SEH, Structured Exception Handling.
762#
763# Unlike on Unix systems(*) lack of Win64 stack unwinding information
764# has undesired side-effect at run-time: if an exception is raised in
765# assembler subroutine such as those in question (basically we're
766# referring to segmentation violations caused by malformed input
767# parameters), the application is briskly terminated without invoking
768# any exception handlers, most notably without generating memory dump
769# or any user notification whatsoever. This poses a problem. It's
770# possible to address it by registering custom language-specific
771# handler that would restore processor context to the state at
772# subroutine entry point and return "exception is not handled, keep
773# unwinding" code. Writing such handler can be a challenge... But it's
774# doable, though requires certain coding convention. Consider following
775# snippet:
776#
777# .type function,@function
778# function:
779# movq %rsp,%rax # copy rsp to volatile register
780# pushq %r15 # save non-volatile registers
781# pushq %rbx
782# pushq %rbp
783# movq %rsp,%r11
784# subq %rdi,%r11 # prepare [variable] stack frame
785# andq $-64,%r11
786# movq %rax,0(%r11) # check for exceptions
787# movq %r11,%rsp # allocate [variable] stack frame
788# movq %rax,0(%rsp) # save original rsp value
789# magic_point:
790# ...
791# movq 0(%rsp),%rcx # pull original rsp value
792# movq -24(%rcx),%rbp # restore non-volatile registers
793# movq -16(%rcx),%rbx
794# movq -8(%rcx),%r15
795# movq %rcx,%rsp # restore original rsp
796# ret
797# .size function,.-function
798#
799# The key is that up to magic_point copy of original rsp value remains
800# in chosen volatile register and no non-volatile register, except for
801# rsp, is modified. While past magic_point rsp remains constant till
802# the very end of the function. In this case custom language-specific
803# exception handler would look like this:
804#
805# EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
806# CONTEXT *context,DISPATCHER_CONTEXT *disp)
807# { ULONG64 *rsp = (ULONG64 *)context->Rax;
808# if (context->Rip >= magic_point)
809# { rsp = ((ULONG64 **)context->Rsp)[0];
810# context->Rbp = rsp[-3];
811# context->Rbx = rsp[-2];
812# context->R15 = rsp[-1];
813# }
814# context->Rsp = (ULONG64)rsp;
815# context->Rdi = rsp[1];
816# context->Rsi = rsp[2];
817#
818# memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
819# RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
820# dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
821# &disp->HandlerData,&disp->EstablisherFrame,NULL);
822# return ExceptionContinueSearch;
823# }
824#
825# It's appropriate to implement this handler in assembler, directly in
826# function's module. In order to do that one has to know members'
827# offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
828# values. Here they are:
829#
830# CONTEXT.Rax 120
831# CONTEXT.Rcx 128
832# CONTEXT.Rdx 136
833# CONTEXT.Rbx 144
834# CONTEXT.Rsp 152
835# CONTEXT.Rbp 160
836# CONTEXT.Rsi 168
837# CONTEXT.Rdi 176
838# CONTEXT.R8 184
839# CONTEXT.R9 192
840# CONTEXT.R10 200
841# CONTEXT.R11 208
842# CONTEXT.R12 216
843# CONTEXT.R13 224
844# CONTEXT.R14 232
845# CONTEXT.R15 240
846# CONTEXT.Rip 248
847# CONTEXT.Xmm6 512
848# sizeof(CONTEXT) 1232
849# DISPATCHER_CONTEXT.ControlPc 0
850# DISPATCHER_CONTEXT.ImageBase 8
851# DISPATCHER_CONTEXT.FunctionEntry 16
852# DISPATCHER_CONTEXT.EstablisherFrame 24
853# DISPATCHER_CONTEXT.TargetIp 32
854# DISPATCHER_CONTEXT.ContextRecord 40
855# DISPATCHER_CONTEXT.LanguageHandler 48
856# DISPATCHER_CONTEXT.HandlerData 56
857# UNW_FLAG_NHANDLER 0
858# ExceptionContinueSearch 1
859#
860# In order to tie the handler to the function one has to compose
861# couple of structures: one for .xdata segment and one for .pdata.
862#
863# UNWIND_INFO structure for .xdata segment would be
864#
865# function_unwind_info:
866# .byte 9,0,0,0
867# .rva handler
868#
869# This structure designates exception handler for a function with
870# zero-length prologue, no stack frame or frame register.
871#
872# To facilitate composing of .pdata structures, auto-generated "gear"
873# prologue copies rsp value to rax and denotes next instruction with
874# .LSEH_begin_{function_name} label. This essentially defines the SEH
875# styling rule mentioned in the beginning. Position of this label is
876# chosen in such manner that possible exceptions raised in the "gear"
877# prologue would be accounted to caller and unwound from latter's frame.
878# End of function is marked with respective .LSEH_end_{function_name}
879# label. To summarize, .pdata segment would contain
880#
881# .rva .LSEH_begin_function
882# .rva .LSEH_end_function
883# .rva function_unwind_info
884#
885# Reference to functon_unwind_info from .xdata segment is the anchor.
886# In case you wonder why references are 32-bit .rvas and not 64-bit
887# .quads. References put into these two segments are required to be
888# *relative* to the base address of the current binary module, a.k.a.
889# image base. No Win64 module, be it .exe or .dll, can be larger than
890# 2GB and thus such relative references can be and are accommodated in
891# 32 bits.
892#
893# Having reviewed the example function code, one can argue that "movq
894# %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
895# rax would contain an undefined value. If this "offends" you, use
896# another register and refrain from modifying rax till magic_point is
897# reached, i.e. as if it was a non-volatile register. If more registers
898# are required prior [variable] frame setup is completed, note that
899# nobody says that you can have only one "magic point." You can
900# "liberate" non-volatile registers by denoting last stack off-load
901# instruction and reflecting it in finer grade unwind logic in handler.
902# After all, isn't it why it's called *language-specific* handler...
903#
904# Attentive reader can notice that exceptions would be mishandled in
905# auto-generated "gear" epilogue. Well, exception effectively can't
906# occur there, because if memory area used by it was subject to
907# segmentation violation, then it would be raised upon call to the
908# function (and as already mentioned be accounted to caller, which is
909# not a problem). If you're still not comfortable, then define tail
910# "magic point" just prior ret instruction and have handler treat it...
911#
912# (*) Note that we're talking about run-time, not debug-time. Lack of
913# unwind information makes debugging hard on both Windows and
914# Unix. "Unlike" referes to the fact that on Unix signal handler
915# will always be invoked, core dumped and appropriate exit code
916# returned to parent (for user notification).