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 62 my $flavour = shift; 63 my $output = shift; 64 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } 65 66 { my ($stddev,$stdino,@junk)=stat(STDOUT); 67 my ($outdev,$outino,@junk)=stat($output); 68 69 open STDOUT,">$output" || die "can't open $output: $!" 70 if ($stddev!=$outdev || $stdino!=$outino); 71 } 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 chomp($prefix); 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 $current_segment; 105 my $current_function; 106 my %globals; 107 108 { package opcode; # pick up opcodes 109 sub re { 110 my $self = shift; # single instance in enough... 111 local *line = shift; 112 undef $ret; 113 114 if ($line =~ /^([a-z][a-z0-9]*)/i) { 115 $self->{op} = $1; 116 $ret = $self; 117 $line = substr($line,@+[0]); $line =~ s/^\s+//; 118 119 undef $self->{sz}; 120 if ($self->{op} =~ /^(movz)b.*/) { # movz is pain... 121 $self->{op} = $1; 122 $self->{sz} = "b"; 123 } elsif ($self->{op} =~ /call|jmp/) { 124 $self->{sz} = ""; 125 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op)/) { # SSEn 126 $self->{sz} = ""; 127 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) { 128 $self->{op} = $1; 129 $self->{sz} = $2; 130 } 131 } 132 $ret; 133 } 134 sub size { 135 my $self = shift; 136 my $sz = shift; 137 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz})); 138 $self->{sz}; 139 } 140 sub out { 141 my $self = shift; 142 if ($gas) { 143 if ($self->{op} eq "movz") { # movz is pain... 144 sprintf "%s%s%s",$self->{op},$self->{sz},shift; 145 } elsif ($self->{op} =~ /^set/) { 146 "$self->{op}"; 147 } elsif ($self->{op} eq "ret") { 148 my $epilogue = ""; 149 if ($win64 && $current_function->{abi} eq "svr4") { 150 $epilogue = "movq 8(%rsp),%rdi\n\t" . 151 "movq 16(%rsp),%rsi\n\t"; 152 } 153 $epilogue . ".byte 0xf3,0xc3"; 154 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") { 155 ".p2align\t3\n\t.quad"; 156 } else { 157 "$self->{op}$self->{sz}"; 158 } 159 } else { 160 $self->{op} =~ s/^movz/movzx/; 161 if ($self->{op} eq "ret") { 162 $self->{op} = ""; 163 if ($win64 && $current_function->{abi} eq "svr4") { 164 $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t". 165 "mov rsi,QWORD${PTR}[16+rsp]\n\t"; 166 } 167 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret"; 168 } elsif ($self->{op} =~ /^(pop|push)f/) { 169 $self->{op} .= $self->{sz}; 170 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") { 171 $self->{op} = "\tDQ"; 172 } 173 $self->{op}; 174 } 175 } 176 sub mnemonic { 177 my $self=shift; 178 my $op=shift; 179 $self->{op}=$op if (defined($op)); 180 $self->{op}; 181 } 182 } 183 { package const; # pick up constants, which start with $ 184 sub re { 185 my $self = shift; # single instance in enough... 186 local *line = shift; 187 undef $ret; 188 189 if ($line =~ /^\$([^,]+)/) { 190 $self->{value} = $1; 191 $ret = $self; 192 $line = substr($line,@+[0]); $line =~ s/^\s+//; 193 } 194 $ret; 195 } 196 sub out { 197 my $self = shift; 198 199 if ($gas) { 200 # Solaris /usr/ccs/bin/as can't handle multiplications 201 # in $self->{value} 202 $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi; 203 $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg; 204 sprintf "\$%s",$self->{value}; 205 } else { 206 $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig; 207 $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm); 208 sprintf "%s",$self->{value}; 209 } 210 } 211 } 212 { package ea; # pick up effective addresses: expr(%reg,%reg,scale) 213 sub re { 214 my $self = shift; # single instance in enough... 215 local *line = shift; 216 undef $ret; 217 218 # optional * ---vvv--- appears in indirect jmp/call 219 if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) { 220 $self->{asterisk} = $1; 221 $self->{label} = $2; 222 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3); 223 $self->{scale} = 1 if (!defined($self->{scale})); 224 $ret = $self; 225 $line = substr($line,@+[0]); $line =~ s/^\s+//; 226 227 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) { 228 die if (opcode->mnemonic() ne "mov"); 229 opcode->mnemonic("lea"); 230 } 231 $self->{base} =~ s/^%//; 232 $self->{index} =~ s/^%// if (defined($self->{index})); 233 } 234 $ret; 235 } 236 sub size {} 237 sub out { 238 my $self = shift; 239 my $sz = shift; 240 241 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei; 242 $self->{label} =~ s/\.L/$decor/g; 243 244 # Silently convert all EAs to 64-bit. This is required for 245 # elder GNU assembler and results in more compact code, 246 # *but* most importantly AES module depends on this feature! 247 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/; 248 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/; 249 250 if ($gas) { 251 # Solaris /usr/ccs/bin/as can't handle multiplications 252 # in $self->{label}, new gas requires sign extension... 253 use integer; 254 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi; 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"); 258 259 if (defined($self->{index})) { 260 sprintf "%s%s(%%%s,%%%s,%d)",$self->{asterisk}, 261 $self->{label},$self->{base}, 262 $self->{index},$self->{scale}; 263 } else { 264 sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base}; 265 } 266 } else { 267 %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" ); 268 269 $self->{label} =~ s/\./\$/g; 270 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig; 271 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/); 272 $sz="q" if ($self->{asterisk}); 273 274 if (defined($self->{index})) { 275 sprintf "%s[%s%s*%d+%s]",$szmap{$sz}, 276 $self->{label}?"$self->{label}+":"", 277 $self->{index},$self->{scale}, 278 $self->{base}; 279 } elsif ($self->{base} eq "rip") { 280 sprintf "%s[%s]",$szmap{$sz},$self->{label}; 281 } else { 282 sprintf "%s[%s%s]",$szmap{$sz}, 283 $self->{label}?"$self->{label}+":"", 284 $self->{base}; 285 } 286 } 287 } 288 } 289 { package register; # pick up registers, which start with %. 290 sub re { 291 my $class = shift; # muliple instances... 292 my $self = {}; 293 local *line = shift; 294 undef $ret; 295 296 # optional * ---vvv--- appears in indirect jmp/call 297 if ($line =~ /^(\*?)%(\w+)/) { 298 bless $self,$class; 299 $self->{asterisk} = $1; 300 $self->{value} = $2; 301 $ret = $self; 302 $line = substr($line,@+[0]); $line =~ s/^\s+//; 303 } 304 $ret; 305 } 306 sub size { 307 my $self = shift; 308 undef $ret; 309 310 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; } 311 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; } 312 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; } 313 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; } 314 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; } 315 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; } 316 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; } 317 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; } 318 319 $ret; 320 } 321 sub out { 322 my $self = shift; 323 if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; } 324 else { $self->{value}; } 325 } 326 } 327 { package label; # pick up labels, which end with : 328 sub re { 329 my $self = shift; # single instance is enough... 330 local *line = shift; 331 undef $ret; 332 333 if ($line =~ /(^[\.\w]+)\:/) { 334 $self->{value} = $1; 335 $ret = $self; 336 $line = substr($line,@+[0]); $line =~ s/^\s+//; 337 338 $self->{value} =~ s/^\.L/$decor/; 339 } 340 $ret; 341 } 342 sub out { 343 my $self = shift; 344 345 if ($gas) { 346 my $func = ($globals{$self->{value}} or $self->{value}) . ":"; 347 if ($win64 && 348 $current_function->{name} eq $self->{value} && 349 $current_function->{abi} eq "svr4") { 350 $func .= "\n"; 351 $func .= " movq %rdi,8(%rsp)\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"; 378 my $narg = $current_function->{narg}; 379 $narg=6 if (!defined($narg)); 380 $func .= " mov rdi,rcx\n" if ($narg>0); 381 $func .= " mov rsi,rdx\n" if ($narg>1); 382 $func .= " mov rdx,r8\n" if ($narg>2); 383 $func .= " mov rcx,r9\n" if ($narg>3); 384 $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4); 385 $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5); 386 $func .= "\n"; 387 } else { 388 "$current_function->{name}". 389 ($nasm ? ":" : "\tPROC $current_function->{scope}"); 390 } 391 } 392 } 393 { package expr; # pick up expressioins 394 sub re { 395 my $self = shift; # single instance is enough... 396 local *line = shift; 397 undef $ret; 398 399 if ($line =~ /(^[^,]+)/) { 400 $self->{value} = $1; 401 $ret = $self; 402 $line = substr($line,@+[0]); $line =~ s/^\s+//; 403 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; 407 } 408 $ret; 409 } 410 sub out { 411 my $self = shift; 412 if ($nasm && opcode->mnemonic()=~m/^j/) { 413 "NEAR ".$self->{value}; 414 } else { 415 $self->{value}; 416 } 417 } 418 } 419 { package directive; # pick up directives, which start with . 420 sub re { 421 my $self = shift; # single instance is enough... 422 local *line = shift; 423 undef $ret; 424 my $dir; 425 my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2: 426 ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48, 427 "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48, 428 "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48, 429 "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48, 430 "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c, 431 "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c, 432 "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c, 433 "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c ); 434 435 if ($line =~ /^\s*(\.\w+)/) { 436 $dir = $1; 437 $ret = $self; 438 undef $self->{value}; 439 $line = substr($line,@+[0]); $line =~ s/^\s+//; 440 441 SWITCH: for ($dir) { 442 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) { 443 $dir="\t.long"; 444 $line=sprintf "0x%x,0x90000000",$opcode{$1}; 445 } 446 last; 447 }; 448 /\.global|\.globl|\.extern/ 449 && do { $globals{$line} = $prefix . $line; 450 $line = $globals{$line} if ($prefix); 451 last; 452 }; 453 /\.type/ && do { ($sym,$type,$narg) = split(',',$line); 454 if ($type eq "\@function") { 455 undef $current_function; 456 $current_function->{name} = $sym; 457 $current_function->{abi} = "svr4"; 458 $current_function->{narg} = $narg; 459 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE"; 460 } elsif ($type eq "\@abi-omnipotent") { 461 undef $current_function; 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); 472 } 473 last; 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 } elsif ($line=~/\.CRT\$/i) { 550 $v.=" rdata align=8"; 551 } 552 } else { 553 $v="$current_segment\tENDS\n" if ($current_segment); 554 $v.="$line\tSEGMENT"; 555 if ($line=~/\.([px])data/) { 556 $v.=" READONLY"; 557 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref); 558 } elsif ($line=~/\.CRT\$/i) { 559 $v.=" READONLY DWORD"; 560 } 561 } 562 $current_segment = $line; 563 $self->{value} = $v; 564 last; 565 }; 566 /\.extern/ && do { $self->{value} = "EXTERN\t".$line; 567 $self->{value} .= ":NEAR" if ($masm); 568 last; 569 }; 570 /\.globl|.global/ 571 && do { $self->{value} = $masm?"PUBLIC":"global"; 572 $self->{value} .= "\t".$line; 573 last; 574 }; 575 /\.size/ && do { if (defined($current_function)) { 576 undef $self->{value}; 577 if ($current_function->{abi} eq "svr4") { 578 $self->{value}="${decor}SEH_end_$current_function->{name}:"; 579 $self->{value}.=":\n" if($masm); 580 } 581 $self->{value}.="$current_function->{name}\tENDP" if($masm); 582 undef $current_function; 583 } 584 last; 585 }; 586 /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; }; 587 /\.(value|long|rva|quad)/ 588 && do { my $sz = substr($1,0,1); 589 my @arr = split(/,\s*/,$line); 590 my $last = pop(@arr); 591 my $conv = sub { my $var=shift; 592 $var=~s/^(0b[0-1]+)/oct($1)/eig; 593 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm); 594 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva")) 595 { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; } 596 $var; 597 }; 598 599 $sz =~ tr/bvlrq/BWDDQ/; 600 $self->{value} = "\tD$sz\t"; 601 for (@arr) { $self->{value} .= &$conv($_).","; } 602 $self->{value} .= &$conv($last); 603 last; 604 }; 605 /\.byte/ && do { my @str=split(/,\s*/,$line); 606 map(s/(0b[0-1]+)/oct($1)/eig,@str); 607 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm); 608 while ($#str>15) { 609 $self->{value}.="DB\t" 610 .join(",",@str[0..15])."\n"; 611 foreach (0..15) { shift @str; } 612 } 613 $self->{value}.="DB\t" 614 .join(",",@str) if (@str); 615 last; 616 }; 617 } 618 $line = ""; 619 } 620 621 $ret; 622 } 623 sub out { 624 my $self = shift; 625 $self->{value}; 626 } 627 } 628 629 if ($nasm) { 630 print <<___; 631 default rel 632 ___ 633 } elsif ($masm) { 634 print <<___; 635 OPTION DOTNAME 636 ___ 637 } 638 while($line=<>) { 639 640 chomp($line); 641 642 $line =~ s|[#!].*$||; # get rid of asm-style comments... 643 $line =~ s|/\*.*\*/||; # ... and C-style comments... 644 $line =~ s|^\s+||; # ... and skip white spaces in beginning 645 646 undef $label; 647 undef $opcode; 648 undef $sz; 649 undef @args; 650 651 if ($label=label->re(\$line)) { print $label->out(); } 652 653 if (directive->re(\$line)) { 654 printf "%s",directive->out(); 655 } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: while (1) { 656 my $arg; 657 658 if ($arg=register->re(\$line)) { opcode->size($arg->size()); } 659 elsif ($arg=const->re(\$line)) { } 660 elsif ($arg=ea->re(\$line)) { } 661 elsif ($arg=expr->re(\$line)) { } 662 else { last ARGUMENT; } 663 664 push @args,$arg; 665 666 last ARGUMENT if ($line !~ /^,/); 667 668 $line =~ s/^,\s*//; 669 } # ARGUMENT: 670 671 $sz=opcode->size(); 672 673 if ($#args>=0) { 674 my $insn; 675 if ($gas) { 676 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz); 677 } else { 678 $insn = $opcode->out(); 679 $insn .= $sz if (map($_->out() =~ /x?mm/,@args)); 680 @args = reverse(@args); 681 undef $sz if ($nasm && $opcode->mnemonic() eq "lea"); 682 } 683 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args)); 684 } else { 685 printf "\t%s",$opcode->out(); 686 } 687 } 688 689 print $line,"\n"; 690 } 691 692 print "\n$current_segment\tENDS\n" if ($current_segment && $masm); 693 print "END\n" if ($masm); 694 695 close STDOUT; 696 697 ################################################# 699 # Cross-reference x86_64 ABI "card" 700 # 701 # Unix Win64 702 # %rax * * 703 # %rbx - - 704 # %rcx #4 #1 705 # %rdx #3 #2 706 # %rsi #2 - 707 # %rdi #1 - 708 # %rbp - - 709 # %rsp - - 710 # %r8 #5 #3 711 # %r9 #6 #4 712 # %r10 * * 713 # %r11 * * 714 # %r12 - - 715 # %r13 - - 716 # %r14 - - 717 # %r15 - - 718 # 719 # (*) volatile register 720 # (-) preserved by callee 721 # (#) Nth argument, volatile 722 # 723 # In Unix terms top of stack is argument transfer area for arguments 724 # which could not be accomodated in registers. Or in other words 7th 725 # [integer] argument resides at 8(%rsp) upon function entry point. 726 # 128 bytes above %rsp constitute a "red zone" which is not touched 727 # by signal handlers and can be used as temporal storage without 728 # allocating a frame. 729 # 730 # In Win64 terms N*8 bytes on top of stack is argument transfer area, 731 # which belongs to/can be overwritten by callee. N is the number of 732 # arguments passed to callee, *but* not less than 4! This means that 733 # upon function entry point 5th argument resides at 40(%rsp), as well 734 # as that 32 bytes from 8(%rsp) can always be used as temporal 735 # storage [without allocating a frame]. One can actually argue that 736 # one can assume a "red zone" above stack pointer under Win64 as well. 737 # Point is that at apparently no occasion Windows kernel would alter 738 # the area above user stack pointer in true asynchronous manner... 739 # 740 # All the above means that if assembler programmer adheres to Unix 741 # register and stack layout, but disregards the "red zone" existense, 742 # it's possible to use following prologue and epilogue to "gear" from 743 # Unix to Win64 ABI in leaf functions with not more than 6 arguments. 744 # 745 # omnipotent_function: 746 # ifdef WIN64 747 # movq %rdi,8(%rsp) 748 # movq %rsi,16(%rsp) 749 # movq %rcx,%rdi ; if 1st argument is actually present 750 # movq %rdx,%rsi ; if 2nd argument is actually ... 751 # movq %r8,%rdx ; if 3rd argument is ... 752 # movq %r9,%rcx ; if 4th argument ... 753 # movq 40(%rsp),%r8 ; if 5th ... 754 # movq 48(%rsp),%r9 ; if 6th ... 755 # endif 756 # ... 757 # ifdef WIN64 758 # movq 8(%rsp),%rdi 759 # movq 16(%rsp),%rsi 760 # endif 761 # ret 762 # 763 ################################################# 765 # Win64 SEH, Structured Exception Handling. 766 # 767 # Unlike on Unix systems(*) lack of Win64 stack unwinding information 768 # has undesired side-effect at run-time: if an exception is raised in 769 # assembler subroutine such as those in question (basically we're 770 # referring to segmentation violations caused by malformed input 771 # parameters), the application is briskly terminated without invoking 772 # any exception handlers, most notably without generating memory dump 773 # or any user notification whatsoever. This poses a problem. It's 774 # possible to address it by registering custom language-specific 775 # handler that would restore processor context to the state at 776 # subroutine entry point and return "exception is not handled, keep 777 # unwinding" code. Writing such handler can be a challenge... But it's 778 # doable, though requires certain coding convention. Consider following 779 # snippet: 780 # 781 # .type function,@function 782 # function: 783 # movq %rsp,%rax # copy rsp to volatile register 784 # pushq %r15 # save non-volatile registers 785 # pushq %rbx 786 # pushq %rbp 787 # movq %rsp,%r11 788 # subq %rdi,%r11 # prepare [variable] stack frame 789 # andq $-64,%r11 790 # movq %rax,0(%r11) # check for exceptions 791 # movq %r11,%rsp # allocate [variable] stack frame 792 # movq %rax,0(%rsp) # save original rsp value 793 # magic_point: 794 # ... 795 # movq 0(%rsp),%rcx # pull original rsp value 796 # movq -24(%rcx),%rbp # restore non-volatile registers 797 # movq -16(%rcx),%rbx 798 # movq -8(%rcx),%r15 799 # movq %rcx,%rsp # restore original rsp 800 # ret 801 # .size function,.-function 802 # 803 # The key is that up to magic_point copy of original rsp value remains 804 # in chosen volatile register and no non-volatile register, except for 805 # rsp, is modified. While past magic_point rsp remains constant till 806 # the very end of the function. In this case custom language-specific 807 # exception handler would look like this: 808 # 809 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, 810 # CONTEXT *context,DISPATCHER_CONTEXT *disp) 811 # { ULONG64 *rsp = (ULONG64 *)context->Rax; 812 # if (context->Rip >= magic_point) 813 # { rsp = ((ULONG64 **)context->Rsp)[0]; 814 # context->Rbp = rsp[-3]; 815 # context->Rbx = rsp[-2]; 816 # context->R15 = rsp[-1]; 817 # } 818 # context->Rsp = (ULONG64)rsp; 819 # context->Rdi = rsp[1]; 820 # context->Rsi = rsp[2]; 821 # 822 # memcpy (disp->ContextRecord,context,sizeof(CONTEXT)); 823 # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase, 824 # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord, 825 # &disp->HandlerData,&disp->EstablisherFrame,NULL); 826 # return ExceptionContinueSearch; 827 # } 828 # 829 # It's appropriate to implement this handler in assembler, directly in 830 # function's module. In order to do that one has to know members' 831 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant 832 # values. Here they are: 833 # 834 # CONTEXT.Rax 120 835 # CONTEXT.Rcx 128 836 # CONTEXT.Rdx 136 837 # CONTEXT.Rbx 144 838 # CONTEXT.Rsp 152 839 # CONTEXT.Rbp 160 840 # CONTEXT.Rsi 168 841 # CONTEXT.Rdi 176 842 # CONTEXT.R8 184 843 # CONTEXT.R9 192 844 # CONTEXT.R10 200 845 # CONTEXT.R11 208 846 # CONTEXT.R12 216 847 # CONTEXT.R13 224 848 # CONTEXT.R14 232 849 # CONTEXT.R15 240 850 # CONTEXT.Rip 248 851 # CONTEXT.Xmm6 512 852 # sizeof(CONTEXT) 1232 853 # DISPATCHER_CONTEXT.ControlPc 0 854 # DISPATCHER_CONTEXT.ImageBase 8 855 # DISPATCHER_CONTEXT.FunctionEntry 16 856 # DISPATCHER_CONTEXT.EstablisherFrame 24 857 # DISPATCHER_CONTEXT.TargetIp 32 858 # DISPATCHER_CONTEXT.ContextRecord 40 859 # DISPATCHER_CONTEXT.LanguageHandler 48 860 # DISPATCHER_CONTEXT.HandlerData 56 861 # UNW_FLAG_NHANDLER 0 862 # ExceptionContinueSearch 1 863 # 864 # In order to tie the handler to the function one has to compose 865 # couple of structures: one for .xdata segment and one for .pdata. 866 # 867 # UNWIND_INFO structure for .xdata segment would be 868 # 869 # function_unwind_info: 870 # .byte 9,0,0,0 871 # .rva handler 872 # 873 # This structure designates exception handler for a function with 874 # zero-length prologue, no stack frame or frame register. 875 # 876 # To facilitate composing of .pdata structures, auto-generated "gear" 877 # prologue copies rsp value to rax and denotes next instruction with 878 # .LSEH_begin_{function_name} label. This essentially defines the SEH 879 # styling rule mentioned in the beginning. Position of this label is 880 # chosen in such manner that possible exceptions raised in the "gear" 881 # prologue would be accounted to caller and unwound from latter's frame. 882 # End of function is marked with respective .LSEH_end_{function_name} 883 # label. To summarize, .pdata segment would contain 884 # 885 # .rva .LSEH_begin_function 886 # .rva .LSEH_end_function 887 # .rva function_unwind_info 888 # 889 # Reference to functon_unwind_info from .xdata segment is the anchor. 890 # In case you wonder why references are 32-bit .rvas and not 64-bit 891 # .quads. References put into these two segments are required to be 892 # *relative* to the base address of the current binary module, a.k.a. 893 # image base. No Win64 module, be it .exe or .dll, can be larger than 894 # 2GB and thus such relative references can be and are accommodated in 895 # 32 bits. 896 # 897 # Having reviewed the example function code, one can argue that "movq 898 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix 899 # rax would contain an undefined value. If this "offends" you, use 900 # another register and refrain from modifying rax till magic_point is 901 # reached, i.e. as if it was a non-volatile register. If more registers 902 # are required prior [variable] frame setup is completed, note that 903 # nobody says that you can have only one "magic point." You can 904 # "liberate" non-volatile registers by denoting last stack off-load 905 # instruction and reflecting it in finer grade unwind logic in handler. 906 # After all, isn't it why it's called *language-specific* handler... 907 # 908 # Attentive reader can notice that exceptions would be mishandled in 909 # auto-generated "gear" epilogue. Well, exception effectively can't 910 # occur there, because if memory area used by it was subject to 911 # segmentation violation, then it would be raised upon call to the 912 # function (and as already mentioned be accounted to caller, which is 913 # not a problem). If you're still not comfortable, then define tail 914 # "magic point" just prior ret instruction and have handler treat it... 915 # 916 # (*) Note that we're talking about run-time, not debug-time. Lack of 917 # unwind information makes debugging hard on both Windows and 918 # Unix. "Unlike" referes to the fact that on Unix signal handler 919 # will always be invoked, core dumped and appropriate exit code 920 # returned to parent (for user notification). 921