x86_64-xlate.pl 43 KB

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