2
0

x86_64-xlate.pl 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. #
  842. # $$line may still contains align= option. We do care
  843. # about section type here.
  844. #
  845. $current_segment = $$line;
  846. $current_segment =~ s/([^\s]+).*$/$1/;
  847. if (!$elf && $current_segment eq ".rodata") {
  848. if ($flavour eq "macosx") { $self->{value} = ".section\t__DATA,__const"; }
  849. }
  850. if (!$elf && $current_segment eq ".init") {
  851. if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
  852. elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
  853. }
  854. } elsif ($dir =~ /\.(text|data)/) {
  855. $current_segment=".$1";
  856. } elsif ($dir =~ /\.hidden/) {
  857. if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$$line"; }
  858. elsif ($flavour eq "mingw64") { $self->{value} = ""; }
  859. } elsif ($dir =~ /\.comm/) {
  860. $self->{value} = "$dir\t$prefix$$line";
  861. $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
  862. } elsif ($dir =~ /\.previous/) {
  863. $self->{value} = "" if ($flavour eq "mingw64");
  864. }
  865. $$line = "";
  866. return $self;
  867. }
  868. # non-gas case or nasm/masm
  869. SWITCH: for ($dir) {
  870. /\.text/ && do { my $v=undef;
  871. if ($nasm) {
  872. $current_segment = pop(@segment_stack);
  873. if (not $current_segment) {
  874. push(@segment_stack, ".text");
  875. }
  876. $v="section .text code align=64\n";
  877. $current_segment = ".text";
  878. push(@segment_stack, $current_segment);
  879. } else {
  880. $current_segment = pop(@segment_stack);
  881. if (not $current_segment) {
  882. push(@segment_stack, ".text\$");
  883. }
  884. $v="$current_segment\tENDS\n" if ($current_segment);
  885. $current_segment = ".text\$";
  886. push(@segment_stack, $current_segment);
  887. $v.="$current_segment\tSEGMENT ";
  888. $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
  889. $v.=" 'CODE'";
  890. }
  891. $self->{value} = $v;
  892. last;
  893. };
  894. /\.data/ && do { my $v=undef;
  895. if ($nasm) {
  896. $v="section .data data align=8\n";
  897. } else {
  898. $current_segment = pop(@segment_stack);
  899. $v="$current_segment\tENDS\n" if ($current_segment);
  900. $current_segment = "_DATA";
  901. push(@segment_stack, $current_segment);
  902. $v.="$current_segment\tSEGMENT";
  903. }
  904. $self->{value} = $v;
  905. last;
  906. };
  907. /\.section/ && do { my $v=undef;
  908. my $align=undef;
  909. #
  910. # $$line may currently contain something like this
  911. # .rodata align = 64
  912. # align part is optional
  913. #
  914. $align = $$line;
  915. $align =~ s/(.*)(align\s*=\s*\d+$)/$2/;
  916. $$line =~ s/(.*)(\s+align\s*=\s*\d+$)/$1/;
  917. $$line = ".CRT\$XCU" if ($$line eq ".init");
  918. $$line = ".rdata" if ($$line eq ".rodata");
  919. if ($nasm) {
  920. $current_segment = pop(@segment_stack);
  921. if (not $current_segment) {
  922. #
  923. # This is a hack which deals with ecp_nistz256-x86_64.pl,
  924. # The precomputed curve is stored in the first section
  925. # in .asm file. Pushing extra .text section here
  926. # allows our poor man's solution to stick to assumption
  927. # .text section is always the first.
  928. #
  929. push(@segment_stack, ".text");
  930. }
  931. $v="section $$line";
  932. if ($$line=~/\.([prx])data/) {
  933. if ($align =~ /align\s*=\s*(\d+)/) {
  934. $v.= " rdata align=$1" ;
  935. } else {
  936. $v.=" rdata align=";
  937. $v.=$1 eq "p"? 4 : 8;
  938. }
  939. } elsif ($$line=~/\.CRT\$/i) {
  940. $v.=" rdata align=8";
  941. }
  942. } else {
  943. $current_segment = pop(@segment_stack);
  944. if (not $current_segment) {
  945. #
  946. # same hack for masm to keep ecp_nistz256-x86_64.pl
  947. # happy.
  948. #
  949. push(@segment_stack, ".text\$");
  950. }
  951. $v="$current_segment\tENDS\n" if ($current_segment);
  952. $v.="$$line\tSEGMENT";
  953. if ($$line=~/\.([prx])data/) {
  954. $v.=" READONLY";
  955. if ($align =~ /align\s*=\s*(\d+)$/) {
  956. $v.=" ALIGN($1)" if ($masm>=$masmref);
  957. } else {
  958. $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
  959. }
  960. } elsif ($$line=~/\.CRT\$/i) {
  961. $v.=" READONLY ";
  962. $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
  963. }
  964. }
  965. $current_segment = $$line;
  966. push(@segment_stack, $$line);
  967. $self->{value} = $v;
  968. last;
  969. };
  970. /\.extern/ && do { $self->{value} = "EXTERN\t".$$line;
  971. $self->{value} .= ":NEAR" if ($masm);
  972. last;
  973. };
  974. /\.globl|.global/
  975. && do { $self->{value} = $masm?"PUBLIC":"global";
  976. $self->{value} .= "\t".$$line;
  977. last;
  978. };
  979. /\.size/ && do { if (defined($current_function)) {
  980. undef $self->{value};
  981. if ($current_function->{abi} eq "svr4") {
  982. $self->{value}="${decor}SEH_end_$current_function->{name}:";
  983. $self->{value}.=":\n" if($masm);
  984. }
  985. $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
  986. undef $current_function;
  987. }
  988. last;
  989. };
  990. /\.align/ && do { my $max = ($masm && $masm>=$masmref) ? 256 : 4096;
  991. $self->{value} = "ALIGN\t".($$line>$max?$max:$$line);
  992. last;
  993. };
  994. /\.(value|long|rva|quad)/
  995. && do { my $sz = substr($1,0,1);
  996. my @arr = split(/,\s*/,$$line);
  997. my $last = pop(@arr);
  998. my $conv = sub { my $var=shift;
  999. $var=~s/^(0b[0-1]+)/oct($1)/eig;
  1000. $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
  1001. if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
  1002. { $var=~s/^([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
  1003. $var;
  1004. };
  1005. $sz =~ tr/bvlrq/BWDDQ/;
  1006. $self->{value} = "\tD$sz\t";
  1007. for (@arr) { $self->{value} .= &$conv($_).","; }
  1008. $self->{value} .= &$conv($last);
  1009. last;
  1010. };
  1011. /\.byte/ && do { my @str=split(/,\s*/,$$line);
  1012. map(s/(0b[0-1]+)/oct($1)/eig,@str);
  1013. map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
  1014. while ($#str>15) {
  1015. $self->{value}.="DB\t"
  1016. .join(",",@str[0..15])."\n";
  1017. foreach (0..15) { shift @str; }
  1018. }
  1019. $self->{value}.="DB\t"
  1020. .join(",",@str) if (@str);
  1021. last;
  1022. };
  1023. /\.comm/ && do { my @str=split(/,\s*/,$$line);
  1024. my $v=undef;
  1025. if ($nasm) {
  1026. $v.="common $prefix@str[0] @str[1]";
  1027. } else {
  1028. $current_segment = pop(@segment_stack);;
  1029. $v="$current_segment\tENDS\n" if ($current_segment);
  1030. $current_segment = "_DATA";
  1031. push(@segment_stack, $current_segment);
  1032. $v.="$current_segment\tSEGMENT\n";
  1033. $v.="COMM @str[0]:DWORD:".@str[1]/4;
  1034. }
  1035. $self->{value} = $v;
  1036. last;
  1037. };
  1038. /^.previous/ && do {
  1039. my $v=undef;
  1040. if ($nasm) {
  1041. pop(@segment_stack); # pop ourselves, we don't need to emit END directive
  1042. # pop section so we can emit proper .section name.
  1043. $current_segment = pop(@segment_stack);
  1044. $v="section $current_segment";
  1045. # Hack again:
  1046. # push section/segment to stack. The .previous is currently paired
  1047. # with .rodata only. We have to keep extra '.text' on stack for
  1048. # situation where there is for example .pdata section 'terminated'
  1049. # by new '.text' section.
  1050. #
  1051. push(@segment_stack, $current_segment);
  1052. } else {
  1053. $current_segment = pop(@segment_stack);
  1054. $v="$current_segment\tENDS\n" if ($current_segment);
  1055. $current_segment = pop(@segment_stack);
  1056. if ($current_segment =~ /\.text\$/) {
  1057. $v.="$current_segment\tSEGMENT ";
  1058. $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
  1059. $v.=" 'CODE'";
  1060. push(@segment_stack, $current_segment);
  1061. }
  1062. }
  1063. $self->{value} = $v;
  1064. last;
  1065. };
  1066. }
  1067. $$line = "";
  1068. }
  1069. $ret;
  1070. }
  1071. sub out {
  1072. my $self = shift;
  1073. $self->{value};
  1074. }
  1075. }
  1076. # Upon initial x86_64 introduction SSE>2 extensions were not introduced
  1077. # yet. In order not to be bothered by tracing exact assembler versions,
  1078. # but at the same time to provide a bare security minimum of AES-NI, we
  1079. # hard-code some instructions. Extensions past AES-NI on the other hand
  1080. # are traced by examining assembler version in individual perlasm
  1081. # modules...
  1082. my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
  1083. "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
  1084. sub rex {
  1085. my $opcode=shift;
  1086. my ($dst,$src,$rex)=@_;
  1087. $rex|=0x04 if($dst>=8);
  1088. $rex|=0x01 if($src>=8);
  1089. push @$opcode,($rex|0x40) if ($rex);
  1090. }
  1091. my $movq = sub { # elderly gas can't handle inter-register movq
  1092. my $arg = shift;
  1093. my @opcode=(0x66);
  1094. if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
  1095. my ($src,$dst)=($1,$2);
  1096. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  1097. rex(\@opcode,$src,$dst,0x8);
  1098. push @opcode,0x0f,0x7e;
  1099. push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
  1100. @opcode;
  1101. } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
  1102. my ($src,$dst)=($2,$1);
  1103. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  1104. rex(\@opcode,$src,$dst,0x8);
  1105. push @opcode,0x0f,0x6e;
  1106. push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
  1107. @opcode;
  1108. } else {
  1109. ();
  1110. }
  1111. };
  1112. my $pextrd = sub {
  1113. if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
  1114. my @opcode=(0x66);
  1115. my $imm=$1;
  1116. my $src=$2;
  1117. my $dst=$3;
  1118. if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
  1119. elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
  1120. rex(\@opcode,$src,$dst);
  1121. push @opcode,0x0f,0x3a,0x16;
  1122. push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
  1123. push @opcode,$imm;
  1124. @opcode;
  1125. } else {
  1126. ();
  1127. }
  1128. };
  1129. my $pinsrd = sub {
  1130. if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
  1131. my @opcode=(0x66);
  1132. my $imm=$1;
  1133. my $src=$2;
  1134. my $dst=$3;
  1135. if ($src =~ /%r([0-9]+)/) { $src = $1; }
  1136. elsif ($src =~ /%e/) { $src = $regrm{$src}; }
  1137. rex(\@opcode,$dst,$src);
  1138. push @opcode,0x0f,0x3a,0x22;
  1139. push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
  1140. push @opcode,$imm;
  1141. @opcode;
  1142. } else {
  1143. ();
  1144. }
  1145. };
  1146. my $pshufb = sub {
  1147. if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  1148. my @opcode=(0x66);
  1149. rex(\@opcode,$2,$1);
  1150. push @opcode,0x0f,0x38,0x00;
  1151. push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
  1152. @opcode;
  1153. } else {
  1154. ();
  1155. }
  1156. };
  1157. my $palignr = sub {
  1158. if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  1159. my @opcode=(0x66);
  1160. rex(\@opcode,$3,$2);
  1161. push @opcode,0x0f,0x3a,0x0f;
  1162. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  1163. push @opcode,$1;
  1164. @opcode;
  1165. } else {
  1166. ();
  1167. }
  1168. };
  1169. my $pclmulqdq = sub {
  1170. if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  1171. my @opcode=(0x66);
  1172. rex(\@opcode,$3,$2);
  1173. push @opcode,0x0f,0x3a,0x44;
  1174. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  1175. my $c=$1;
  1176. push @opcode,$c=~/^0/?oct($c):$c;
  1177. @opcode;
  1178. } else {
  1179. ();
  1180. }
  1181. };
  1182. my $rdrand = sub {
  1183. if (shift =~ /%[er](\w+)/) {
  1184. my @opcode=();
  1185. my $dst=$1;
  1186. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  1187. rex(\@opcode,0,$dst,8);
  1188. push @opcode,0x0f,0xc7,0xf0|($dst&7);
  1189. @opcode;
  1190. } else {
  1191. ();
  1192. }
  1193. };
  1194. my $rdseed = sub {
  1195. if (shift =~ /%[er](\w+)/) {
  1196. my @opcode=();
  1197. my $dst=$1;
  1198. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  1199. rex(\@opcode,0,$dst,8);
  1200. push @opcode,0x0f,0xc7,0xf8|($dst&7);
  1201. @opcode;
  1202. } else {
  1203. ();
  1204. }
  1205. };
  1206. # Not all AVX-capable assemblers recognize AMD XOP extension. Since we
  1207. # are using only two instructions hand-code them in order to be excused
  1208. # from chasing assembler versions...
  1209. sub rxb {
  1210. my $opcode=shift;
  1211. my ($dst,$src1,$src2,$rxb)=@_;
  1212. $rxb|=0x7<<5;
  1213. $rxb&=~(0x04<<5) if($dst>=8);
  1214. $rxb&=~(0x01<<5) if($src1>=8);
  1215. $rxb&=~(0x02<<5) if($src2>=8);
  1216. push @$opcode,$rxb;
  1217. }
  1218. my $vprotd = sub {
  1219. if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  1220. my @opcode=(0x8f);
  1221. rxb(\@opcode,$3,$2,-1,0x08);
  1222. push @opcode,0x78,0xc2;
  1223. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  1224. my $c=$1;
  1225. push @opcode,$c=~/^0/?oct($c):$c;
  1226. @opcode;
  1227. } else {
  1228. ();
  1229. }
  1230. };
  1231. my $vprotq = sub {
  1232. if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  1233. my @opcode=(0x8f);
  1234. rxb(\@opcode,$3,$2,-1,0x08);
  1235. push @opcode,0x78,0xc3;
  1236. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  1237. my $c=$1;
  1238. push @opcode,$c=~/^0/?oct($c):$c;
  1239. @opcode;
  1240. } else {
  1241. ();
  1242. }
  1243. };
  1244. # Intel Control-flow Enforcement Technology extension. All functions and
  1245. # indirect branch targets will have to start with this instruction...
  1246. my $endbranch = sub {
  1247. (0xf3,0x0f,0x1e,0xfa);
  1248. };
  1249. ########################################################################
  1250. if ($nasm) {
  1251. print <<___;
  1252. default rel
  1253. %define XMMWORD
  1254. %define YMMWORD
  1255. %define ZMMWORD
  1256. ___
  1257. } elsif ($masm) {
  1258. print <<___;
  1259. OPTION DOTNAME
  1260. ___
  1261. }
  1262. while(defined(my $line=<>)) {
  1263. $line =~ s|\R$||; # Better chomp
  1264. $line =~ s|[#!].*$||; # get rid of asm-style comments...
  1265. $line =~ s|/\*.*\*/||; # ... and C-style comments...
  1266. $line =~ s|^\s+||; # ... and skip whitespaces in beginning
  1267. $line =~ s|\s+$||; # ... and at the end
  1268. if (my $label=label->re(\$line)) { print $label->out(); }
  1269. if (my $directive=directive->re(\$line)) {
  1270. printf "%s",$directive->out();
  1271. } elsif (my $opcode=opcode->re(\$line)) {
  1272. my $asm = eval("\$".$opcode->mnemonic());
  1273. if ((ref($asm) eq 'CODE') && scalar(my @bytes=&$asm($line))) {
  1274. print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
  1275. next;
  1276. }
  1277. my @args;
  1278. ARGUMENT: while (1) {
  1279. my $arg;
  1280. ($arg=register->re(\$line, $opcode))||
  1281. ($arg=const->re(\$line)) ||
  1282. ($arg=ea->re(\$line, $opcode)) ||
  1283. ($arg=expr->re(\$line, $opcode)) ||
  1284. last ARGUMENT;
  1285. push @args,$arg;
  1286. last ARGUMENT if ($line !~ /^,/);
  1287. $line =~ s/^,\s*//;
  1288. } # ARGUMENT:
  1289. if ($#args>=0) {
  1290. my $insn;
  1291. my $sz=$opcode->size();
  1292. if ($gas) {
  1293. $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
  1294. @args = map($_->out($sz),@args);
  1295. printf "\t%s\t%s",$insn,join(",",@args);
  1296. } else {
  1297. $insn = $opcode->out();
  1298. foreach (@args) {
  1299. my $arg = $_->out();
  1300. # $insn.=$sz compensates for movq, pinsrw, ...
  1301. if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
  1302. if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
  1303. if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
  1304. if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
  1305. }
  1306. @args = reverse(@args);
  1307. undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
  1308. printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
  1309. }
  1310. } else {
  1311. printf "\t%s",$opcode->out();
  1312. }
  1313. }
  1314. print $line,"\n";
  1315. }
  1316. print "$cet_property" if ($cet_property);
  1317. print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
  1318. print "END\n" if ($masm);
  1319. close STDOUT or die "error closing STDOUT: $!;"
  1320. #################################################
  1321. # Cross-reference x86_64 ABI "card"
  1322. #
  1323. # Unix Win64
  1324. # %rax * *
  1325. # %rbx - -
  1326. # %rcx #4 #1
  1327. # %rdx #3 #2
  1328. # %rsi #2 -
  1329. # %rdi #1 -
  1330. # %rbp - -
  1331. # %rsp - -
  1332. # %r8 #5 #3
  1333. # %r9 #6 #4
  1334. # %r10 * *
  1335. # %r11 * *
  1336. # %r12 - -
  1337. # %r13 - -
  1338. # %r14 - -
  1339. # %r15 - -
  1340. #
  1341. # (*) volatile register
  1342. # (-) preserved by callee
  1343. # (#) Nth argument, volatile
  1344. #
  1345. # In Unix terms top of stack is argument transfer area for arguments
  1346. # which could not be accommodated in registers. Or in other words 7th
  1347. # [integer] argument resides at 8(%rsp) upon function entry point.
  1348. # 128 bytes above %rsp constitute a "red zone" which is not touched
  1349. # by signal handlers and can be used as temporal storage without
  1350. # allocating a frame.
  1351. #
  1352. # In Win64 terms N*8 bytes on top of stack is argument transfer area,
  1353. # which belongs to/can be overwritten by callee. N is the number of
  1354. # arguments passed to callee, *but* not less than 4! This means that
  1355. # upon function entry point 5th argument resides at 40(%rsp), as well
  1356. # as that 32 bytes from 8(%rsp) can always be used as temporal
  1357. # storage [without allocating a frame]. One can actually argue that
  1358. # one can assume a "red zone" above stack pointer under Win64 as well.
  1359. # Point is that at apparently no occasion Windows kernel would alter
  1360. # the area above user stack pointer in true asynchronous manner...
  1361. #
  1362. # All the above means that if assembler programmer adheres to Unix
  1363. # register and stack layout, but disregards the "red zone" existence,
  1364. # it's possible to use following prologue and epilogue to "gear" from
  1365. # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
  1366. #
  1367. # omnipotent_function:
  1368. # ifdef WIN64
  1369. # movq %rdi,8(%rsp)
  1370. # movq %rsi,16(%rsp)
  1371. # movq %rcx,%rdi ; if 1st argument is actually present
  1372. # movq %rdx,%rsi ; if 2nd argument is actually ...
  1373. # movq %r8,%rdx ; if 3rd argument is ...
  1374. # movq %r9,%rcx ; if 4th argument ...
  1375. # movq 40(%rsp),%r8 ; if 5th ...
  1376. # movq 48(%rsp),%r9 ; if 6th ...
  1377. # endif
  1378. # ...
  1379. # ifdef WIN64
  1380. # movq 8(%rsp),%rdi
  1381. # movq 16(%rsp),%rsi
  1382. # endif
  1383. # ret
  1384. #
  1385. #################################################
  1386. # Win64 SEH, Structured Exception Handling.
  1387. #
  1388. # Unlike on Unix systems(*) lack of Win64 stack unwinding information
  1389. # has undesired side-effect at run-time: if an exception is raised in
  1390. # assembler subroutine such as those in question (basically we're
  1391. # referring to segmentation violations caused by malformed input
  1392. # parameters), the application is briskly terminated without invoking
  1393. # any exception handlers, most notably without generating memory dump
  1394. # or any user notification whatsoever. This poses a problem. It's
  1395. # possible to address it by registering custom language-specific
  1396. # handler that would restore processor context to the state at
  1397. # subroutine entry point and return "exception is not handled, keep
  1398. # unwinding" code. Writing such handler can be a challenge... But it's
  1399. # doable, though requires certain coding convention. Consider following
  1400. # snippet:
  1401. #
  1402. # .type function,@function
  1403. # function:
  1404. # movq %rsp,%rax # copy rsp to volatile register
  1405. # pushq %r15 # save non-volatile registers
  1406. # pushq %rbx
  1407. # pushq %rbp
  1408. # movq %rsp,%r11
  1409. # subq %rdi,%r11 # prepare [variable] stack frame
  1410. # andq $-64,%r11
  1411. # movq %rax,0(%r11) # check for exceptions
  1412. # movq %r11,%rsp # allocate [variable] stack frame
  1413. # movq %rax,0(%rsp) # save original rsp value
  1414. # magic_point:
  1415. # ...
  1416. # movq 0(%rsp),%rcx # pull original rsp value
  1417. # movq -24(%rcx),%rbp # restore non-volatile registers
  1418. # movq -16(%rcx),%rbx
  1419. # movq -8(%rcx),%r15
  1420. # movq %rcx,%rsp # restore original rsp
  1421. # magic_epilogue:
  1422. # ret
  1423. # .size function,.-function
  1424. #
  1425. # The key is that up to magic_point copy of original rsp value remains
  1426. # in chosen volatile register and no non-volatile register, except for
  1427. # rsp, is modified. While past magic_point rsp remains constant till
  1428. # the very end of the function. In this case custom language-specific
  1429. # exception handler would look like this:
  1430. #
  1431. # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
  1432. # CONTEXT *context,DISPATCHER_CONTEXT *disp)
  1433. # { ULONG64 *rsp = (ULONG64 *)context->Rax;
  1434. # ULONG64 rip = context->Rip;
  1435. #
  1436. # if (rip >= magic_point)
  1437. # { rsp = (ULONG64 *)context->Rsp;
  1438. # if (rip < magic_epilogue)
  1439. # { rsp = (ULONG64 *)rsp[0];
  1440. # context->Rbp = rsp[-3];
  1441. # context->Rbx = rsp[-2];
  1442. # context->R15 = rsp[-1];
  1443. # }
  1444. # }
  1445. # context->Rsp = (ULONG64)rsp;
  1446. # context->Rdi = rsp[1];
  1447. # context->Rsi = rsp[2];
  1448. #
  1449. # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
  1450. # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
  1451. # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
  1452. # &disp->HandlerData,&disp->EstablisherFrame,NULL);
  1453. # return ExceptionContinueSearch;
  1454. # }
  1455. #
  1456. # It's appropriate to implement this handler in assembler, directly in
  1457. # function's module. In order to do that one has to know members'
  1458. # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
  1459. # values. Here they are:
  1460. #
  1461. # CONTEXT.Rax 120
  1462. # CONTEXT.Rcx 128
  1463. # CONTEXT.Rdx 136
  1464. # CONTEXT.Rbx 144
  1465. # CONTEXT.Rsp 152
  1466. # CONTEXT.Rbp 160
  1467. # CONTEXT.Rsi 168
  1468. # CONTEXT.Rdi 176
  1469. # CONTEXT.R8 184
  1470. # CONTEXT.R9 192
  1471. # CONTEXT.R10 200
  1472. # CONTEXT.R11 208
  1473. # CONTEXT.R12 216
  1474. # CONTEXT.R13 224
  1475. # CONTEXT.R14 232
  1476. # CONTEXT.R15 240
  1477. # CONTEXT.Rip 248
  1478. # CONTEXT.Xmm6 512
  1479. # sizeof(CONTEXT) 1232
  1480. # DISPATCHER_CONTEXT.ControlPc 0
  1481. # DISPATCHER_CONTEXT.ImageBase 8
  1482. # DISPATCHER_CONTEXT.FunctionEntry 16
  1483. # DISPATCHER_CONTEXT.EstablisherFrame 24
  1484. # DISPATCHER_CONTEXT.TargetIp 32
  1485. # DISPATCHER_CONTEXT.ContextRecord 40
  1486. # DISPATCHER_CONTEXT.LanguageHandler 48
  1487. # DISPATCHER_CONTEXT.HandlerData 56
  1488. # UNW_FLAG_NHANDLER 0
  1489. # ExceptionContinueSearch 1
  1490. #
  1491. # In order to tie the handler to the function one has to compose
  1492. # couple of structures: one for .xdata segment and one for .pdata.
  1493. #
  1494. # UNWIND_INFO structure for .xdata segment would be
  1495. #
  1496. # function_unwind_info:
  1497. # .byte 9,0,0,0
  1498. # .rva handler
  1499. #
  1500. # This structure designates exception handler for a function with
  1501. # zero-length prologue, no stack frame or frame register.
  1502. #
  1503. # To facilitate composing of .pdata structures, auto-generated "gear"
  1504. # prologue copies rsp value to rax and denotes next instruction with
  1505. # .LSEH_begin_{function_name} label. This essentially defines the SEH
  1506. # styling rule mentioned in the beginning. Position of this label is
  1507. # chosen in such manner that possible exceptions raised in the "gear"
  1508. # prologue would be accounted to caller and unwound from latter's frame.
  1509. # End of function is marked with respective .LSEH_end_{function_name}
  1510. # label. To summarize, .pdata segment would contain
  1511. #
  1512. # .rva .LSEH_begin_function
  1513. # .rva .LSEH_end_function
  1514. # .rva function_unwind_info
  1515. #
  1516. # Reference to function_unwind_info from .xdata segment is the anchor.
  1517. # In case you wonder why references are 32-bit .rvas and not 64-bit
  1518. # .quads. References put into these two segments are required to be
  1519. # *relative* to the base address of the current binary module, a.k.a.
  1520. # image base. No Win64 module, be it .exe or .dll, can be larger than
  1521. # 2GB and thus such relative references can be and are accommodated in
  1522. # 32 bits.
  1523. #
  1524. # Having reviewed the example function code, one can argue that "movq
  1525. # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
  1526. # rax would contain an undefined value. If this "offends" you, use
  1527. # another register and refrain from modifying rax till magic_point is
  1528. # reached, i.e. as if it was a non-volatile register. If more registers
  1529. # are required prior [variable] frame setup is completed, note that
  1530. # nobody says that you can have only one "magic point." You can
  1531. # "liberate" non-volatile registers by denoting last stack off-load
  1532. # instruction and reflecting it in finer grade unwind logic in handler.
  1533. # After all, isn't it why it's called *language-specific* handler...
  1534. #
  1535. # SE handlers are also involved in unwinding stack when executable is
  1536. # profiled or debugged. Profiling implies additional limitations that
  1537. # are too subtle to discuss here. For now it's sufficient to say that
  1538. # in order to simplify handlers one should either a) offload original
  1539. # %rsp to stack (like discussed above); or b) if you have a register to
  1540. # spare for frame pointer, choose volatile one.
  1541. #
  1542. # (*) Note that we're talking about run-time, not debug-time. Lack of
  1543. # unwind information makes debugging hard on both Windows and
  1544. # Unix. "Unlike" refers to the fact that on Unix signal handler
  1545. # will always be invoked, core dumped and appropriate exit code
  1546. # returned to parent (for user notification).