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