x86_64-xlate.pl 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. #!/usr/bin/env perl
  2. # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
  3. #
  4. # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
  5. # format is way easier to parse. Because it's simpler to "gear" from
  6. # Unix ABI to Windows one [see cross-reference "card" at the end of
  7. # file]. Because Linux targets were available first...
  8. #
  9. # In addition the script also "distills" code suitable for GNU
  10. # assembler, so that it can be compiled with more rigid assemblers,
  11. # such as Solaris /usr/ccs/bin/as.
  12. #
  13. # This translator is not designed to convert *arbitrary* assembler
  14. # code from AT&T format to MASM one. It's designed to convert just
  15. # enough to provide for dual-ABI OpenSSL modules development...
  16. # There *are* limitations and you might have to modify your assembler
  17. # code or this script to achieve the desired result...
  18. #
  19. # Currently recognized limitations:
  20. #
  21. # - can't use multiple ops per line;
  22. #
  23. # Dual-ABI styling rules.
  24. #
  25. # 1. Adhere to Unix register and stack layout [see cross-reference
  26. # ABI "card" at the end for explanation].
  27. # 2. Forget about "red zone," stick to more traditional blended
  28. # stack frame allocation. If volatile storage is actually required
  29. # that is. If not, just leave the stack as is.
  30. # 3. Functions tagged with ".type name,@function" get crafted with
  31. # unified Win64 prologue and epilogue automatically. If you want
  32. # to take care of ABI differences yourself, tag functions as
  33. # ".type name,@abi-omnipotent" instead.
  34. # 4. To optimize the Win64 prologue you can specify number of input
  35. # arguments as ".type name,@function,N." Keep in mind that if N is
  36. # larger than 6, then you *have to* write "abi-omnipotent" code,
  37. # because >6 cases can't be addressed with unified prologue.
  38. # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
  39. # (sorry about latter).
  40. # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
  41. # required to identify the spots, where to inject Win64 epilogue!
  42. # But on the pros, it's then prefixed with rep automatically:-)
  43. # 7. Stick to explicit ip-relative addressing. If you have to use
  44. # GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
  45. # Both are recognized and translated to proper Win64 addressing
  46. # modes. To support legacy code a synthetic directive, .picmeup,
  47. # is implemented. It puts address of the *next* instruction into
  48. # target register, e.g.:
  49. #
  50. # .picmeup %rax
  51. # lea .Label-.(%rax),%rax
  52. #
  53. # 8. In order to provide for structured exception handling unified
  54. # Win64 prologue copies %rsp value to %rax. For further details
  55. # see SEH paragraph at the end.
  56. # 9. .init segment is allowed to contain calls to functions only.
  57. # a. If function accepts more than 4 arguments *and* >4th argument
  58. # is declared as non 64-bit value, do clear its upper part.
  59. my $flavour = shift;
  60. my $output = shift;
  61. if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
  62. open STDOUT,">$output" || die "can't open $output: $!"
  63. if (defined($output));
  64. my $gas=1; $gas=0 if ($output =~ /\.asm$/);
  65. my $elf=1; $elf=0 if (!$gas);
  66. my $win64=0;
  67. my $prefix="";
  68. my $decor=".L";
  69. my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
  70. my $masm=0;
  71. my $PTR=" PTR";
  72. my $nasmref=2.03;
  73. my $nasm=0;
  74. if ($flavour eq "mingw64") { $gas=1; $elf=0; $win64=1;
  75. $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
  76. chomp($prefix);
  77. }
  78. elsif ($flavour eq "macosx") { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
  79. elsif ($flavour eq "masm") { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
  80. elsif ($flavour eq "nasm") { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
  81. elsif (!$gas)
  82. { if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
  83. { $nasm = $1 + $2*0.01; $PTR=""; }
  84. elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
  85. { $masm = $1 + $2*2**-16 + $4*2**-32; }
  86. die "no assembler found on %PATH" if (!($nasm || $masm));
  87. $win64=1;
  88. $elf=0;
  89. $decor="\$L\$";
  90. }
  91. my $current_segment;
  92. my $current_function;
  93. my %globals;
  94. { package opcode; # pick up opcodes
  95. sub re {
  96. my $self = shift; # single instance in enough...
  97. local *line = shift;
  98. undef $ret;
  99. if ($line =~ /^([a-z][a-z0-9]*)/i) {
  100. $self->{op} = $1;
  101. $ret = $self;
  102. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  103. undef $self->{sz};
  104. if ($self->{op} =~ /^(movz)x?([bw]).*/) { # movz is pain...
  105. $self->{op} = $1;
  106. $self->{sz} = $2;
  107. } elsif ($self->{op} =~ /call|jmp/) {
  108. $self->{sz} = "";
  109. } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
  110. $self->{sz} = "";
  111. } elsif ($self->{op} =~ /^v/) { # VEX
  112. $self->{sz} = "";
  113. } elsif ($self->{op} =~ /mov[dq]/ && $line =~ /%xmm/) {
  114. $self->{sz} = "";
  115. } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
  116. $self->{op} = $1;
  117. $self->{sz} = $2;
  118. }
  119. }
  120. $ret;
  121. }
  122. sub size {
  123. my $self = shift;
  124. my $sz = shift;
  125. $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
  126. $self->{sz};
  127. }
  128. sub out {
  129. my $self = shift;
  130. if ($gas) {
  131. if ($self->{op} eq "movz") { # movz is pain...
  132. sprintf "%s%s%s",$self->{op},$self->{sz},shift;
  133. } elsif ($self->{op} =~ /^set/) {
  134. "$self->{op}";
  135. } elsif ($self->{op} eq "ret") {
  136. my $epilogue = "";
  137. if ($win64 && $current_function->{abi} eq "svr4") {
  138. $epilogue = "movq 8(%rsp),%rdi\n\t" .
  139. "movq 16(%rsp),%rsi\n\t";
  140. }
  141. $epilogue . ".byte 0xf3,0xc3";
  142. } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
  143. ".p2align\t3\n\t.quad";
  144. } else {
  145. "$self->{op}$self->{sz}";
  146. }
  147. } else {
  148. $self->{op} =~ s/^movz/movzx/;
  149. if ($self->{op} eq "ret") {
  150. $self->{op} = "";
  151. if ($win64 && $current_function->{abi} eq "svr4") {
  152. $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
  153. "mov rsi,QWORD${PTR}[16+rsp]\n\t";
  154. }
  155. $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
  156. } elsif ($self->{op} =~ /^(pop|push)f/) {
  157. $self->{op} .= $self->{sz};
  158. } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
  159. $self->{op} = "\tDQ";
  160. }
  161. $self->{op};
  162. }
  163. }
  164. sub mnemonic {
  165. my $self=shift;
  166. my $op=shift;
  167. $self->{op}=$op if (defined($op));
  168. $self->{op};
  169. }
  170. }
  171. { package const; # pick up constants, which start with $
  172. sub re {
  173. my $self = shift; # single instance in enough...
  174. local *line = shift;
  175. undef $ret;
  176. if ($line =~ /^\$([^,]+)/) {
  177. $self->{value} = $1;
  178. $ret = $self;
  179. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  180. }
  181. $ret;
  182. }
  183. sub out {
  184. my $self = shift;
  185. if ($gas) {
  186. # Solaris /usr/ccs/bin/as can't handle multiplications
  187. # in $self->{value}
  188. $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
  189. $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
  190. sprintf "\$%s",$self->{value};
  191. } else {
  192. $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
  193. $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
  194. sprintf "%s",$self->{value};
  195. }
  196. }
  197. }
  198. { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
  199. sub re {
  200. my $self = shift; # single instance in enough...
  201. local *line = shift;
  202. undef $ret;
  203. # optional * ---vvv--- appears in indirect jmp/call
  204. if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
  205. $self->{asterisk} = $1;
  206. $self->{label} = $2;
  207. ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
  208. $self->{scale} = 1 if (!defined($self->{scale}));
  209. $ret = $self;
  210. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  211. if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
  212. die if (opcode->mnemonic() ne "mov");
  213. opcode->mnemonic("lea");
  214. }
  215. $self->{base} =~ s/^%//;
  216. $self->{index} =~ s/^%// if (defined($self->{index}));
  217. }
  218. $ret;
  219. }
  220. sub size {}
  221. sub out {
  222. my $self = shift;
  223. my $sz = shift;
  224. $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
  225. $self->{label} =~ s/\.L/$decor/g;
  226. # Silently convert all EAs to 64-bit. This is required for
  227. # elder GNU assembler and results in more compact code,
  228. # *but* most importantly AES module depends on this feature!
  229. $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
  230. $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
  231. # Solaris /usr/ccs/bin/as can't handle multiplications
  232. # in $self->{label}, new gas requires sign extension...
  233. use integer;
  234. $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
  235. $self->{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
  236. $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
  237. if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
  238. $self->{base} =~ /(rbp|r13)/) {
  239. $self->{base} = $self->{index}; $self->{index} = $1;
  240. }
  241. if ($gas) {
  242. $self->{label} =~ s/^___imp_/__imp__/ if ($flavour eq "mingw64");
  243. if (defined($self->{index})) {
  244. sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
  245. $self->{label},
  246. $self->{base}?"%$self->{base}":"",
  247. $self->{index},$self->{scale};
  248. } else {
  249. sprintf "%s%s(%%%s)", $self->{asterisk},$self->{label},$self->{base};
  250. }
  251. } else {
  252. %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR",
  253. l=>"DWORD$PTR", d=>"DWORD$PTR",
  254. q=>"QWORD$PTR", o=>"OWORD$PTR",
  255. x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
  256. $self->{label} =~ s/\./\$/g;
  257. $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
  258. $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
  259. ($self->{asterisk}) && ($sz="q") ||
  260. (opcode->mnemonic() =~ /^v?mov([qd])$/) && ($sz=$1) ||
  261. (opcode->mnemonic() =~ /^v?pinsr([qdwb])$/) && ($sz=$1) ||
  262. (opcode->mnemonic() =~ /^vpbroadcast([qdwb])$/) && ($sz=$1) ||
  263. (opcode->mnemonic() =~ /^vinsert[fi]128$/) && ($sz="x");
  264. if (defined($self->{index})) {
  265. sprintf "%s[%s%s*%d%s]",$szmap{$sz},
  266. $self->{label}?"$self->{label}+":"",
  267. $self->{index},$self->{scale},
  268. $self->{base}?"+$self->{base}":"";
  269. } elsif ($self->{base} eq "rip") {
  270. sprintf "%s[%s]",$szmap{$sz},$self->{label};
  271. } else {
  272. sprintf "%s[%s%s]",$szmap{$sz},
  273. $self->{label}?"$self->{label}+":"",
  274. $self->{base};
  275. }
  276. }
  277. }
  278. }
  279. { package register; # pick up registers, which start with %.
  280. sub re {
  281. my $class = shift; # muliple instances...
  282. my $self = {};
  283. local *line = shift;
  284. undef $ret;
  285. # optional * ---vvv--- appears in indirect jmp/call
  286. if ($line =~ /^(\*?)%(\w+)/) {
  287. bless $self,$class;
  288. $self->{asterisk} = $1;
  289. $self->{value} = $2;
  290. $ret = $self;
  291. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  292. }
  293. $ret;
  294. }
  295. sub size {
  296. my $self = shift;
  297. undef $ret;
  298. if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
  299. elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
  300. elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
  301. elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
  302. elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
  303. elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
  304. elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
  305. elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
  306. $ret;
  307. }
  308. sub out {
  309. my $self = shift;
  310. if ($gas) { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
  311. else { $self->{value}; }
  312. }
  313. }
  314. { package label; # pick up labels, which end with :
  315. sub re {
  316. my $self = shift; # single instance is enough...
  317. local *line = shift;
  318. undef $ret;
  319. if ($line =~ /(^[\.\w]+)\:/) {
  320. $self->{value} = $1;
  321. $ret = $self;
  322. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  323. $self->{value} =~ s/^\.L/$decor/;
  324. }
  325. $ret;
  326. }
  327. sub out {
  328. my $self = shift;
  329. if ($gas) {
  330. my $func = ($globals{$self->{value}} or $self->{value}) . ":";
  331. if ($win64 &&
  332. $current_function->{name} eq $self->{value} &&
  333. $current_function->{abi} eq "svr4") {
  334. $func .= "\n";
  335. $func .= " movq %rdi,8(%rsp)\n";
  336. $func .= " movq %rsi,16(%rsp)\n";
  337. $func .= " movq %rsp,%rax\n";
  338. $func .= "${decor}SEH_begin_$current_function->{name}:\n";
  339. my $narg = $current_function->{narg};
  340. $narg=6 if (!defined($narg));
  341. $func .= " movq %rcx,%rdi\n" if ($narg>0);
  342. $func .= " movq %rdx,%rsi\n" if ($narg>1);
  343. $func .= " movq %r8,%rdx\n" if ($narg>2);
  344. $func .= " movq %r9,%rcx\n" if ($narg>3);
  345. $func .= " movq 40(%rsp),%r8\n" if ($narg>4);
  346. $func .= " movq 48(%rsp),%r9\n" if ($narg>5);
  347. }
  348. $func;
  349. } elsif ($self->{value} ne "$current_function->{name}") {
  350. $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
  351. $self->{value} . ":";
  352. } elsif ($win64 && $current_function->{abi} eq "svr4") {
  353. my $func = "$current_function->{name}" .
  354. ($nasm ? ":" : "\tPROC $current_function->{scope}") .
  355. "\n";
  356. $func .= " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
  357. $func .= " mov QWORD${PTR}[16+rsp],rsi\n";
  358. $func .= " mov rax,rsp\n";
  359. $func .= "${decor}SEH_begin_$current_function->{name}:";
  360. $func .= ":" if ($masm);
  361. $func .= "\n";
  362. my $narg = $current_function->{narg};
  363. $narg=6 if (!defined($narg));
  364. $func .= " mov rdi,rcx\n" if ($narg>0);
  365. $func .= " mov rsi,rdx\n" if ($narg>1);
  366. $func .= " mov rdx,r8\n" if ($narg>2);
  367. $func .= " mov rcx,r9\n" if ($narg>3);
  368. $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
  369. $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
  370. $func .= "\n";
  371. } else {
  372. "$current_function->{name}".
  373. ($nasm ? ":" : "\tPROC $current_function->{scope}");
  374. }
  375. }
  376. }
  377. { package expr; # pick up expressioins
  378. sub re {
  379. my $self = shift; # single instance is enough...
  380. local *line = shift;
  381. undef $ret;
  382. if ($line =~ /(^[^,]+)/) {
  383. $self->{value} = $1;
  384. $ret = $self;
  385. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  386. $self->{value} =~ s/\@PLT// if (!$elf);
  387. $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
  388. $self->{value} =~ s/\.L/$decor/g;
  389. }
  390. $ret;
  391. }
  392. sub out {
  393. my $self = shift;
  394. if ($nasm && opcode->mnemonic()=~m/^j(?![re]cxz)/) {
  395. "NEAR ".$self->{value};
  396. } else {
  397. $self->{value};
  398. }
  399. }
  400. }
  401. { package directive; # pick up directives, which start with .
  402. sub re {
  403. my $self = shift; # single instance is enough...
  404. local *line = shift;
  405. undef $ret;
  406. my $dir;
  407. my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
  408. ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
  409. "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
  410. "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
  411. "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
  412. "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
  413. "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
  414. "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
  415. "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
  416. if ($line =~ /^\s*(\.\w+)/) {
  417. $dir = $1;
  418. $ret = $self;
  419. undef $self->{value};
  420. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  421. SWITCH: for ($dir) {
  422. /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
  423. $dir="\t.long";
  424. $line=sprintf "0x%x,0x90000000",$opcode{$1};
  425. }
  426. last;
  427. };
  428. /\.global|\.globl|\.extern/
  429. && do { $globals{$line} = $prefix . $line;
  430. $line = $globals{$line} if ($prefix);
  431. last;
  432. };
  433. /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
  434. if ($type eq "\@function") {
  435. undef $current_function;
  436. $current_function->{name} = $sym;
  437. $current_function->{abi} = "svr4";
  438. $current_function->{narg} = $narg;
  439. $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
  440. } elsif ($type eq "\@abi-omnipotent") {
  441. undef $current_function;
  442. $current_function->{name} = $sym;
  443. $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
  444. }
  445. $line =~ s/\@abi\-omnipotent/\@function/;
  446. $line =~ s/\@function.*/\@function/;
  447. last;
  448. };
  449. /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
  450. $dir = ".byte";
  451. $line = join(",",unpack("C*",$1),0);
  452. }
  453. last;
  454. };
  455. /\.rva|\.long|\.quad/
  456. && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
  457. $line =~ s/\.L/$decor/g;
  458. last;
  459. };
  460. }
  461. if ($gas) {
  462. $self->{value} = $dir . "\t" . $line;
  463. if ($dir =~ /\.extern/) {
  464. $self->{value} = ""; # swallow extern
  465. } elsif (!$elf && $dir =~ /\.type/) {
  466. $self->{value} = "";
  467. $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
  468. (defined($globals{$1})?".scl 2;":".scl 3;") .
  469. "\t.type 32;\t.endef"
  470. if ($win64 && $line =~ /([^,]+),\@function/);
  471. } elsif (!$elf && $dir =~ /\.size/) {
  472. $self->{value} = "";
  473. if (defined($current_function)) {
  474. $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
  475. if ($win64 && $current_function->{abi} eq "svr4");
  476. undef $current_function;
  477. }
  478. } elsif (!$elf && $dir =~ /\.align/) {
  479. $self->{value} = ".p2align\t" . (log($line)/log(2));
  480. } elsif ($dir eq ".section") {
  481. $current_segment=$line;
  482. if (!$elf && $current_segment eq ".init") {
  483. if ($flavour eq "macosx") { $self->{value} = ".mod_init_func"; }
  484. elsif ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
  485. }
  486. } elsif ($dir =~ /\.(text|data)/) {
  487. $current_segment=".$1";
  488. } elsif ($dir =~ /\.hidden/) {
  489. if ($flavour eq "macosx") { $self->{value} = ".private_extern\t$prefix$line"; }
  490. elsif ($flavour eq "mingw64") { $self->{value} = ""; }
  491. } elsif ($dir =~ /\.comm/) {
  492. $self->{value} = "$dir\t$prefix$line";
  493. $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
  494. }
  495. $line = "";
  496. return $self;
  497. }
  498. # non-gas case or nasm/masm
  499. SWITCH: for ($dir) {
  500. /\.text/ && do { my $v=undef;
  501. if ($nasm) {
  502. $v="section .text code align=64\n";
  503. } else {
  504. $v="$current_segment\tENDS\n" if ($current_segment);
  505. $current_segment = ".text\$";
  506. $v.="$current_segment\tSEGMENT ";
  507. $v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
  508. $v.=" 'CODE'";
  509. }
  510. $self->{value} = $v;
  511. last;
  512. };
  513. /\.data/ && do { my $v=undef;
  514. if ($nasm) {
  515. $v="section .data data align=8\n";
  516. } else {
  517. $v="$current_segment\tENDS\n" if ($current_segment);
  518. $current_segment = "_DATA";
  519. $v.="$current_segment\tSEGMENT";
  520. }
  521. $self->{value} = $v;
  522. last;
  523. };
  524. /\.section/ && do { my $v=undef;
  525. $line =~ s/([^,]*).*/$1/;
  526. $line = ".CRT\$XCU" if ($line eq ".init");
  527. if ($nasm) {
  528. $v="section $line";
  529. if ($line=~/\.([px])data/) {
  530. $v.=" rdata align=";
  531. $v.=$1 eq "p"? 4 : 8;
  532. } elsif ($line=~/\.CRT\$/i) {
  533. $v.=" rdata align=8";
  534. }
  535. } else {
  536. $v="$current_segment\tENDS\n" if ($current_segment);
  537. $v.="$line\tSEGMENT";
  538. if ($line=~/\.([px])data/) {
  539. $v.=" READONLY";
  540. $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
  541. } elsif ($line=~/\.CRT\$/i) {
  542. $v.=" READONLY ";
  543. $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
  544. }
  545. }
  546. $current_segment = $line;
  547. $self->{value} = $v;
  548. last;
  549. };
  550. /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
  551. $self->{value} .= ":NEAR" if ($masm);
  552. last;
  553. };
  554. /\.globl|.global/
  555. && do { $self->{value} = $masm?"PUBLIC":"global";
  556. $self->{value} .= "\t".$line;
  557. last;
  558. };
  559. /\.size/ && do { if (defined($current_function)) {
  560. undef $self->{value};
  561. if ($current_function->{abi} eq "svr4") {
  562. $self->{value}="${decor}SEH_end_$current_function->{name}:";
  563. $self->{value}.=":\n" if($masm);
  564. }
  565. $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
  566. undef $current_function;
  567. }
  568. last;
  569. };
  570. /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
  571. /\.(value|long|rva|quad)/
  572. && do { my $sz = substr($1,0,1);
  573. my @arr = split(/,\s*/,$line);
  574. my $last = pop(@arr);
  575. my $conv = sub { my $var=shift;
  576. $var=~s/^(0b[0-1]+)/oct($1)/eig;
  577. $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
  578. if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
  579. { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
  580. $var;
  581. };
  582. $sz =~ tr/bvlrq/BWDDQ/;
  583. $self->{value} = "\tD$sz\t";
  584. for (@arr) { $self->{value} .= &$conv($_).","; }
  585. $self->{value} .= &$conv($last);
  586. last;
  587. };
  588. /\.byte/ && do { my @str=split(/,\s*/,$line);
  589. map(s/(0b[0-1]+)/oct($1)/eig,@str);
  590. map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);
  591. while ($#str>15) {
  592. $self->{value}.="DB\t"
  593. .join(",",@str[0..15])."\n";
  594. foreach (0..15) { shift @str; }
  595. }
  596. $self->{value}.="DB\t"
  597. .join(",",@str) if (@str);
  598. last;
  599. };
  600. /\.comm/ && do { my @str=split(/,\s*/,$line);
  601. my $v=undef;
  602. if ($nasm) {
  603. $v.="common $prefix@str[0] @str[1]";
  604. } else {
  605. $v="$current_segment\tENDS\n" if ($current_segment);
  606. $current_segment = "_DATA";
  607. $v.="$current_segment\tSEGMENT\n";
  608. $v.="COMM @str[0]:DWORD:".@str[1]/4;
  609. }
  610. $self->{value} = $v;
  611. last;
  612. };
  613. }
  614. $line = "";
  615. }
  616. $ret;
  617. }
  618. sub out {
  619. my $self = shift;
  620. $self->{value};
  621. }
  622. }
  623. sub rex {
  624. local *opcode=shift;
  625. my ($dst,$src,$rex)=@_;
  626. $rex|=0x04 if($dst>=8);
  627. $rex|=0x01 if($src>=8);
  628. push @opcode,($rex|0x40) if ($rex);
  629. }
  630. # older gas and ml64 don't handle SSE>2 instructions
  631. my %regrm = ( "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
  632. "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7 );
  633. my $movq = sub { # elderly gas can't handle inter-register movq
  634. my $arg = shift;
  635. my @opcode=(0x66);
  636. if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
  637. my ($src,$dst)=($1,$2);
  638. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  639. rex(\@opcode,$src,$dst,0x8);
  640. push @opcode,0x0f,0x7e;
  641. push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
  642. @opcode;
  643. } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
  644. my ($src,$dst)=($2,$1);
  645. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  646. rex(\@opcode,$src,$dst,0x8);
  647. push @opcode,0x0f,0x6e;
  648. push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
  649. @opcode;
  650. } else {
  651. ();
  652. }
  653. };
  654. my $pextrd = sub {
  655. if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
  656. my @opcode=(0x66);
  657. $imm=$1;
  658. $src=$2;
  659. $dst=$3;
  660. if ($dst =~ /%r([0-9]+)d/) { $dst = $1; }
  661. elsif ($dst =~ /%e/) { $dst = $regrm{$dst}; }
  662. rex(\@opcode,$src,$dst);
  663. push @opcode,0x0f,0x3a,0x16;
  664. push @opcode,0xc0|(($src&7)<<3)|($dst&7); # ModR/M
  665. push @opcode,$imm;
  666. @opcode;
  667. } else {
  668. ();
  669. }
  670. };
  671. my $pinsrd = sub {
  672. if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
  673. my @opcode=(0x66);
  674. $imm=$1;
  675. $src=$2;
  676. $dst=$3;
  677. if ($src =~ /%r([0-9]+)/) { $src = $1; }
  678. elsif ($src =~ /%e/) { $src = $regrm{$src}; }
  679. rex(\@opcode,$dst,$src);
  680. push @opcode,0x0f,0x3a,0x22;
  681. push @opcode,0xc0|(($dst&7)<<3)|($src&7); # ModR/M
  682. push @opcode,$imm;
  683. @opcode;
  684. } else {
  685. ();
  686. }
  687. };
  688. my $pshufb = sub {
  689. if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  690. my @opcode=(0x66);
  691. rex(\@opcode,$2,$1);
  692. push @opcode,0x0f,0x38,0x00;
  693. push @opcode,0xc0|($1&7)|(($2&7)<<3); # ModR/M
  694. @opcode;
  695. } else {
  696. ();
  697. }
  698. };
  699. my $palignr = sub {
  700. if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  701. my @opcode=(0x66);
  702. rex(\@opcode,$3,$2);
  703. push @opcode,0x0f,0x3a,0x0f;
  704. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  705. push @opcode,$1;
  706. @opcode;
  707. } else {
  708. ();
  709. }
  710. };
  711. my $pclmulqdq = sub {
  712. if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  713. my @opcode=(0x66);
  714. rex(\@opcode,$3,$2);
  715. push @opcode,0x0f,0x3a,0x44;
  716. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  717. my $c=$1;
  718. push @opcode,$c=~/^0/?oct($c):$c;
  719. @opcode;
  720. } else {
  721. ();
  722. }
  723. };
  724. my $rdrand = sub {
  725. if (shift =~ /%[er](\w+)/) {
  726. my @opcode=();
  727. my $dst=$1;
  728. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  729. rex(\@opcode,0,$1,8);
  730. push @opcode,0x0f,0xc7,0xf0|($dst&7);
  731. @opcode;
  732. } else {
  733. ();
  734. }
  735. };
  736. my $rdseed = sub {
  737. if (shift =~ /%[er](\w+)/) {
  738. my @opcode=();
  739. my $dst=$1;
  740. if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
  741. rex(\@opcode,0,$1,8);
  742. push @opcode,0x0f,0xc7,0xf8|($dst&7);
  743. @opcode;
  744. } else {
  745. ();
  746. }
  747. };
  748. sub rxb {
  749. local *opcode=shift;
  750. my ($dst,$src1,$src2,$rxb)=@_;
  751. $rxb|=0x7<<5;
  752. $rxb&=~(0x04<<5) if($dst>=8);
  753. $rxb&=~(0x01<<5) if($src1>=8);
  754. $rxb&=~(0x02<<5) if($src2>=8);
  755. push @opcode,$rxb;
  756. }
  757. my $vprotd = sub {
  758. if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  759. my @opcode=(0x8f);
  760. rxb(\@opcode,$3,$2,-1,0x08);
  761. push @opcode,0x78,0xc2;
  762. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  763. my $c=$1;
  764. push @opcode,$c=~/^0/?oct($c):$c;
  765. @opcode;
  766. } else {
  767. ();
  768. }
  769. };
  770. my $vprotq = sub {
  771. if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
  772. my @opcode=(0x8f);
  773. rxb(\@opcode,$3,$2,-1,0x08);
  774. push @opcode,0x78,0xc3;
  775. push @opcode,0xc0|($2&7)|(($3&7)<<3); # ModR/M
  776. my $c=$1;
  777. push @opcode,$c=~/^0/?oct($c):$c;
  778. @opcode;
  779. } else {
  780. ();
  781. }
  782. };
  783. if ($nasm) {
  784. print <<___;
  785. default rel
  786. %define XMMWORD
  787. %define YMMWORD
  788. %define ZMMWORD
  789. ___
  790. } elsif ($masm) {
  791. print <<___;
  792. OPTION DOTNAME
  793. ___
  794. }
  795. while($line=<>) {
  796. chomp($line);
  797. $line =~ s|[#!].*$||; # get rid of asm-style comments...
  798. $line =~ s|/\*.*\*/||; # ... and C-style comments...
  799. $line =~ s|^\s+||; # ... and skip white spaces in beginning
  800. $line =~ s|\s+$||; # ... and at the end
  801. undef $label;
  802. undef $opcode;
  803. undef @args;
  804. if ($label=label->re(\$line)) { print $label->out(); }
  805. if (directive->re(\$line)) {
  806. printf "%s",directive->out();
  807. } elsif ($opcode=opcode->re(\$line)) {
  808. my $asm = eval("\$".$opcode->mnemonic());
  809. undef @bytes;
  810. if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
  811. print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
  812. next;
  813. }
  814. ARGUMENT: while (1) {
  815. my $arg;
  816. if ($arg=register->re(\$line)) { opcode->size($arg->size()); }
  817. elsif ($arg=const->re(\$line)) { }
  818. elsif ($arg=ea->re(\$line)) { }
  819. elsif ($arg=expr->re(\$line)) { }
  820. else { last ARGUMENT; }
  821. push @args,$arg;
  822. last ARGUMENT if ($line !~ /^,/);
  823. $line =~ s/^,\s*//;
  824. } # ARGUMENT:
  825. if ($#args>=0) {
  826. my $insn;
  827. my $sz=opcode->size();
  828. if ($gas) {
  829. $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
  830. @args = map($_->out($sz),@args);
  831. printf "\t%s\t%s",$insn,join(",",@args);
  832. } else {
  833. $insn = $opcode->out();
  834. foreach (@args) {
  835. my $arg = $_->out();
  836. # $insn.=$sz compensates for movq, pinsrw, ...
  837. if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
  838. if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
  839. if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
  840. if ($arg =~ /^mm[0-9]+$/) { $insn.=$sz; $sz="q" if(!$sz); last; }
  841. }
  842. @args = reverse(@args);
  843. undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
  844. printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
  845. }
  846. } else {
  847. printf "\t%s",$opcode->out();
  848. }
  849. }
  850. print $line,"\n";
  851. }
  852. print "\n$current_segment\tENDS\n" if ($current_segment && $masm);
  853. print "END\n" if ($masm);
  854. close STDOUT;
  855. #################################################
  856. # Cross-reference x86_64 ABI "card"
  857. #
  858. # Unix Win64
  859. # %rax * *
  860. # %rbx - -
  861. # %rcx #4 #1
  862. # %rdx #3 #2
  863. # %rsi #2 -
  864. # %rdi #1 -
  865. # %rbp - -
  866. # %rsp - -
  867. # %r8 #5 #3
  868. # %r9 #6 #4
  869. # %r10 * *
  870. # %r11 * *
  871. # %r12 - -
  872. # %r13 - -
  873. # %r14 - -
  874. # %r15 - -
  875. #
  876. # (*) volatile register
  877. # (-) preserved by callee
  878. # (#) Nth argument, volatile
  879. #
  880. # In Unix terms top of stack is argument transfer area for arguments
  881. # which could not be accomodated in registers. Or in other words 7th
  882. # [integer] argument resides at 8(%rsp) upon function entry point.
  883. # 128 bytes above %rsp constitute a "red zone" which is not touched
  884. # by signal handlers and can be used as temporal storage without
  885. # allocating a frame.
  886. #
  887. # In Win64 terms N*8 bytes on top of stack is argument transfer area,
  888. # which belongs to/can be overwritten by callee. N is the number of
  889. # arguments passed to callee, *but* not less than 4! This means that
  890. # upon function entry point 5th argument resides at 40(%rsp), as well
  891. # as that 32 bytes from 8(%rsp) can always be used as temporal
  892. # storage [without allocating a frame]. One can actually argue that
  893. # one can assume a "red zone" above stack pointer under Win64 as well.
  894. # Point is that at apparently no occasion Windows kernel would alter
  895. # the area above user stack pointer in true asynchronous manner...
  896. #
  897. # All the above means that if assembler programmer adheres to Unix
  898. # register and stack layout, but disregards the "red zone" existense,
  899. # it's possible to use following prologue and epilogue to "gear" from
  900. # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
  901. #
  902. # omnipotent_function:
  903. # ifdef WIN64
  904. # movq %rdi,8(%rsp)
  905. # movq %rsi,16(%rsp)
  906. # movq %rcx,%rdi ; if 1st argument is actually present
  907. # movq %rdx,%rsi ; if 2nd argument is actually ...
  908. # movq %r8,%rdx ; if 3rd argument is ...
  909. # movq %r9,%rcx ; if 4th argument ...
  910. # movq 40(%rsp),%r8 ; if 5th ...
  911. # movq 48(%rsp),%r9 ; if 6th ...
  912. # endif
  913. # ...
  914. # ifdef WIN64
  915. # movq 8(%rsp),%rdi
  916. # movq 16(%rsp),%rsi
  917. # endif
  918. # ret
  919. #
  920. #################################################
  921. # Win64 SEH, Structured Exception Handling.
  922. #
  923. # Unlike on Unix systems(*) lack of Win64 stack unwinding information
  924. # has undesired side-effect at run-time: if an exception is raised in
  925. # assembler subroutine such as those in question (basically we're
  926. # referring to segmentation violations caused by malformed input
  927. # parameters), the application is briskly terminated without invoking
  928. # any exception handlers, most notably without generating memory dump
  929. # or any user notification whatsoever. This poses a problem. It's
  930. # possible to address it by registering custom language-specific
  931. # handler that would restore processor context to the state at
  932. # subroutine entry point and return "exception is not handled, keep
  933. # unwinding" code. Writing such handler can be a challenge... But it's
  934. # doable, though requires certain coding convention. Consider following
  935. # snippet:
  936. #
  937. # .type function,@function
  938. # function:
  939. # movq %rsp,%rax # copy rsp to volatile register
  940. # pushq %r15 # save non-volatile registers
  941. # pushq %rbx
  942. # pushq %rbp
  943. # movq %rsp,%r11
  944. # subq %rdi,%r11 # prepare [variable] stack frame
  945. # andq $-64,%r11
  946. # movq %rax,0(%r11) # check for exceptions
  947. # movq %r11,%rsp # allocate [variable] stack frame
  948. # movq %rax,0(%rsp) # save original rsp value
  949. # magic_point:
  950. # ...
  951. # movq 0(%rsp),%rcx # pull original rsp value
  952. # movq -24(%rcx),%rbp # restore non-volatile registers
  953. # movq -16(%rcx),%rbx
  954. # movq -8(%rcx),%r15
  955. # movq %rcx,%rsp # restore original rsp
  956. # ret
  957. # .size function,.-function
  958. #
  959. # The key is that up to magic_point copy of original rsp value remains
  960. # in chosen volatile register and no non-volatile register, except for
  961. # rsp, is modified. While past magic_point rsp remains constant till
  962. # the very end of the function. In this case custom language-specific
  963. # exception handler would look like this:
  964. #
  965. # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
  966. # CONTEXT *context,DISPATCHER_CONTEXT *disp)
  967. # { ULONG64 *rsp = (ULONG64 *)context->Rax;
  968. # if (context->Rip >= magic_point)
  969. # { rsp = ((ULONG64 **)context->Rsp)[0];
  970. # context->Rbp = rsp[-3];
  971. # context->Rbx = rsp[-2];
  972. # context->R15 = rsp[-1];
  973. # }
  974. # context->Rsp = (ULONG64)rsp;
  975. # context->Rdi = rsp[1];
  976. # context->Rsi = rsp[2];
  977. #
  978. # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
  979. # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
  980. # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
  981. # &disp->HandlerData,&disp->EstablisherFrame,NULL);
  982. # return ExceptionContinueSearch;
  983. # }
  984. #
  985. # It's appropriate to implement this handler in assembler, directly in
  986. # function's module. In order to do that one has to know members'
  987. # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
  988. # values. Here they are:
  989. #
  990. # CONTEXT.Rax 120
  991. # CONTEXT.Rcx 128
  992. # CONTEXT.Rdx 136
  993. # CONTEXT.Rbx 144
  994. # CONTEXT.Rsp 152
  995. # CONTEXT.Rbp 160
  996. # CONTEXT.Rsi 168
  997. # CONTEXT.Rdi 176
  998. # CONTEXT.R8 184
  999. # CONTEXT.R9 192
  1000. # CONTEXT.R10 200
  1001. # CONTEXT.R11 208
  1002. # CONTEXT.R12 216
  1003. # CONTEXT.R13 224
  1004. # CONTEXT.R14 232
  1005. # CONTEXT.R15 240
  1006. # CONTEXT.Rip 248
  1007. # CONTEXT.Xmm6 512
  1008. # sizeof(CONTEXT) 1232
  1009. # DISPATCHER_CONTEXT.ControlPc 0
  1010. # DISPATCHER_CONTEXT.ImageBase 8
  1011. # DISPATCHER_CONTEXT.FunctionEntry 16
  1012. # DISPATCHER_CONTEXT.EstablisherFrame 24
  1013. # DISPATCHER_CONTEXT.TargetIp 32
  1014. # DISPATCHER_CONTEXT.ContextRecord 40
  1015. # DISPATCHER_CONTEXT.LanguageHandler 48
  1016. # DISPATCHER_CONTEXT.HandlerData 56
  1017. # UNW_FLAG_NHANDLER 0
  1018. # ExceptionContinueSearch 1
  1019. #
  1020. # In order to tie the handler to the function one has to compose
  1021. # couple of structures: one for .xdata segment and one for .pdata.
  1022. #
  1023. # UNWIND_INFO structure for .xdata segment would be
  1024. #
  1025. # function_unwind_info:
  1026. # .byte 9,0,0,0
  1027. # .rva handler
  1028. #
  1029. # This structure designates exception handler for a function with
  1030. # zero-length prologue, no stack frame or frame register.
  1031. #
  1032. # To facilitate composing of .pdata structures, auto-generated "gear"
  1033. # prologue copies rsp value to rax and denotes next instruction with
  1034. # .LSEH_begin_{function_name} label. This essentially defines the SEH
  1035. # styling rule mentioned in the beginning. Position of this label is
  1036. # chosen in such manner that possible exceptions raised in the "gear"
  1037. # prologue would be accounted to caller and unwound from latter's frame.
  1038. # End of function is marked with respective .LSEH_end_{function_name}
  1039. # label. To summarize, .pdata segment would contain
  1040. #
  1041. # .rva .LSEH_begin_function
  1042. # .rva .LSEH_end_function
  1043. # .rva function_unwind_info
  1044. #
  1045. # Reference to function_unwind_info from .xdata segment is the anchor.
  1046. # In case you wonder why references are 32-bit .rvas and not 64-bit
  1047. # .quads. References put into these two segments are required to be
  1048. # *relative* to the base address of the current binary module, a.k.a.
  1049. # image base. No Win64 module, be it .exe or .dll, can be larger than
  1050. # 2GB and thus such relative references can be and are accommodated in
  1051. # 32 bits.
  1052. #
  1053. # Having reviewed the example function code, one can argue that "movq
  1054. # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
  1055. # rax would contain an undefined value. If this "offends" you, use
  1056. # another register and refrain from modifying rax till magic_point is
  1057. # reached, i.e. as if it was a non-volatile register. If more registers
  1058. # are required prior [variable] frame setup is completed, note that
  1059. # nobody says that you can have only one "magic point." You can
  1060. # "liberate" non-volatile registers by denoting last stack off-load
  1061. # instruction and reflecting it in finer grade unwind logic in handler.
  1062. # After all, isn't it why it's called *language-specific* handler...
  1063. #
  1064. # Attentive reader can notice that exceptions would be mishandled in
  1065. # auto-generated "gear" epilogue. Well, exception effectively can't
  1066. # occur there, because if memory area used by it was subject to
  1067. # segmentation violation, then it would be raised upon call to the
  1068. # function (and as already mentioned be accounted to caller, which is
  1069. # not a problem). If you're still not comfortable, then define tail
  1070. # "magic point" just prior ret instruction and have handler treat it...
  1071. #
  1072. # (*) Note that we're talking about run-time, not debug-time. Lack of
  1073. # unwind information makes debugging hard on both Windows and
  1074. # Unix. "Unlike" referes to the fact that on Unix signal handler
  1075. # will always be invoked, core dumped and appropriate exit code
  1076. # returned to parent (for user notification).