Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

1194 рядки
36 KiB

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