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