x86_64-xlate.pl 52 KB

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