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