Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

1492 řádky
45 KiB

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