1#! /usr/bin/env perl 2# Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved. 3# 4# Licensed under the OpenSSL license (the "License"). You may not use 5# this file except in compliance with the License. You can obtain a copy 6# in the file LICENSE in the source distribution or at 7# https://www.openssl.org/source/license.html 8 9 10# Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>. 11# 12# Why AT&T to MASM and not vice versa? Several reasons. Because AT&T 13# format is way easier to parse. Because it's simpler to "gear" from 14# Unix ABI to Windows one [see cross-reference "card" at the end of 15# file]. Because Linux targets were available first... 16# 17# In addition the script also "distills" code suitable for GNU 18# assembler, so that it can be compiled with more rigid assemblers, 19# such as Solaris /usr/ccs/bin/as. 20# 21# This translator is not designed to convert *arbitrary* assembler 22# code from AT&T format to MASM one. It's designed to convert just 23# enough to provide for dual-ABI OpenSSL modules development... 24# There *are* limitations and you might have to modify your assembler 25# code or this script to achieve the desired result... 26# 27# Currently recognized limitations: 28# 29# - can't use multiple ops per line; 30# 31# Dual-ABI styling rules. 32# 33# 1. Adhere to Unix register and stack layout [see cross-reference 34# ABI "card" at the end for explanation]. 35# 2. Forget about "red zone," stick to more traditional blended 36# stack frame allocation. If volatile storage is actually required 37# that is. If not, just leave the stack as is. 38# 3. Functions tagged with ".type name,@function" get crafted with 39# unified Win64 prologue and epilogue automatically. If you want 40# to take care of ABI differences yourself, tag functions as 41# ".type name,@abi-omnipotent" instead. 42# 4. To optimize the Win64 prologue you can specify number of input 43# arguments as ".type name,@function,N." Keep in mind that if N is 44# larger than 6, then you *have to* write "abi-omnipotent" code, 45# because >6 cases can't be addressed with unified prologue. 46# 5. Name local labels as .L*, do *not* use dynamic labels such as 1: 47# (sorry about latter). 48# 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is 49# required to identify the spots, where to inject Win64 epilogue! 50# But on the pros, it's then prefixed with rep automatically:-) 51# 7. Stick to explicit ip-relative addressing. If you have to use 52# GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??. 53# Both are recognized and translated to proper Win64 addressing 54# modes. 55# 56# 8. In order to provide for structured exception handling unified 57# Win64 prologue copies %rsp value to %rax. For further details 58# see SEH paragraph at the end. 59# 9. .init segment is allowed to contain calls to functions only. 60# a. If function accepts more than 4 arguments *and* >4th argument 61# is declared as non 64-bit value, do clear its upper part. 62 63 64use strict; 65 66my $flavour = shift; 67my $output = shift; 68if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } 69 70open STDOUT,">$output" || die "can't open $output: $!" 71 if (defined($output)); 72 73my $gas=1; $gas=0 if ($output =~ /\.asm$/); 74my $elf=1; $elf=0 if (!$gas); 75my $win64=0; 76my $prefix=""; 77my $decor=".L"; 78 79my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005 80my $masm=0; 81my $PTR=" PTR"; 82 83my $nasmref=2.03; 84my $nasm=0; 85 86if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1; 87 $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`; 88 $prefix =~ s|\R$||; # Better chomp 89 } 90elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; } 91elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; } 92elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; } 93elsif (!$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 104my $current_segment; 105my $current_function; 106my %globals; 107 108{ package opcode; # pick up opcodes 109 sub re { 110 my ($class, $line) = @_; 111 my $self = {}; 112 my $ret; 113 114 if ($$line =~ /^([a-z][a-z0-9]*)/i) { 115 bless $self,$class; 116 $self->{op} = $1; 117 $ret = $self; 118 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 119 120 undef $self->{sz}; 121 if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain... 122 $self->{op} = $1; 123 $self->{sz} = $2; 124 } elsif ($self->{op} =~ /call|jmp/) { 125 $self->{sz} = ""; 126 } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn 127 $self->{sz} = ""; 128 } elsif ($self->{op} =~ /^[vk]/) { # VEX or k* such as kmov 129 $self->{sz} = ""; 130 } elsif ($self->{op} =~ /mov[dq]/ && $$line =~ /%xmm/) { 131 $self->{sz} = ""; 132 } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) { 133 $self->{op} = $1; 134 $self->{sz} = $2; 135 } 136 } 137 $ret; 138 } 139 sub size { 140 my ($self, $sz) = @_; 141 $self->{sz} = $sz if (defined($sz) && !defined($self->{sz})); 142 $self->{sz}; 143 } 144 sub out { 145 my $self = shift; 146 if ($gas) { 147 if ($self->{op} eq "movz") { # movz is pain... 148 sprintf "%s%s%s",$self->{op},$self->{sz},shift; 149 } elsif ($self->{op} =~ /^set/) { 150 "$self->{op}"; 151 } elsif ($self->{op} eq "ret") { 152 my $epilogue = ""; 153 if ($win64 && $current_function->{abi} eq "svr4") { 154 $epilogue = "movq 8(%rsp),%rdi\n\t" . 155 "movq 16(%rsp),%rsi\n\t"; 156 } 157 $epilogue . ".byte 0xf3,0xc3"; 158 } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") { 159 ".p2align\t3\n\t.quad"; 160 } else { 161 "$self->{op}$self->{sz}"; 162 } 163 } else { 164 $self->{op} =~ s/^movz/movzx/; 165 if ($self->{op} eq "ret") { 166 $self->{op} = ""; 167 if ($win64 && $current_function->{abi} eq "svr4") { 168 $self->{op} = "mov rdi,QWORD$PTR\[8+rsp\]\t;WIN64 epilogue\n\t". 169 "mov rsi,QWORD$PTR\[16+rsp\]\n\t"; 170 } 171 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret"; 172 } elsif ($self->{op} =~ /^(pop|push)f/) { 173 $self->{op} .= $self->{sz}; 174 } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") { 175 $self->{op} = "\tDQ"; 176 } 177 $self->{op}; 178 } 179 } 180 sub mnemonic { 181 my ($self, $op) = @_; 182 $self->{op}=$op if (defined($op)); 183 $self->{op}; 184 } 185} 186{ package const; # pick up constants, which start with $ 187 sub re { 188 my ($class, $line) = @_; 189 my $self = {}; 190 my $ret; 191 192 if ($$line =~ /^\$([^,]+)/) { 193 bless $self, $class; 194 $self->{value} = $1; 195 $ret = $self; 196 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 197 } 198 $ret; 199 } 200 sub out { 201 my $self = shift; 202 203 $self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig; 204 if ($gas) { 205 # Solaris /usr/ccs/bin/as can't handle multiplications 206 # in $self->{value} 207 my $value = $self->{value}; 208 no warnings; # oct might complain about overflow, ignore here... 209 $value =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi; 210 if ($value =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg) { 211 $self->{value} = $value; 212 } 213 sprintf "\$%s",$self->{value}; 214 } else { 215 my $value = $self->{value}; 216 $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm); 217 sprintf "%s",$value; 218 } 219 } 220} 221{ package ea; # pick up effective addresses: expr(%reg,%reg,scale) 222 223 my %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", 224 l=>"DWORD$PTR", d=>"DWORD$PTR", 225 q=>"QWORD$PTR", o=>"OWORD$PTR", 226 x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", 227 z=>"ZMMWORD$PTR" ) if (!$gas); 228 229 sub re { 230 my ($class, $line, $opcode) = @_; 231 my $self = {}; 232 my $ret; 233 234 # optional * ----vvv--- appears in indirect jmp/call 235 if ($$line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)((?:{[^}]+})*)/) { 236 bless $self, $class; 237 $self->{asterisk} = $1; 238 $self->{label} = $2; 239 ($self->{base},$self->{index},$self->{scale})=split(/,/,$3); 240 $self->{scale} = 1 if (!defined($self->{scale})); 241 $self->{opmask} = $4; 242 $ret = $self; 243 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 244 245 if ($win64 && $self->{label} =~ s/\@GOTPCREL//) { 246 die if ($opcode->mnemonic() ne "mov"); 247 $opcode->mnemonic("lea"); 248 } 249 $self->{base} =~ s/^%//; 250 $self->{index} =~ s/^%// if (defined($self->{index})); 251 $self->{opcode} = $opcode; 252 } 253 $ret; 254 } 255 sub size {} 256 sub out { 257 my ($self, $sz) = @_; 258 259 $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei; 260 $self->{label} =~ s/\.L/$decor/g; 261 262 # Silently convert all EAs to 64-bit. This is required for 263 # elder GNU assembler and results in more compact code, 264 # *but* most importantly AES module depends on this feature! 265 $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/; 266 $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/; 267 268 # Solaris /usr/ccs/bin/as can't handle multiplications 269 # in $self->{label}... 270 use integer; 271 $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi; 272 $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg; 273 274 # Some assemblers insist on signed presentation of 32-bit 275 # offsets, but sign extension is a tricky business in perl... 276 if ((1<<31)<<1) { 277 $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg; 278 } else { 279 $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg; 280 } 281 282 # if base register is %rbp or %r13, see if it's possible to 283 # flip base and index registers [for better performance] 284 if (!$self->{label} && $self->{index} && $self->{scale}==1 && 285 $self->{base} =~ /(rbp|r13)/) { 286 $self->{base} = $self->{index}; $self->{index} = $1; 287 } 288 289 if ($gas) { 290 $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64"); 291 292 if (defined($self->{index})) { 293 sprintf "%s%s(%s,%%%s,%d)%s", 294 $self->{asterisk},$self->{label}, 295 $self->{base}?"%$self->{base}":"", 296 $self->{index},$self->{scale}, 297 $self->{opmask}; 298 } else { 299 sprintf "%s%s(%%%s)%s", $self->{asterisk},$self->{label}, 300 $self->{base},$self->{opmask}; 301 } 302 } else { 303 $self->{label} =~ s/\./\$/g; 304 $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig; 305 $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/); 306 307 my $mnemonic = $self->{opcode}->mnemonic(); 308 ($self->{asterisk}) && ($sz="q") || 309 ($mnemonic =~ /^v?mov([qd])$/) && ($sz=$1) || 310 ($mnemonic =~ /^v?pinsr([qdwb])$/) && ($sz=$1) || 311 ($mnemonic =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) || 312 ($mnemonic =~ /^v(?!perm)[a-z]+[fi]128$/) && ($sz="x"); 313 314 $self->{opmask} =~ s/%(k[0-7])/$1/; 315 316 if (defined($self->{index})) { 317 sprintf "%s[%s%s*%d%s]%s",$szmap{$sz}, 318 $self->{label}?"$self->{label}+":"", 319 $self->{index},$self->{scale}, 320 $self->{base}?"+$self->{base}":"", 321 $self->{opmask}; 322 } elsif ($self->{base} eq "rip") { 323 sprintf "%s[%s]",$szmap{$sz},$self->{label}; 324 } else { 325 sprintf "%s[%s%s]%s", $szmap{$sz}, 326 $self->{label}?"$self->{label}+":"", 327 $self->{base},$self->{opmask}; 328 } 329 } 330 } 331} 332{ package register; # pick up registers, which start with %. 333 sub re { 334 my ($class, $line, $opcode) = @_; 335 my $self = {}; 336 my $ret; 337 338 # optional * ----vvv--- appears in indirect jmp/call 339 if ($$line =~ /^(\*?)%(\w+)((?:{[^}]+})*)/) { 340 bless $self,$class; 341 $self->{asterisk} = $1; 342 $self->{value} = $2; 343 $self->{opmask} = $3; 344 $opcode->size($self->size()); 345 $ret = $self; 346 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 347 } 348 $ret; 349 } 350 sub size { 351 my $self = shift; 352 my $ret; 353 354 if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; } 355 elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; } 356 elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; } 357 elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; } 358 elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; } 359 elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; } 360 elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; } 361 elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; } 362 363 $ret; 364 } 365 sub out { 366 my $self = shift; 367 if ($gas) { sprintf "%s%%%s%s", $self->{asterisk}, 368 $self->{value}, 369 $self->{opmask}; } 370 else { $self->{opmask} =~ s/%(k[0-7])/$1/; 371 $self->{value}.$self->{opmask}; } 372 } 373} 374{ package label; # pick up labels, which end with : 375 sub re { 376 my ($class, $line) = @_; 377 my $self = {}; 378 my $ret; 379 380 if ($$line =~ /(^[\.\w]+)\:/) { 381 bless $self,$class; 382 $self->{value} = $1; 383 $ret = $self; 384 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 385 386 $self->{value} =~ s/^\.L/$decor/; 387 } 388 $ret; 389 } 390 sub out { 391 my $self = shift; 392 393 if ($gas) { 394 my $func = ($globals{$self->{value}} or $self->{value}) . ":"; 395 if ($win64 && $current_function->{name} eq $self->{value} 396 && $current_function->{abi} eq "svr4") { 397 $func .= "\n"; 398 $func .= " movq %rdi,8(%rsp)\n"; 399 $func .= " movq %rsi,16(%rsp)\n"; 400 $func .= " movq %rsp,%rax\n"; 401 $func .= "${decor}SEH_begin_$current_function->{name}:\n"; 402 my $narg = $current_function->{narg}; 403 $narg=6 if (!defined($narg)); 404 $func .= " movq %rcx,%rdi\n" if ($narg>0); 405 $func .= " movq %rdx,%rsi\n" if ($narg>1); 406 $func .= " movq %r8,%rdx\n" if ($narg>2); 407 $func .= " movq %r9,%rcx\n" if ($narg>3); 408 $func .= " movq 40(%rsp),%r8\n" if ($narg>4); 409 $func .= " movq 48(%rsp),%r9\n" if ($narg>5); 410 } 411 $func; 412 } elsif ($self->{value} ne "$current_function->{name}") { 413 # Make all labels in masm global. 414 $self->{value} .= ":" if ($masm); 415 $self->{value} . ":"; 416 } elsif ($win64 && $current_function->{abi} eq "svr4") { 417 my $func = "$current_function->{name}" . 418 ($nasm ? ":" : "\tPROC $current_function->{scope}") . 419 "\n"; 420 $func .= " mov QWORD$PTR\[8+rsp\],rdi\t;WIN64 prologue\n"; 421 $func .= " mov QWORD$PTR\[16+rsp\],rsi\n"; 422 $func .= " mov rax,rsp\n"; 423 $func .= "${decor}SEH_begin_$current_function->{name}:"; 424 $func .= ":" if ($masm); 425 $func .= "\n"; 426 my $narg = $current_function->{narg}; 427 $narg=6 if (!defined($narg)); 428 $func .= " mov rdi,rcx\n" if ($narg>0); 429 $func .= " mov rsi,rdx\n" if ($narg>1); 430 $func .= " mov rdx,r8\n" if ($narg>2); 431 $func .= " mov rcx,r9\n" if ($narg>3); 432 $func .= " mov r8,QWORD$PTR\[40+rsp\]\n" if ($narg>4); 433 $func .= " mov r9,QWORD$PTR\[48+rsp\]\n" if ($narg>5); 434 $func .= "\n"; 435 } else { 436 "$current_function->{name}". 437 ($nasm ? ":" : "\tPROC $current_function->{scope}"); 438 } 439 } 440} 441{ package expr; # pick up expressions 442 sub re { 443 my ($class, $line, $opcode) = @_; 444 my $self = {}; 445 my $ret; 446 447 if ($$line =~ /(^[^,]+)/) { 448 bless $self,$class; 449 $self->{value} = $1; 450 $ret = $self; 451 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 452 453 $self->{value} =~ s/\@PLT// if (!$elf); 454 $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei; 455 $self->{value} =~ s/\.L/$decor/g; 456 $self->{opcode} = $opcode; 457 } 458 $ret; 459 } 460 sub out { 461 my $self = shift; 462 if ($nasm && $self->{opcode}->mnemonic()=~m/^j(?![re]cxz)/) { 463 "NEAR ".$self->{value}; 464 } else { 465 $self->{value}; 466 } 467 } 468} 469{ package cfi_directive; 470 # CFI directives annotate instructions that are significant for 471 # stack unwinding procedure compliant with DWARF specification, 472 # see http://dwarfstd.org/. Besides naturally expected for this 473 # script platform-specific filtering function, this module adds 474 # three auxiliary synthetic directives not recognized by [GNU] 475 # assembler: 476 # 477 # - .cfi_push to annotate push instructions in prologue, which 478 # translates to .cfi_adjust_cfa_offset (if needed) and 479 # .cfi_offset; 480 # - .cfi_pop to annotate pop instructions in epilogue, which 481 # translates to .cfi_adjust_cfa_offset (if needed) and 482 # .cfi_restore; 483 # - [and most notably] .cfi_cfa_expression which encodes 484 # DW_CFA_def_cfa_expression and passes it to .cfi_escape as 485 # byte vector; 486 # 487 # CFA expressions were introduced in DWARF specification version 488 # 3 and describe how to deduce CFA, Canonical Frame Address. This 489 # becomes handy if your stack frame is variable and you can't 490 # spare register for [previous] frame pointer. Suggested directive 491 # syntax is made-up mix of DWARF operator suffixes [subset of] 492 # and references to registers with optional bias. Following example 493 # describes offloaded *original* stack pointer at specific offset 494 # from *current* stack pointer: 495 # 496 # .cfi_cfa_expression %rsp+40,deref,+8 497 # 498 # Final +8 has everything to do with the fact that CFA is defined 499 # as reference to top of caller's stack, and on x86_64 call to 500 # subroutine pushes 8-byte return address. In other words original 501 # stack pointer upon entry to a subroutine is 8 bytes off from CFA. 502 503 # Below constants are taken from "DWARF Expressions" section of the 504 # DWARF specification, section is numbered 7.7 in versions 3 and 4. 505 my %DW_OP_simple = ( # no-arg operators, mapped directly 506 deref => 0x06, dup => 0x12, 507 drop => 0x13, over => 0x14, 508 pick => 0x15, swap => 0x16, 509 rot => 0x17, xderef => 0x18, 510 511 abs => 0x19, and => 0x1a, 512 div => 0x1b, minus => 0x1c, 513 mod => 0x1d, mul => 0x1e, 514 neg => 0x1f, not => 0x20, 515 or => 0x21, plus => 0x22, 516 shl => 0x24, shr => 0x25, 517 shra => 0x26, xor => 0x27, 518 ); 519 520 my %DW_OP_complex = ( # used in specific subroutines 521 constu => 0x10, # uleb128 522 consts => 0x11, # sleb128 523 plus_uconst => 0x23, # uleb128 524 lit0 => 0x30, # add 0-31 to opcode 525 reg0 => 0x50, # add 0-31 to opcode 526 breg0 => 0x70, # add 0-31 to opcole, sleb128 527 regx => 0x90, # uleb28 528 fbreg => 0x91, # sleb128 529 bregx => 0x92, # uleb128, sleb128 530 piece => 0x93, # uleb128 531 ); 532 533 # Following constants are defined in x86_64 ABI supplement, for 534 # example available at https://www.uclibc.org/docs/psABI-x86_64.pdf, 535 # see section 3.7 "Stack Unwind Algorithm". 536 my %DW_reg_idx = ( 537 "%rax"=>0, "%rdx"=>1, "%rcx"=>2, "%rbx"=>3, 538 "%rsi"=>4, "%rdi"=>5, "%rbp"=>6, "%rsp"=>7, 539 "%r8" =>8, "%r9" =>9, "%r10"=>10, "%r11"=>11, 540 "%r12"=>12, "%r13"=>13, "%r14"=>14, "%r15"=>15 541 ); 542 543 my ($cfa_reg, $cfa_rsp); 544 545 # [us]leb128 format is variable-length integer representation base 546 # 2^128, with most significant bit of each byte being 0 denoting 547 # *last* most significant digit. See "Variable Length Data" in the 548 # DWARF specification, numbered 7.6 at least in versions 3 and 4. 549 sub sleb128 { 550 use integer; # get right shift extend sign 551 552 my $val = shift; 553 my $sign = ($val < 0) ? -1 : 0; 554 my @ret = (); 555 556 while(1) { 557 push @ret, $val&0x7f; 558 559 # see if remaining bits are same and equal to most 560 # significant bit of the current digit, if so, it's 561 # last digit... 562 last if (($val>>6) == $sign); 563 564 @ret[-1] |= 0x80; 565 $val >>= 7; 566 } 567 568 return @ret; 569 } 570 sub uleb128 { 571 my $val = shift; 572 my @ret = (); 573 574 while(1) { 575 push @ret, $val&0x7f; 576 577 # see if it's last significant digit... 578 last if (($val >>= 7) == 0); 579 580 @ret[-1] |= 0x80; 581 } 582 583 return @ret; 584 } 585 sub const { 586 my $val = shift; 587 588 if ($val >= 0 && $val < 32) { 589 return ($DW_OP_complex{lit0}+$val); 590 } 591 return ($DW_OP_complex{consts}, sleb128($val)); 592 } 593 sub reg { 594 my $val = shift; 595 596 return if ($val !~ m/^(%r\w+)(?:([\+\-])((?:0x)?[0-9a-f]+))?/); 597 598 my $reg = $DW_reg_idx{$1}; 599 my $off = eval ("0 $2 $3"); 600 601 return (($DW_OP_complex{breg0} + $reg), sleb128($off)); 602 # Yes, we use DW_OP_bregX+0 to push register value and not 603 # DW_OP_regX, because latter would require even DW_OP_piece, 604 # which would be a waste under the circumstances. If you have 605 # to use DWP_OP_reg, use "regx:N"... 606 } 607 sub cfa_expression { 608 my $line = shift; 609 my @ret; 610 611 foreach my $token (split(/,\s*/,$line)) { 612 if ($token =~ /^%r/) { 613 push @ret,reg($token); 614 } elsif ($token =~ /((?:0x)?[0-9a-f]+)\((%r\w+)\)/) { 615 push @ret,reg("$2+$1"); 616 } elsif ($token =~ /(\w+):(\-?(?:0x)?[0-9a-f]+)(U?)/i) { 617 my $i = 1*eval($2); 618 push @ret,$DW_OP_complex{$1}, ($3 ? uleb128($i) : sleb128($i)); 619 } elsif (my $i = 1*eval($token) or $token eq "0") { 620 if ($token =~ /^\+/) { 621 push @ret,$DW_OP_complex{plus_uconst},uleb128($i); 622 } else { 623 push @ret,const($i); 624 } 625 } else { 626 push @ret,$DW_OP_simple{$token}; 627 } 628 } 629 630 # Finally we return DW_CFA_def_cfa_expression, 15, followed by 631 # length of the expression and of course the expression itself. 632 return (15,scalar(@ret),@ret); 633 } 634 sub re { 635 my ($class, $line) = @_; 636 my $self = {}; 637 my $ret; 638 639 if ($$line =~ s/^\s*\.cfi_(\w+)\s*//) { 640 bless $self,$class; 641 $ret = $self; 642 undef $self->{value}; 643 my $dir = $1; 644 645 SWITCH: for ($dir) { 646 # What is $cfa_rsp? Effectively it's difference between %rsp 647 # value and current CFA, Canonical Frame Address, which is 648 # why it starts with -8. Recall that CFA is top of caller's 649 # stack... 650 /startproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", -8); last; }; 651 /endproc/ && do { ($cfa_reg, $cfa_rsp) = ("%rsp", 0); last; }; 652 /def_cfa_register/ 653 && do { $cfa_reg = $$line; last; }; 654 /def_cfa_offset/ 655 && do { $cfa_rsp = -1*eval($$line) if ($cfa_reg eq "%rsp"); 656 last; 657 }; 658 /adjust_cfa_offset/ 659 && do { $cfa_rsp -= 1*eval($$line) if ($cfa_reg eq "%rsp"); 660 last; 661 }; 662 /def_cfa/ && do { if ($$line =~ /(%r\w+)\s*,\s*(.+)/) { 663 $cfa_reg = $1; 664 $cfa_rsp = -1*eval($2) if ($cfa_reg eq "%rsp"); 665 } 666 last; 667 }; 668 /push/ && do { $dir = undef; 669 $cfa_rsp -= 8; 670 if ($cfa_reg eq "%rsp") { 671 $self->{value} = ".cfi_adjust_cfa_offset\t8\n"; 672 } 673 $self->{value} .= ".cfi_offset\t$$line,$cfa_rsp"; 674 last; 675 }; 676 /pop/ && do { $dir = undef; 677 $cfa_rsp += 8; 678 if ($cfa_reg eq "%rsp") { 679 $self->{value} = ".cfi_adjust_cfa_offset\t-8\n"; 680 } 681 $self->{value} .= ".cfi_restore\t$$line"; 682 last; 683 }; 684 /cfa_expression/ 685 && do { $dir = undef; 686 $self->{value} = ".cfi_escape\t" . 687 join(",", map(sprintf("0x%02x", $_), 688 cfa_expression($$line))); 689 last; 690 }; 691 } 692 693 $self->{value} = ".cfi_$dir\t$$line" if ($dir); 694 695 $$line = ""; 696 } 697 698 return $ret; 699 } 700 sub out { 701 my $self = shift; 702 return ($elf ? $self->{value} : undef); 703 } 704} 705{ package directive; # pick up directives, which start with . 706 sub re { 707 my ($class, $line) = @_; 708 my $self = {}; 709 my $ret; 710 my $dir; 711 712 # chain-call to cfi_directive 713 $ret = cfi_directive->re($line) and return $ret; 714 715 if ($$line =~ /^\s*(\.\w+)/) { 716 bless $self,$class; 717 $dir = $1; 718 $ret = $self; 719 undef $self->{value}; 720 $$line = substr($$line,@+[0]); $$line =~ s/^\s+//; 721 722 SWITCH: for ($dir) { 723 /\.global|\.globl|\.extern/ 724 && do { $globals{$$line} = $prefix . $$line; 725 $$line = $globals{$$line} if ($prefix); 726 last; 727 }; 728 /\.type/ && do { my ($sym,$type,$narg) = split(',',$$line); 729 if ($type eq "\@function") { 730 undef $current_function; 731 $current_function->{name} = $sym; 732 $current_function->{abi} = "svr4"; 733 $current_function->{narg} = $narg; 734 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE"; 735 } elsif ($type eq "\@abi-omnipotent") { 736 undef $current_function; 737 $current_function->{name} = $sym; 738 $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE"; 739 } 740 $$line =~ s/\@abi\-omnipotent/\@function/; 741 $$line =~ s/\@function.*/\@function/; 742 last; 743 }; 744 /\.asciz/ && do { if ($$line =~ /^"(.*)"$/) { 745 $dir = ".byte"; 746 $$line = join(",",unpack("C*",$1),0); 747 } 748 last; 749 }; 750 /\.rva|\.long|\.quad/ 751 && do { $$line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei; 752 $$line =~ s/\.L/$decor/g; 753 last; 754 }; 755 } 756 757 if ($gas) { 758 $self->{value} = $dir . "\t" . $$line; 759 760 if ($dir =~ /\.extern/) { 761 $self->{value} = ""; # swallow extern 762 } elsif (!$elf && $dir =~ /\.type/) { 763 $self->{value} = ""; 764 $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" . 765 (defined($globals{$1})?".scl 2;":".scl 3;") . 766 "\t.type 32;\t.endef" 767 if ($win64 && $$line =~ /([^,]+),\@function/); 768 } elsif (!$elf && $dir =~ /\.size/) { 769 $self->{value} = ""; 770 if (defined($current_function)) { 771 $self->{value} .= "${decor}SEH_end_$current_function->{name}:" 772 if ($win64 && $current_function->{abi} eq "svr4"); 773 undef $current_function; 774 } 775 } elsif (!$elf && $dir =~ /\.align/) { 776 $self->{value} = ".p2align\t" . (log($$line)/log(2)); 777 } elsif ($dir eq ".section") { 778 $current_segment=$$line; 779 if (!$elf && $current_segment eq ".init") { 780 if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; } 781 elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; } 782 } 783 } elsif ($dir =~ /\.(text|data)/) { 784 $current_segment=".$1"; 785 } elsif ($dir =~ /\.hidden/) { 786 if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; } 787 elsif ($flavour eq "mingw64") { $self->{value} = ""; } 788 } elsif ($dir =~ /\.comm/) { 789 $self->{value} = "$dir\t$prefix$$line"; 790 $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx"); 791 } 792 $$line = ""; 793 return $self; 794 } 795 796 # non-gas case or nasm/masm 797 SWITCH: for ($dir) { 798 /\.text/ && do { my $v=undef; 799 if ($nasm) { 800 $v="section .text code align=64\n"; 801 } else { 802 $v="$current_segment\tENDS\n" if ($current_segment); 803 $current_segment = ".text\$"; 804 $v.="$current_segment\tSEGMENT "; 805 $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE"; 806 $v.=" 'CODE'"; 807 } 808 $self->{value} = $v; 809 last; 810 }; 811 /\.data/ && do { my $v=undef; 812 if ($nasm) { 813 $v="section .data data align=8\n"; 814 } else { 815 $v="$current_segment\tENDS\n" if ($current_segment); 816 $current_segment = "_DATA"; 817 $v.="$current_segment\tSEGMENT"; 818 } 819 $self->{value} = $v; 820 last; 821 }; 822 /\.section/ && do { my $v=undef; 823 $$line =~ s/([^,]*).*/$1/; 824 $$line = ".CRT\$XCU" if ($$line eq ".init"); 825 if ($nasm) { 826 $v="section $$line"; 827 if ($$line=~/\.([px])data/) { 828 $v.=" rdata align="; 829 $v.=$1 eq "p"? 4 : 8; 830 } elsif ($$line=~/\.CRT\$/i) { 831 $v.=" rdata align=8"; 832 } 833 } else { 834 $v="$current_segment\tENDS\n" if ($current_segment); 835 $v.="$$line\tSEGMENT"; 836 if ($$line=~/\.([px])data/) { 837 $v.=" READONLY"; 838 $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref); 839 } elsif ($$line=~/\.CRT\$/i) { 840 $v.=" READONLY "; 841 $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD"; 842 } 843 } 844 $current_segment = $$line; 845 $self->{value} = $v; 846 last; 847 }; 848 /\.extern/ && do { $self->{value} = "EXTERN\t".$$line; 849 $self->{value} .= ":NEAR" if ($masm); 850 last; 851 }; 852 /\.globl|.global/ 853 && do { $self->{value} = $masm?"PUBLIC":"global"; 854 $self->{value} .= "\t".$$line; 855 last; 856 }; 857 /\.size/ && do { if (defined($current_function)) { 858 undef $self->{value}; 859 if ($current_function->{abi} eq "svr4") { 860 $self->{value}="${decor}SEH_end_$current_function->{name}:"; 861 $self->{value}.=":\n" if($masm); 862 } 863 $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name}); 864 undef $current_function; 865 } 866 last; 867 }; 868 /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096; 869 $self->{value} = "ALIGN\t".($$line>$max?$max:$$line); 870 last; 871 }; 872 /\.(value|long|rva|quad)/ 873 && do { my $sz = substr($1,0,1); 874 my @arr = split(/,\s*/,$$line); 875 my $last = pop(@arr); 876 my $conv = sub { my $var=shift; 877 $var=~s/^(0b[0-1]+)/oct($1)/eig; 878 $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm); 879 if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva")) 880 { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; } 881 $var; 882 }; 883 884 $sz =~ tr/bvlrq/BWDDQ/; 885 $self->{value} = "\tD$sz\t"; 886 for (@arr) { $self->{value} .= &$conv($_).","; } 887 $self->{value} .= &$conv($last); 888 last; 889 }; 890 /\.byte/ && do { my @str=split(/,\s*/,$$line); 891 map(s/(0b[0-1]+)/oct($1)/eig,@str); 892 map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm); 893 while ($#str>15) { 894 $self->{value}.="DB\t" 895 .join(",",@str[0..15])."\n"; 896 foreach (0..15) { shift @str; } 897 } 898 $self->{value}.="DB\t" 899 .join(",",@str) if (@str); 900 last; 901 }; 902 /\.comm/ && do { my @str=split(/,\s*/,$$line); 903 my $v=undef; 904 if ($nasm) { 905 $v.="common $prefix@str[0] @str[1]"; 906 } else { 907 $v="$current_segment\tENDS\n" if ($current_segment); 908 $current_segment = "_DATA"; 909 $v.="$current_segment\tSEGMENT\n"; 910 $v.="COMM @str[0]:DWORD:".@str[1]/4; 911 } 912 $self->{value} = $v; 913 last; 914 }; 915 } 916 $$line = ""; 917 } 918 919 $ret; 920 } 921 sub out { 922 my $self = shift; 923 $self->{value}; 924 } 925} 926 927# Upon initial x86_64 introduction SSE>2 extensions were not introduced 928# yet. In order not to be bothered by tracing exact assembler versions, 929# but at the same time to provide a bare security minimum of AES-NI, we 930# hard-code some instructions. Extensions past AES-NI on the other hand 931# are traced by examining assembler version in individual perlasm 932# modules... 933 934my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3, 935 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 ); 936 937sub rex { 938 my $opcode=shift; 939 my ($dst,$src,$rex)=@_; 940 941 $rex|=0x04 if($dst>=8); 942 $rex|=0x01 if($src>=8); 943 push @$opcode,($rex|0x40) if ($rex); 944} 945 946my $movq = sub { # elderly gas can't handle inter-register movq 947 my $arg = shift; 948 my @opcode=(0x66); 949 if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) { 950 my ($src,$dst)=($1,$2); 951 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; } 952 rex(\@opcode,$src,$dst,0x8); 953 push @opcode,0x0f,0x7e; 954 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M 955 @opcode; 956 } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) { 957 my ($src,$dst)=($2,$1); 958 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; } 959 rex(\@opcode,$src,$dst,0x8); 960 push @opcode,0x0f,0x6e; 961 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M 962 @opcode; 963 } else { 964 (); 965 } 966}; 967 968my $pextrd = sub { 969 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) { 970 my @opcode=(0x66); 971 my $imm=$1; 972 my $src=$2; 973 my $dst=$3; 974 if ($dst =~ /%r([0-9]+)d/) { $dst = $1; } 975 elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; } 976 rex(\@opcode,$src,$dst); 977 push @opcode,0x0f,0x3a,0x16; 978 push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M 979 push @opcode,$imm; 980 @opcode; 981 } else { 982 (); 983 } 984}; 985 986my $pinsrd = sub { 987 if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) { 988 my @opcode=(0x66); 989 my $imm=$1; 990 my $src=$2; 991 my $dst=$3; 992 if ($src =~ /%r([0-9]+)/) { $src = $1; } 993 elsif ($src =~ /%e/) { $src = $regrm{$src}; } 994 rex(\@opcode,$dst,$src); 995 push @opcode,0x0f,0x3a,0x22; 996 push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M 997 push @opcode,$imm; 998 @opcode; 999 } else { 1000 (); 1001 } 1002}; 1003 1004my $pshufb = sub { 1005 if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) { 1006 my @opcode=(0x66); 1007 rex(\@opcode,$2,$1); 1008 push @opcode,0x0f,0x38,0x00; 1009 push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M 1010 @opcode; 1011 } else { 1012 (); 1013 } 1014}; 1015 1016my $palignr = sub { 1017 if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) { 1018 my @opcode=(0x66); 1019 rex(\@opcode,$3,$2); 1020 push @opcode,0x0f,0x3a,0x0f; 1021 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M 1022 push @opcode,$1; 1023 @opcode; 1024 } else { 1025 (); 1026 } 1027}; 1028 1029my $pclmulqdq = sub { 1030 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) { 1031 my @opcode=(0x66); 1032 rex(\@opcode,$3,$2); 1033 push @opcode,0x0f,0x3a,0x44; 1034 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M 1035 my $c=$1; 1036 push @opcode,$c=~/^0/?oct($c):$c; 1037 @opcode; 1038 } else { 1039 (); 1040 } 1041}; 1042 1043my $rdrand = sub { 1044 if (shift =~ /%[er](\w+)/) { 1045 my @opcode=(); 1046 my $dst=$1; 1047 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; } 1048 rex(\@opcode,0,$dst,8); 1049 push @opcode,0x0f,0xc7,0xf0|($dst&7); 1050 @opcode; 1051 } else { 1052 (); 1053 } 1054}; 1055 1056my $rdseed = sub { 1057 if (shift =~ /%[er](\w+)/) { 1058 my @opcode=(); 1059 my $dst=$1; 1060 if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; } 1061 rex(\@opcode,0,$dst,8); 1062 push @opcode,0x0f,0xc7,0xf8|($dst&7); 1063 @opcode; 1064 } else { 1065 (); 1066 } 1067}; 1068 1069# Not all AVX-capable assemblers recognize AMD XOP extension. Since we 1070# are using only two instructions hand-code them in order to be excused 1071# from chasing assembler versions... 1072 1073sub rxb { 1074 my $opcode=shift; 1075 my ($dst,$src1,$src2,$rxb)=@_; 1076 1077 $rxb|=0x7<<5; 1078 $rxb&=~(0x04<<5) if($dst>=8); 1079 $rxb&=~(0x01<<5) if($src1>=8); 1080 $rxb&=~(0x02<<5) if($src2>=8); 1081 push @$opcode,$rxb; 1082} 1083 1084my $vprotd = sub { 1085 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) { 1086 my @opcode=(0x8f); 1087 rxb(\@opcode,$3,$2,-1,0x08); 1088 push @opcode,0x78,0xc2; 1089 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M 1090 my $c=$1; 1091 push @opcode,$c=~/^0/?oct($c):$c; 1092 @opcode; 1093 } else { 1094 (); 1095 } 1096}; 1097 1098my $vprotq = sub { 1099 if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) { 1100 my @opcode=(0x8f); 1101 rxb(\@opcode,$3,$2,-1,0x08); 1102 push @opcode,0x78,0xc3; 1103 push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M 1104 my $c=$1; 1105 push @opcode,$c=~/^0/?oct($c):$c; 1106 @opcode; 1107 } else { 1108 (); 1109 } 1110}; 1111 1112# Intel Control-flow Enforcement Technology extension. All functions and 1113# indirect branch targets will have to start with this instruction... 1114 1115my $endbranch = sub { 1116 (0xf3,0x0f,0x1e,0xfa); 1117}; 1118 1119######################################################################## 1120 1121if ($nasm) { 1122 print <<___; 1123default rel 1124%define XMMWORD 1125%define YMMWORD 1126%define ZMMWORD 1127___ 1128} elsif ($masm) { 1129 print <<___; 1130OPTION DOTNAME 1131___ 1132} 1133while(defined(my $line=<>)) { 1134 1135 $line =~ s|\R$||; # Better chomp 1136 1137 $line =~ s|[#!].*$||; # get rid of asm-style comments... 1138 $line =~ s|/\*.*\*/||; # ... and C-style comments... 1139 $line =~ s|^\s+||; # ... and skip white spaces in beginning 1140 $line =~ s|\s+$||; # ... and at the end 1141 1142 if (my $label=label->re(\$line)) { print $label->out(); } 1143 1144 if (my $directive=directive->re(\$line)) { 1145 printf "%s",$directive->out(); 1146 } elsif (my $opcode=opcode->re(\$line)) { 1147 my $asm = eval("\$".$opcode->mnemonic()); 1148 1149 if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) { 1150 print $gas?".byte\t":"DB\t",join(',',@bytes),"\n"; 1151 next; 1152 } 1153 1154 my @args; 1155 ARGUMENT: while (1) { 1156 my $arg; 1157 1158 ($arg=register->re(\$line, $opcode))|| 1159 ($arg=const->re(\$line)) || 1160 ($arg=ea->re(\$line, $opcode)) || 1161 ($arg=expr->re(\$line, $opcode)) || 1162 last ARGUMENT; 1163 1164 push @args,$arg; 1165 1166 last ARGUMENT if ($line !~ /^,/); 1167 1168 $line =~ s/^,\s*//; 1169 } # ARGUMENT: 1170 1171 if ($#args>=0) { 1172 my $insn; 1173 my $sz=$opcode->size(); 1174 1175 if ($gas) { 1176 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz); 1177 @args = map($_->out($sz),@args); 1178 printf "\t%s\t%s",$insn,join(",",@args); 1179 } else { 1180 $insn = $opcode->out(); 1181 foreach (@args) { 1182 my $arg = $_->out(); 1183 # $insn.=$sz compensates for movq, pinsrw, ... 1184 if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; } 1185 if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; } 1186 if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; } 1187 if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; } 1188 } 1189 @args = reverse(@args); 1190 undef $sz if ($nasm && $opcode->mnemonic() eq "lea"); 1191 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args)); 1192 } 1193 } else { 1194 printf "\t%s",$opcode->out(); 1195 } 1196 } 1197 1198 print $line,"\n"; 1199} 1200 1201print "\n$current_segment\tENDS\n" if ($current_segment && $masm); 1202print "END\n" if ($masm); 1203 1204close STDOUT; 1205 1206################################################# 1207# Cross-reference x86_64 ABI "card" 1208# 1209# Unix Win64 1210# %rax * * 1211# %rbx - - 1212# %rcx #4 #1 1213# %rdx #3 #2 1214# %rsi #2 - 1215# %rdi #1 - 1216# %rbp - - 1217# %rsp - - 1218# %r8 #5 #3 1219# %r9 #6 #4 1220# %r10 * * 1221# %r11 * * 1222# %r12 - - 1223# %r13 - - 1224# %r14 - - 1225# %r15 - - 1226# 1227# (*) volatile register 1228# (-) preserved by callee 1229# (#) Nth argument, volatile 1230# 1231# In Unix terms top of stack is argument transfer area for arguments 1232# which could not be accommodated in registers. Or in other words 7th 1233# [integer] argument resides at 8(%rsp) upon function entry point. 1234# 128 bytes above %rsp constitute a "red zone" which is not touched 1235# by signal handlers and can be used as temporal storage without 1236# allocating a frame. 1237# 1238# In Win64 terms N*8 bytes on top of stack is argument transfer area, 1239# which belongs to/can be overwritten by callee. N is the number of 1240# arguments passed to callee, *but* not less than 4! This means that 1241# upon function entry point 5th argument resides at 40(%rsp), as well 1242# as that 32 bytes from 8(%rsp) can always be used as temporal 1243# storage [without allocating a frame]. One can actually argue that 1244# one can assume a "red zone" above stack pointer under Win64 as well. 1245# Point is that at apparently no occasion Windows kernel would alter 1246# the area above user stack pointer in true asynchronous manner... 1247# 1248# All the above means that if assembler programmer adheres to Unix 1249# register and stack layout, but disregards the "red zone" existence, 1250# it's possible to use following prologue and epilogue to "gear" from 1251# Unix to Win64 ABI in leaf functions with not more than 6 arguments. 1252# 1253# omnipotent_function: 1254# ifdef WIN64 1255# movq %rdi,8(%rsp) 1256# movq %rsi,16(%rsp) 1257# movq %rcx,%rdi ; if 1st argument is actually present 1258# movq %rdx,%rsi ; if 2nd argument is actually ... 1259# movq %r8,%rdx ; if 3rd argument is ... 1260# movq %r9,%rcx ; if 4th argument ... 1261# movq 40(%rsp),%r8 ; if 5th ... 1262# movq 48(%rsp),%r9 ; if 6th ... 1263# endif 1264# ... 1265# ifdef WIN64 1266# movq 8(%rsp),%rdi 1267# movq 16(%rsp),%rsi 1268# endif 1269# ret 1270# 1271################################################# 1272# Win64 SEH, Structured Exception Handling. 1273# 1274# Unlike on Unix systems(*) lack of Win64 stack unwinding information 1275# has undesired side-effect at run-time: if an exception is raised in 1276# assembler subroutine such as those in question (basically we're 1277# referring to segmentation violations caused by malformed input 1278# parameters), the application is briskly terminated without invoking 1279# any exception handlers, most notably without generating memory dump 1280# or any user notification whatsoever. This poses a problem. It's 1281# possible to address it by registering custom language-specific 1282# handler that would restore processor context to the state at 1283# subroutine entry point and return "exception is not handled, keep 1284# unwinding" code. Writing such handler can be a challenge... But it's 1285# doable, though requires certain coding convention. Consider following 1286# snippet: 1287# 1288# .type function,@function 1289# function: 1290# movq %rsp,%rax # copy rsp to volatile register 1291# pushq %r15 # save non-volatile registers 1292# pushq %rbx 1293# pushq %rbp 1294# movq %rsp,%r11 1295# subq %rdi,%r11 # prepare [variable] stack frame 1296# andq $-64,%r11 1297# movq %rax,0(%r11) # check for exceptions 1298# movq %r11,%rsp # allocate [variable] stack frame 1299# movq %rax,0(%rsp) # save original rsp value 1300# magic_point: 1301# ... 1302# movq 0(%rsp),%rcx # pull original rsp value 1303# movq -24(%rcx),%rbp # restore non-volatile registers 1304# movq -16(%rcx),%rbx 1305# movq -8(%rcx),%r15 1306# movq %rcx,%rsp # restore original rsp 1307# magic_epilogue: 1308# ret 1309# .size function,.-function 1310# 1311# The key is that up to magic_point copy of original rsp value remains 1312# in chosen volatile register and no non-volatile register, except for 1313# rsp, is modified. While past magic_point rsp remains constant till 1314# the very end of the function. In this case custom language-specific 1315# exception handler would look like this: 1316# 1317# EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, 1318# CONTEXT *context,DISPATCHER_CONTEXT *disp) 1319# { ULONG64 *rsp = (ULONG64 *)context->Rax; 1320# ULONG64 rip = context->Rip; 1321# 1322# if (rip >= magic_point) 1323# { rsp = (ULONG64 *)context->Rsp; 1324# if (rip < magic_epilogue) 1325# { rsp = (ULONG64 *)rsp[0]; 1326# context->Rbp = rsp[-3]; 1327# context->Rbx = rsp[-2]; 1328# context->R15 = rsp[-1]; 1329# } 1330# } 1331# context->Rsp = (ULONG64)rsp; 1332# context->Rdi = rsp[1]; 1333# context->Rsi = rsp[2]; 1334# 1335# memcpy (disp->ContextRecord,context,sizeof(CONTEXT)); 1336# RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase, 1337# dips->ControlPc,disp->FunctionEntry,disp->ContextRecord, 1338# &disp->HandlerData,&disp->EstablisherFrame,NULL); 1339# return ExceptionContinueSearch; 1340# } 1341# 1342# It's appropriate to implement this handler in assembler, directly in 1343# function's module. In order to do that one has to know members' 1344# offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant 1345# values. Here they are: 1346# 1347# CONTEXT.Rax 120 1348# CONTEXT.Rcx 128 1349# CONTEXT.Rdx 136 1350# CONTEXT.Rbx 144 1351# CONTEXT.Rsp 152 1352# CONTEXT.Rbp 160 1353# CONTEXT.Rsi 168 1354# CONTEXT.Rdi 176 1355# CONTEXT.R8 184 1356# CONTEXT.R9 192 1357# CONTEXT.R10 200 1358# CONTEXT.R11 208 1359# CONTEXT.R12 216 1360# CONTEXT.R13 224 1361# CONTEXT.R14 232 1362# CONTEXT.R15 240 1363# CONTEXT.Rip 248 1364# CONTEXT.Xmm6 512 1365# sizeof(CONTEXT) 1232 1366# DISPATCHER_CONTEXT.ControlPc 0 1367# DISPATCHER_CONTEXT.ImageBase 8 1368# DISPATCHER_CONTEXT.FunctionEntry 16 1369# DISPATCHER_CONTEXT.EstablisherFrame 24 1370# DISPATCHER_CONTEXT.TargetIp 32 1371# DISPATCHER_CONTEXT.ContextRecord 40 1372# DISPATCHER_CONTEXT.LanguageHandler 48 1373# DISPATCHER_CONTEXT.HandlerData 56 1374# UNW_FLAG_NHANDLER 0 1375# ExceptionContinueSearch 1 1376# 1377# In order to tie the handler to the function one has to compose 1378# couple of structures: one for .xdata segment and one for .pdata. 1379# 1380# UNWIND_INFO structure for .xdata segment would be 1381# 1382# function_unwind_info: 1383# .byte 9,0,0,0 1384# .rva handler 1385# 1386# This structure designates exception handler for a function with 1387# zero-length prologue, no stack frame or frame register. 1388# 1389# To facilitate composing of .pdata structures, auto-generated "gear" 1390# prologue copies rsp value to rax and denotes next instruction with 1391# .LSEH_begin_{function_name} label. This essentially defines the SEH 1392# styling rule mentioned in the beginning. Position of this label is 1393# chosen in such manner that possible exceptions raised in the "gear" 1394# prologue would be accounted to caller and unwound from latter's frame. 1395# End of function is marked with respective .LSEH_end_{function_name} 1396# label. To summarize, .pdata segment would contain 1397# 1398# .rva .LSEH_begin_function 1399# .rva .LSEH_end_function 1400# .rva function_unwind_info 1401# 1402# Reference to function_unwind_info from .xdata segment is the anchor. 1403# In case you wonder why references are 32-bit .rvas and not 64-bit 1404# .quads. References put into these two segments are required to be 1405# *relative* to the base address of the current binary module, a.k.a. 1406# image base. No Win64 module, be it .exe or .dll, can be larger than 1407# 2GB and thus such relative references can be and are accommodated in 1408# 32 bits. 1409# 1410# Having reviewed the example function code, one can argue that "movq 1411# %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix 1412# rax would contain an undefined value. If this "offends" you, use 1413# another register and refrain from modifying rax till magic_point is 1414# reached, i.e. as if it was a non-volatile register. If more registers 1415# are required prior [variable] frame setup is completed, note that 1416# nobody says that you can have only one "magic point." You can 1417# "liberate" non-volatile registers by denoting last stack off-load 1418# instruction and reflecting it in finer grade unwind logic in handler. 1419# After all, isn't it why it's called *language-specific* handler... 1420# 1421# SE handlers are also involved in unwinding stack when executable is 1422# profiled or debugged. Profiling implies additional limitations that 1423# are too subtle to discuss here. For now it's sufficient to say that 1424# in order to simplify handlers one should either a) offload original 1425# %rsp to stack (like discussed above); or b) if you have a register to 1426# spare for frame pointer, choose volatile one. 1427# 1428# (*) Note that we're talking about run-time, not debug-time. Lack of 1429# unwind information makes debugging hard on both Windows and 1430# Unix. "Unlike" refers to the fact that on Unix signal handler 1431# will always be invoked, core dumped and appropriate exit code 1432# returned to parent (for user notification). 1433