x86_64-xlate.pl 35 KB

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