PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/crypto/openssl/crypto/perlasm/x86_64-xlate.pl

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