x86_64-xlate.pl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. #!/usr/bin/env perl
  2. # Ascetic x86_64 AT&T to MASM 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. # - indirect calls and jumps are not supported;
  23. #
  24. # Dual-ABI styling rules.
  25. #
  26. # 1. Adhere to Unix register and stack layout [see the end for
  27. # explanation].
  28. # 2. Forget about "red zone," stick to more traditional blended
  29. # stack frame allocation. If volatile storage is actually required
  30. # that is. If not, just leave the stack as is.
  31. # 3. Functions tagged with ".type name,@function" get crafted with
  32. # unified Win64 prologue and epilogue automatically. If you want
  33. # to take care of ABI differences yourself, tag functions as
  34. # ".type name,@abi-omnipotent" instead.
  35. # 4. To optimize the Win64 prologue you can specify number of input
  36. # arguments as ".type name,@function,N." Keep in mind that if N is
  37. # larger than 6, then you *have to* write "abi-omnipotent" code,
  38. # because >6 cases can't be addressed with unified prologue.
  39. # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
  40. # (sorry about latter).
  41. # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
  42. # required to identify the spots, where to inject Win64 epilogue!
  43. # But on the pros, it's then prefixed with rep automatically:-)
  44. # 7. Due to MASM limitations [and certain general counter-intuitivity
  45. # of ip-relative addressing] generation of position-independent
  46. # code is assisted by synthetic directive, .picmeup, which puts
  47. # address of the *next* instruction into target register.
  48. #
  49. # Example 1:
  50. # .picmeup %rax
  51. # lea .Label-.(%rax),%rax
  52. # Example 2:
  53. # .picmeup %rcx
  54. # .Lpic_point:
  55. # ...
  56. # lea .Label-.Lpic_point(%rcx),%rbp
  57. my $output = shift;
  58. { my ($stddev,$stdino,@junk)=stat(STDOUT);
  59. my ($outdev,$outino,@junk)=stat($output);
  60. open STDOUT,">$output" || die "can't open $output: $!"
  61. if ($stddev!=$outdev || $stdino!=$outino);
  62. }
  63. my $win64=1 if ($output =~ /\.asm/);
  64. my $masmref=8 + 50727*2**-32; # 8.00.50727 shipped with VS2005
  65. my $masm=$masmref;
  66. my $PTR=" PTR";
  67. my $nasm=0;
  68. if ($win64)
  69. { if ($ENV{ASM} =~ m/nasm/)
  70. { $nasm = 1; $PTR=""; }
  71. elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
  72. { $masm = $1 + $2*2**-16 + $4*2**-32; }
  73. }
  74. my $current_segment;
  75. my $current_function;
  76. { package opcode; # pick up opcodes
  77. sub re {
  78. my $self = shift; # single instance in enough...
  79. local *line = shift;
  80. undef $ret;
  81. if ($line =~ /^([a-z][a-z0-9]*)/i) {
  82. $self->{op} = $1;
  83. $ret = $self;
  84. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  85. undef $self->{sz};
  86. if ($self->{op} =~ /^(movz)b.*/) { # movz is pain...
  87. $self->{op} = $1;
  88. $self->{sz} = "b";
  89. } elsif ($self->{op} =~ /call/) {
  90. $self->{sz} = ""
  91. } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
  92. $self->{op} = $1;
  93. $self->{sz} = $2;
  94. }
  95. }
  96. $ret;
  97. }
  98. sub size {
  99. my $self = shift;
  100. my $sz = shift;
  101. $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
  102. $self->{sz};
  103. }
  104. sub out {
  105. my $self = shift;
  106. if (!$win64) {
  107. if ($self->{op} eq "movz") { # movz is pain...
  108. sprintf "%s%s%s",$self->{op},$self->{sz},shift;
  109. } elsif ($self->{op} =~ /^set/) {
  110. "$self->{op}";
  111. } elsif ($self->{op} eq "ret") {
  112. ".byte 0xf3,0xc3";
  113. } else {
  114. "$self->{op}$self->{sz}";
  115. }
  116. } else {
  117. $self->{op} =~ s/^movz/movzx/;
  118. if ($self->{op} eq "ret") {
  119. $self->{op} = "";
  120. if ($current_function->{abi} eq "svr4") {
  121. $self->{op} = "mov rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
  122. "mov rsi,QWORD${PTR}[16+rsp]\n\t";
  123. }
  124. $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
  125. } elsif ($self->{op} =~ /^j/ && $nasm) {
  126. $self->{op} .= " NEAR";
  127. }
  128. $self->{op};
  129. }
  130. }
  131. sub mnemonic { shift->{op}; }
  132. }
  133. { package const; # pick up constants, which start with $
  134. sub re {
  135. my $self = shift; # single instance in enough...
  136. local *line = shift;
  137. undef $ret;
  138. if ($line =~ /^\$([^,]+)/) {
  139. $self->{value} = $1;
  140. $ret = $self;
  141. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  142. }
  143. $ret;
  144. }
  145. sub out {
  146. my $self = shift;
  147. if (!$win64) {
  148. # Solaris /usr/ccs/bin/as can't handle multiplications
  149. # in $self->{value}
  150. $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
  151. $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
  152. sprintf "\$%s",$self->{value};
  153. } else {
  154. $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
  155. sprintf "%s",$self->{value};
  156. }
  157. }
  158. }
  159. { package ea; # pick up effective addresses: expr(%reg,%reg,scale)
  160. sub re {
  161. my $self = shift; # single instance in enough...
  162. local *line = shift;
  163. undef $ret;
  164. if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
  165. $self->{label} = $1;
  166. ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
  167. $self->{scale} = 1 if (!defined($self->{scale}));
  168. $ret = $self;
  169. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  170. $self->{base} =~ s/^%//;
  171. $self->{index} =~ s/^%// if (defined($self->{index}));
  172. }
  173. $ret;
  174. }
  175. sub size {}
  176. sub out {
  177. my $self = shift;
  178. my $sz = shift;
  179. # Silently convert all EAs to 64-bit. This is required for
  180. # elder GNU assembler and results in more compact code,
  181. # *but* most importantly AES module depends on this feature!
  182. $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
  183. $self->{base} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
  184. if (!$win64) {
  185. # Solaris /usr/ccs/bin/as can't handle multiplications
  186. # in $self->{label}
  187. $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
  188. $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
  189. if (defined($self->{index})) {
  190. sprintf "%s(%%%s,%%%s,%d)",
  191. $self->{label},$self->{base},
  192. $self->{index},$self->{scale};
  193. } else {
  194. sprintf "%s(%%%s)", $self->{label},$self->{base};
  195. }
  196. } else {
  197. %szmap = ( b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR", q=>"QWORD$PTR" );
  198. $self->{label} =~ s/\./\$/g;
  199. $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
  200. $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
  201. if (defined($self->{index})) {
  202. sprintf "%s[%s%s*%d+%s]",$szmap{$sz},
  203. $self->{label}?"$self->{label}+":"",
  204. $self->{index},$self->{scale},
  205. $self->{base};
  206. } elsif ($self->{base} eq "rip") {
  207. sprintf "%s[%s]",$szmap{$sz},$self->{label};
  208. } else {
  209. sprintf "%s[%s%s]",$szmap{$sz},
  210. $self->{label}?"$self->{label}+":"",
  211. $self->{base};
  212. }
  213. }
  214. }
  215. }
  216. { package register; # pick up registers, which start with %.
  217. sub re {
  218. my $class = shift; # muliple instances...
  219. my $self = {};
  220. local *line = shift;
  221. undef $ret;
  222. if ($line =~ /^%(\w+)/) {
  223. bless $self,$class;
  224. $self->{value} = $1;
  225. $ret = $self;
  226. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  227. }
  228. $ret;
  229. }
  230. sub size {
  231. my $self = shift;
  232. undef $ret;
  233. if ($self->{value} =~ /^r[\d]+b$/i) { $ret="b"; }
  234. elsif ($self->{value} =~ /^r[\d]+w$/i) { $ret="w"; }
  235. elsif ($self->{value} =~ /^r[\d]+d$/i) { $ret="l"; }
  236. elsif ($self->{value} =~ /^r[\w]+$/i) { $ret="q"; }
  237. elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
  238. elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
  239. elsif ($self->{value} =~ /^[\w]{2}$/i) { $ret="w"; }
  240. elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
  241. $ret;
  242. }
  243. sub out {
  244. my $self = shift;
  245. sprintf $win64?"%s":"%%%s",$self->{value};
  246. }
  247. }
  248. { package label; # pick up labels, which end with :
  249. sub re {
  250. my $self = shift; # single instance is enough...
  251. local *line = shift;
  252. undef $ret;
  253. if ($line =~ /(^[\.\w]+\:)/) {
  254. $self->{value} = $1;
  255. $ret = $self;
  256. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  257. $self->{value} =~ s/\.L/\$L/ if ($win64);
  258. }
  259. $ret;
  260. }
  261. sub out {
  262. my $self = shift;
  263. if (!$win64) {
  264. $self->{value};
  265. } elsif ($self->{value} ne "$current_function->{name}:") {
  266. $self->{value};
  267. } elsif ($current_function->{abi} eq "svr4") {
  268. my $func = "$current_function->{name}".($nasm?":":"\tPROC")."\n".
  269. " mov QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n".
  270. " mov QWORD${PTR}[16+rsp],rsi\n";
  271. my $narg = $current_function->{narg};
  272. $narg=6 if (!defined($narg));
  273. $func .= " mov rdi,rcx\n" if ($narg>0);
  274. $func .= " mov rsi,rdx\n" if ($narg>1);
  275. $func .= " mov rdx,r8\n" if ($narg>2);
  276. $func .= " mov rcx,r9\n" if ($narg>3);
  277. $func .= " mov r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
  278. $func .= " mov r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
  279. $func .= "\n";
  280. } else {
  281. "$current_function->{name}".($nasm?":":"\tPROC");
  282. }
  283. }
  284. }
  285. { package expr; # pick up expressioins
  286. sub re {
  287. my $self = shift; # single instance is enough...
  288. local *line = shift;
  289. undef $ret;
  290. if ($line =~ /(^[^,]+)/) {
  291. $self->{value} = $1;
  292. $ret = $self;
  293. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  294. $self->{value} =~ s/\.L/\$L/g if ($win64);
  295. }
  296. $ret;
  297. }
  298. sub out {
  299. my $self = shift;
  300. $self->{value};
  301. }
  302. }
  303. { package directive; # pick up directives, which start with .
  304. sub re {
  305. my $self = shift; # single instance is enough...
  306. local *line = shift;
  307. undef $ret;
  308. my $dir;
  309. my %opcode = # lea 2f-1f(%rip),%dst; 1: nop; 2:
  310. ( "%rax"=>0x01058d48, "%rcx"=>0x010d8d48,
  311. "%rdx"=>0x01158d48, "%rbx"=>0x011d8d48,
  312. "%rsp"=>0x01258d48, "%rbp"=>0x012d8d48,
  313. "%rsi"=>0x01358d48, "%rdi"=>0x013d8d48,
  314. "%r8" =>0x01058d4c, "%r9" =>0x010d8d4c,
  315. "%r10"=>0x01158d4c, "%r11"=>0x011d8d4c,
  316. "%r12"=>0x01258d4c, "%r13"=>0x012d8d4c,
  317. "%r14"=>0x01358d4c, "%r15"=>0x013d8d4c );
  318. if ($line =~ /^\s*(\.\w+)/) {
  319. if (!$win64) {
  320. $self->{value} = $1;
  321. $line =~ s/\@abi\-omnipotent/\@function/;
  322. $line =~ s/\@function.*/\@function/;
  323. if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
  324. $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
  325. } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
  326. $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
  327. } elsif ($line =~ /\.extern/) {
  328. $self->{value} = ""; # swallow extern
  329. } else {
  330. $self->{value} = $line;
  331. }
  332. $line = "";
  333. return $self;
  334. }
  335. $dir = $1;
  336. $ret = $self;
  337. undef $self->{value};
  338. $line = substr($line,@+[0]); $line =~ s/^\s+//;
  339. SWITCH: for ($dir) {
  340. /\.(text)/
  341. && do { my $v=undef;
  342. if ($nasm) {
  343. $v ="section .$1 code align=64\n";
  344. $v.="default rel\n";
  345. $v.="%define PUBLIC global";
  346. } else {
  347. $v="$current_segment\tENDS\n" if ($current_segment);
  348. $current_segment = "_$1\$";
  349. $current_segment =~ tr/[a-z]/[A-Z]/;
  350. $v.="$current_segment\tSEGMENT ";
  351. $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
  352. $v.=" 'CODE'";
  353. }
  354. $self->{value} = $v;
  355. last;
  356. };
  357. /\.extern/ && do { $self->{value} = "EXTERN\t".$line;
  358. $self->{value} .= ":BYTE" if (!$nasm);
  359. last;
  360. };
  361. /\.globl/ && do { $self->{value} = "PUBLIC\t".$line; last; };
  362. /\.type/ && do { ($sym,$type,$narg) = split(',',$line);
  363. if ($type eq "\@function") {
  364. undef $current_function;
  365. $current_function->{name} = $sym;
  366. $current_function->{abi} = "svr4";
  367. $current_function->{narg} = $narg;
  368. } elsif ($type eq "\@abi-omnipotent") {
  369. undef $current_function;
  370. $current_function->{name} = $sym;
  371. }
  372. last;
  373. };
  374. /\.size/ && do { if (defined($current_function)) {
  375. $self->{value}="$current_function->{name}\tENDP" if(!$nasm);
  376. undef $current_function;
  377. }
  378. last;
  379. };
  380. /\.align/ && do { $self->{value} = "ALIGN\t".$line; last; };
  381. /\.(byte|value|long|quad)/
  382. && do { my @arr = split(',',$line);
  383. my $sz = substr($1,0,1);
  384. my $last = pop(@arr);
  385. my $conv = sub { my $var=shift;
  386. if ($var=~s/0x([0-9a-f]+)/0$1h/i) { $var; }
  387. else { sprintf"0%Xh",$var; }
  388. };
  389. $sz =~ tr/bvlq/BWDQ/;
  390. $self->{value} = "\tD$sz\t";
  391. for (@arr) { $self->{value} .= &$conv($_).","; }
  392. $self->{value} .= &$conv($last);
  393. last;
  394. };
  395. /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t0%Xh,090000000h",$opcode{$line};
  396. last;
  397. };
  398. /\.asciz/ && do { if ($line =~ /^"(.*)"$/) {
  399. my @str=unpack("C*",$1);
  400. push @str,0;
  401. while ($#str>15) {
  402. $self->{value}.="DB\t"
  403. .join(",",@str[0..15])."\n";
  404. foreach (0..15) { shift @str; }
  405. }
  406. $self->{value}.="DB\t"
  407. .join(",",@str) if (@str);
  408. }
  409. last;
  410. };
  411. }
  412. $line = "";
  413. }
  414. $ret;
  415. }
  416. sub out {
  417. my $self = shift;
  418. $self->{value};
  419. }
  420. }
  421. while($line=<>) {
  422. chomp($line);
  423. $line =~ s|[#!].*$||; # get rid of asm-style comments...
  424. $line =~ s|/\*.*\*/||; # ... and C-style comments...
  425. $line =~ s|^\s+||; # ... and skip white spaces in beginning
  426. undef $label;
  427. undef $opcode;
  428. undef $dst;
  429. undef $src;
  430. undef $sz;
  431. if ($label=label->re(\$line)) { print $label->out(); }
  432. if (directive->re(\$line)) {
  433. printf "%s",directive->out();
  434. } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
  435. if ($src=register->re(\$line)) { opcode->size($src->size()); }
  436. elsif ($src=const->re(\$line)) { }
  437. elsif ($src=ea->re(\$line)) { }
  438. elsif ($src=expr->re(\$line)) { }
  439. last ARGUMENT if ($line !~ /^,/);
  440. $line = substr($line,1); $line =~ s/^\s+//;
  441. if ($dst=register->re(\$line)) { opcode->size($dst->size()); }
  442. elsif ($dst=const->re(\$line)) { }
  443. elsif ($dst=ea->re(\$line)) { }
  444. } # ARGUMENT:
  445. $sz=opcode->size();
  446. if (defined($dst)) {
  447. if (!$win64) {
  448. printf "\t%s\t%s,%s", $opcode->out($dst->size()),
  449. $src->out($sz),$dst->out($sz);
  450. } else {
  451. undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
  452. printf "\t%s\t%s,%s", $opcode->out(),
  453. $dst->out($sz),$src->out($sz);
  454. }
  455. } elsif (defined($src)) {
  456. printf "\t%s\t%s",$opcode->out(),$src->out($sz);
  457. } else {
  458. printf "\t%s",$opcode->out();
  459. }
  460. }
  461. print $line,"\n";
  462. }
  463. print "\n$current_segment\tENDS\nEND\n" if ($current_segment);
  464. close STDOUT;
  465. #################################################
  466. # Cross-reference x86_64 ABI "card"
  467. #
  468. # Unix Win64
  469. # %rax * *
  470. # %rbx - -
  471. # %rcx #4 #1
  472. # %rdx #3 #2
  473. # %rsi #2 -
  474. # %rdi #1 -
  475. # %rbp - -
  476. # %rsp - -
  477. # %r8 #5 #3
  478. # %r9 #6 #4
  479. # %r10 * *
  480. # %r11 * *
  481. # %r12 - -
  482. # %r13 - -
  483. # %r14 - -
  484. # %r15 - -
  485. #
  486. # (*) volatile register
  487. # (-) preserved by callee
  488. # (#) Nth argument, volatile
  489. #
  490. # In Unix terms top of stack is argument transfer area for arguments
  491. # which could not be accomodated in registers. Or in other words 7th
  492. # [integer] argument resides at 8(%rsp) upon function entry point.
  493. # 128 bytes above %rsp constitute a "red zone" which is not touched
  494. # by signal handlers and can be used as temporal storage without
  495. # allocating a frame.
  496. #
  497. # In Win64 terms N*8 bytes on top of stack is argument transfer area,
  498. # which belongs to/can be overwritten by callee. N is the number of
  499. # arguments passed to callee, *but* not less than 4! This means that
  500. # upon function entry point 5th argument resides at 40(%rsp), as well
  501. # as that 32 bytes from 8(%rsp) can always be used as temporal
  502. # storage [without allocating a frame]. One can actually argue that
  503. # one can assume a "red zone" above stack pointer under Win64 as well.
  504. # Point is that at apparently no occasion Windows kernel would alter
  505. # the area above user stack pointer in true asynchronous manner...
  506. #
  507. # All the above means that if assembler programmer adheres to Unix
  508. # register and stack layout, but disregards the "red zone" existense,
  509. # it's possible to use following prologue and epilogue to "gear" from
  510. # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
  511. #
  512. # omnipotent_function:
  513. # ifdef WIN64
  514. # movq %rdi,8(%rsp)
  515. # movq %rsi,16(%rsp)
  516. # movq %rcx,%rdi ; if 1st argument is actually present
  517. # movq %rdx,%rsi ; if 2nd argument is actually ...
  518. # movq %r8,%rdx ; if 3rd argument is ...
  519. # movq %r9,%rcx ; if 4th argument ...
  520. # movq 40(%rsp),%r8 ; if 5th ...
  521. # movq 48(%rsp),%r9 ; if 6th ...
  522. # endif
  523. # ...
  524. # ifdef WIN64
  525. # movq 8(%rsp),%rdi
  526. # movq 16(%rsp),%rsi
  527. # endif
  528. # ret
  529. #
  530. #################################################
  531. # Unlike on Unix systems(*) lack of Win64 stack unwinding information
  532. # has undesired side-effect at run-time: if an exception is raised in
  533. # assembler subroutine such as those in question (basically we're
  534. # referring to segmentation violations caused by malformed input
  535. # parameters), the application is briskly terminated without invoking
  536. # any exception handlers, most notably without generating memory dump
  537. # or any user notification whatsoever. This poses a problem. It's
  538. # possible to address it by registering custom language-specific
  539. # handler that would restore processor context to the state at
  540. # subroutine entry point and return "exception is not handled, keep
  541. # unwinding" code. Writing such handler can be a challenge... But it's
  542. # doable, though requires certain coding convention. Consider following
  543. # snippet:
  544. #
  545. # function:
  546. # movq %rsp,%rax # copy rsp to volatile register
  547. # pushq %r15 # save non-volatile registers
  548. # pushq %rbx
  549. # pushq %rbp
  550. # movq %rsp,%r11
  551. # subq %rdi,%r11 # prepare [variable] stack frame
  552. # andq $-64,%r11
  553. # movq %rax,0(%r11) # check for exceptions
  554. # movq %r11,%rsp # allocate [variable] stack frame
  555. # movq %rax,0(%rsp) # save original rsp value
  556. # magic_point:
  557. # ...
  558. # movq 0(%rsp),%rcx # pull original rsp value
  559. # movq -24(%rcx),%rbp # restore non-volatile registers
  560. # movq -16(%rcx),%rbx
  561. # movq -8(%rcx),%r15
  562. # movq %rcx,%rsp # restore original rsp
  563. # ret
  564. #
  565. # The key is that up to magic_point copy of original rsp value remains
  566. # in chosen volatile register and no non-volatile register, except for
  567. # rsp, is modified. While past magic_point rsp remains constant till
  568. # the very end of the function. In this case custom language-specific
  569. # exception handler would look like this:
  570. #
  571. # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
  572. # CONTEXT *context,DISPATCHER_CONTEXT *disp)
  573. # { ULONG64 *rsp;
  574. # if (context->Rip<magic_point)
  575. # rsp = (ULONG64 *)context->Rax;
  576. # else
  577. # { rsp = ((ULONG64 **)context->Rsp)[0];
  578. # context->Rbp = rsp[-3];
  579. # context->Rbx = rsp[-2];
  580. # context->R15 = rsp[-1];
  581. # }
  582. # context->Rsp = (ULONG64)rsp;
  583. # context->Rdi = rsp[1];
  584. # context->Rsi = rsp[2];
  585. #
  586. # memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
  587. # RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
  588. # dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
  589. # &disp->HandlerData,&disp->EstablisherFrame,NULL);
  590. # return ExceptionContinueSearch;
  591. # }
  592. #
  593. # It's appropriate to implement this handler in assembler, directly in
  594. # function's module. In order to do that one has to know members'
  595. # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
  596. # values. Here they are:
  597. #
  598. # CONTEXT.Rax 120
  599. # CONTEXT.Rcx 128
  600. # CONTEXT.Rdx 136
  601. # CONTEXT.Rbx 144
  602. # CONTEXT.Rsp 152
  603. # CONTEXT.Rbp 160
  604. # CONTEXT.Rsi 168
  605. # CONTEXT.Rdi 176
  606. # CONTEXT.R8 184
  607. # CONTEXT.R9 192
  608. # CONTEXT.R10 200
  609. # CONTEXT.R11 208
  610. # CONTEXT.R12 216
  611. # CONTEXT.R13 224
  612. # CONTEXT.R14 232
  613. # CONTEXT.R15 240
  614. # CONTEXT.Rip 248
  615. # sizeof(CONTEXT) 1232
  616. # DISPATCHER_CONTEXT.ControlPc 0
  617. # DISPATCHER_CONTEXT.ImageBase 8
  618. # DISPATCHER_CONTEXT.FunctionEntry 16
  619. # DISPATCHER_CONTEXT.EstablisherFrame 24
  620. # DISPATCHER_CONTEXT.TargetIp 32
  621. # DISPATCHER_CONTEXT.ContextRecord 40
  622. # DISPATCHER_CONTEXT.LanguageHandler 48
  623. # DISPATCHER_CONTEXT.HandlerData 56
  624. # UNW_FLAG_NHANDLER 0
  625. # ExceptionContinueSearch 1
  626. #
  627. # UNWIND_INFO structure for .xdata segment would be
  628. # DB 9,0,0,0
  629. # DD imagerel handler
  630. # denoting exception handler for a function with zero-length prologue,
  631. # no stack frame or frame register.
  632. #
  633. # P.S. Attentive reader can notice that effectively no exceptions are
  634. # expected in "gear" prologue and epilogue [discussed in "ABI
  635. # cross-reference" above]. No, there are not. This is because if
  636. # memory area used by them was subject to segmentation violation,
  637. # then exception would be raised upon call to our function and be
  638. # accounted to caller and unwound from its frame, which is not a
  639. # problem.
  640. #
  641. # (*) Note that we're talking about run-time, not debug-time. Lack of
  642. # unwind information makes debugging hard on both Windows and
  643. # Unix. "Unlike" referes to the fact that on Unix signal handler
  644. # will always be invoked, core dumped and appropriate exit code
  645. # returned to parent (for user notification).