x86_64-xlate.pl 44 KB

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