Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

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