x86_64-xlate.pl 43 KB

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