1
0

generate_analyzer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #!/usr/bin/env node
  2. "use strict";
  3. const assert = require("assert").strict;
  4. const fs = require("fs");
  5. const path = require("path");
  6. const x86_table = require("./x86_table");
  7. const rust_ast = require("./rust_ast");
  8. const { hex, mkdirpSync, get_switch_value, get_switch_exist, finalize_table_rust } = require("./util");
  9. const OUT_DIR = path.join(__dirname, "..", "src/rust/gen/");
  10. mkdirpSync(OUT_DIR);
  11. const table_arg = get_switch_value("--table");
  12. const gen_all = get_switch_exist("--all");
  13. const to_generate = {
  14. analyzer: gen_all || table_arg === "analyzer",
  15. analyzer0f: gen_all || table_arg === "analyzer0f",
  16. };
  17. assert(
  18. Object.keys(to_generate).some(k => to_generate[k]),
  19. "Pass --table [analyzer|analyzer0f] or --all to pick which tables to generate"
  20. );
  21. gen_table();
  22. function gen_read_imm_call(op, size_variant)
  23. {
  24. let size = (op.os || op.opcode % 2 === 1) ? size_variant : 8;
  25. if(op.imm8 || op.imm8s || op.imm16 || op.imm1632 || op.imm32 || op.immaddr)
  26. {
  27. if(op.imm8)
  28. {
  29. return "cpu.read_imm8()";
  30. }
  31. else if(op.imm8s)
  32. {
  33. return "cpu.read_imm8s()";
  34. }
  35. else
  36. {
  37. if(op.immaddr)
  38. {
  39. // immaddr: depends on address size
  40. return "cpu.read_moffs()";
  41. }
  42. else
  43. {
  44. assert(op.imm1632 || op.imm16 || op.imm32);
  45. if(op.imm1632 && size === 16 || op.imm16)
  46. {
  47. return "cpu.read_imm16()";
  48. }
  49. else
  50. {
  51. assert(op.imm1632 && size === 32 || op.imm32);
  52. return "cpu.read_imm32()";
  53. }
  54. }
  55. }
  56. }
  57. else
  58. {
  59. return undefined;
  60. }
  61. }
  62. function gen_call(name, args)
  63. {
  64. args = args || [];
  65. return `${name}(${args.join(", ")});`;
  66. }
  67. /*
  68. * Current naming scheme:
  69. * instr(16|32|)_(66|F2|F3)?0F?[0-9a-f]{2}(_[0-7])?(_mem|_reg|)
  70. */
  71. function make_instruction_name(encoding, size)
  72. {
  73. const suffix = encoding.os ? String(size) : "";
  74. const opcode_hex = hex(encoding.opcode & 0xFF, 2);
  75. const first_prefix = (encoding.opcode & 0xFF00) === 0 ? "" : hex(encoding.opcode >> 8 & 0xFF, 2);
  76. const second_prefix = (encoding.opcode & 0xFF0000) === 0 ? "" : hex(encoding.opcode >> 16 & 0xFF, 2);
  77. const fixed_g_suffix = encoding.fixed_g === undefined ? "" : `_${encoding.fixed_g}`;
  78. assert(first_prefix === "" || first_prefix === "0F" || first_prefix === "F2" || first_prefix === "F3");
  79. assert(second_prefix === "" || second_prefix === "66" || second_prefix === "F2" || second_prefix === "F3");
  80. return `instr${suffix}_${second_prefix}${first_prefix}${opcode_hex}${fixed_g_suffix}`;
  81. }
  82. function gen_instruction_body(encodings, size)
  83. {
  84. const encoding = encodings[0];
  85. let has_66 = [];
  86. let has_F2 = [];
  87. let has_F3 = [];
  88. let no_prefix = [];
  89. for(let e of encodings)
  90. {
  91. if((e.opcode >>> 16) === 0x66) has_66.push(e);
  92. else if((e.opcode >>> 8 & 0xFF) === 0xF2 || (e.opcode >>> 16) === 0xF2) has_F2.push(e);
  93. else if((e.opcode >>> 8 & 0xFF) === 0xF3 || (e.opcode >>> 16) === 0xF3) has_F3.push(e);
  94. else no_prefix.push(e);
  95. }
  96. if(has_F2.length || has_F3.length)
  97. {
  98. assert((encoding.opcode & 0xFF0000) === 0 || (encoding.opcode & 0xFF00) === 0x0F00);
  99. }
  100. if(has_66.length)
  101. {
  102. assert((encoding.opcode & 0xFF00) === 0x0F00);
  103. }
  104. const code = [];
  105. if(encoding.e)
  106. {
  107. code.push("let modrm_byte = cpu.read_imm8();");
  108. }
  109. if(has_66.length || has_F2.length || has_F3.length)
  110. {
  111. const if_blocks = [];
  112. if(has_66.length) {
  113. const body = gen_instruction_body_after_prefix(has_66, size);
  114. if_blocks.push({ condition: "cpu.prefixes & ::prefix::PREFIX_66 != 0", body, });
  115. }
  116. if(has_F2.length) {
  117. const body = gen_instruction_body_after_prefix(has_F2, size);
  118. if_blocks.push({ condition: "cpu.prefixes & ::prefix::PREFIX_F2 != 0", body, });
  119. }
  120. if(has_F3.length) {
  121. const body = gen_instruction_body_after_prefix(has_F3, size);
  122. if_blocks.push({ condition: "cpu.prefixes & ::prefix::PREFIX_F3 != 0", body, });
  123. }
  124. const else_block = {
  125. body: gen_instruction_body_after_prefix(no_prefix, size),
  126. };
  127. return [].concat(
  128. code,
  129. {
  130. type: "if-else",
  131. if_blocks,
  132. else_block,
  133. }
  134. );
  135. }
  136. else {
  137. return [].concat(
  138. code,
  139. gen_instruction_body_after_prefix(encodings, size)
  140. );
  141. }
  142. }
  143. function gen_instruction_body_after_prefix(encodings, size)
  144. {
  145. const encoding = encodings[0];
  146. if(encoding.fixed_g !== undefined)
  147. {
  148. assert(encoding.e);
  149. // instruction with modrm byte where the middle 3 bits encode the instruction
  150. // group by opcode without prefix plus middle bits of modrm byte
  151. let cases = encodings.reduce((cases_by_opcode, case_) => {
  152. assert(typeof case_.fixed_g === "number");
  153. cases_by_opcode[case_.opcode & 0xFFFF | case_.fixed_g << 16] = case_;
  154. return cases_by_opcode;
  155. }, Object.create(null));
  156. cases = Object.values(cases).sort((e1, e2) => e1.fixed_g - e2.fixed_g);
  157. return [
  158. {
  159. type: "switch",
  160. condition: "modrm_byte >> 3 & 7",
  161. cases: cases.map(case_ => {
  162. const fixed_g = case_.fixed_g;
  163. const body = gen_instruction_body_after_fixed_g(case_, size);
  164. return {
  165. conditions: [fixed_g],
  166. body,
  167. };
  168. }),
  169. default_case: {
  170. body: [
  171. "analysis.ty = ::analysis::AnalysisType::BlockBoundary;",
  172. "analysis.no_next_instruction = true;",
  173. ],
  174. }
  175. },
  176. ];
  177. }
  178. else {
  179. assert(encodings.length === 1);
  180. return gen_instruction_body_after_fixed_g(encodings[0], size);
  181. }
  182. }
  183. function gen_instruction_body_after_fixed_g(encoding, size)
  184. {
  185. const imm_read = gen_read_imm_call(encoding, size);
  186. const instruction_postfix = [];
  187. if(encoding.custom_sti) {
  188. instruction_postfix.push("analysis.ty = ::analysis::AnalysisType::STI;");
  189. }
  190. else if(
  191. encoding.block_boundary &&
  192. // jump_offset_imm: Is a block boundary, but gets a different type (Jump) below
  193. !encoding.jump_offset_imm || (!encoding.custom && encoding.e))
  194. {
  195. instruction_postfix.push("analysis.ty = ::analysis::AnalysisType::BlockBoundary;");
  196. }
  197. if(encoding.no_next_instruction)
  198. {
  199. instruction_postfix.push("analysis.no_next_instruction = true;");
  200. }
  201. if(encoding.absolute_jump)
  202. {
  203. instruction_postfix.push("analysis.absolute_jump = true;");
  204. }
  205. if(encoding.prefix)
  206. {
  207. const instruction_name = "::analysis::" + make_instruction_name(encoding, size) + "_analyze";
  208. const args = ["cpu", "analysis"];
  209. assert(!imm_read);
  210. return [].concat(
  211. gen_call(instruction_name, args),
  212. instruction_postfix
  213. );
  214. }
  215. else if(encoding.e)
  216. {
  217. // instruction with modrm byte where the middle 3 bits encode a register
  218. const reg_postfix = [];
  219. const mem_postfix = [];
  220. if(encoding.mem_ud)
  221. {
  222. mem_postfix.push(
  223. "analysis.ty = ::analysis::AnalysisType::BlockBoundary;"
  224. );
  225. }
  226. if(encoding.reg_ud)
  227. {
  228. reg_postfix.push(
  229. "analysis.ty = ::analysis::AnalysisType::BlockBoundary;"
  230. );
  231. }
  232. if(encoding.ignore_mod)
  233. {
  234. assert(!imm_read, "Unexpected instruction (ignore mod with immediate value)");
  235. // Has modrm byte, but the 2 mod bits are ignored and both
  236. // operands are always registers (0f20-0f24)
  237. return instruction_postfix;
  238. }
  239. else
  240. {
  241. return [].concat(
  242. {
  243. type: "if-else",
  244. if_blocks: [{
  245. condition: "modrm_byte < 0xC0",
  246. body: [].concat(
  247. gen_call("::analysis::modrm_analyze", ["cpu", "modrm_byte"]),
  248. mem_postfix,
  249. ),
  250. }],
  251. else_block: {
  252. body: reg_postfix,
  253. },
  254. },
  255. imm_read ? [imm_read + ";"] : [],
  256. instruction_postfix
  257. );
  258. }
  259. }
  260. else
  261. {
  262. // instruction without modrm byte or prefix
  263. const body = [];
  264. if(imm_read)
  265. {
  266. if(encoding.jump_offset_imm)
  267. {
  268. body.push("let jump_offset = " + imm_read + ";");
  269. if(encoding.conditional_jump)
  270. {
  271. assert(
  272. (encoding.opcode & ~0xF) === 0x70 ||
  273. (encoding.opcode & ~0xF) === 0x0F80 ||
  274. (encoding.opcode & ~0x3) === 0xE0
  275. );
  276. const condition_index = encoding.opcode & 0xFF;
  277. body.push(`analysis.ty = ::analysis::AnalysisType::Jump { offset: jump_offset as i32, condition: Some(0x${hex(condition_index, 2)}), is_32: cpu.osize_32() };`);
  278. }
  279. else
  280. {
  281. body.push(`analysis.ty = ::analysis::AnalysisType::Jump { offset: jump_offset as i32, condition: None, is_32: cpu.osize_32() };`);
  282. }
  283. }
  284. else
  285. {
  286. body.push(imm_read + ";");
  287. }
  288. }
  289. if(encoding.extra_imm16)
  290. {
  291. assert(imm_read);
  292. body.push(gen_call("cpu.read_imm16"));
  293. }
  294. else if(encoding.extra_imm8)
  295. {
  296. assert(imm_read);
  297. body.push(gen_call("cpu.read_imm8"));
  298. }
  299. return [].concat(
  300. body,
  301. instruction_postfix
  302. );
  303. }
  304. }
  305. function gen_table()
  306. {
  307. let by_opcode = Object.create(null);
  308. let by_opcode0f = Object.create(null);
  309. for(let o of x86_table)
  310. {
  311. let opcode = o.opcode;
  312. if((opcode & 0xFF00) === 0x0F00)
  313. {
  314. opcode &= 0xFF;
  315. by_opcode0f[opcode] = by_opcode0f[opcode] || [];
  316. by_opcode0f[opcode].push(o);
  317. }
  318. else
  319. {
  320. opcode &= 0xFF;
  321. by_opcode[opcode] = by_opcode[opcode] || [];
  322. by_opcode[opcode].push(o);
  323. }
  324. }
  325. let cases = [];
  326. for(let opcode = 0; opcode < 0x100; opcode++)
  327. {
  328. let encoding = by_opcode[opcode];
  329. assert(encoding && encoding.length);
  330. let opcode_hex = hex(opcode, 2);
  331. let opcode_high_hex = hex(opcode | 0x100, 2);
  332. if(encoding[0].os)
  333. {
  334. cases.push({
  335. conditions: [`0x${opcode_hex}`],
  336. body: gen_instruction_body(encoding, 16),
  337. });
  338. cases.push({
  339. conditions: [`0x${opcode_high_hex}`],
  340. body: gen_instruction_body(encoding, 32),
  341. });
  342. }
  343. else
  344. {
  345. cases.push({
  346. conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`],
  347. body: gen_instruction_body(encoding, undefined),
  348. });
  349. }
  350. }
  351. const table = {
  352. type: "switch",
  353. condition: "opcode",
  354. cases,
  355. default_case: {
  356. body: ["dbg_assert!(false);"]
  357. },
  358. };
  359. if(to_generate.analyzer)
  360. {
  361. const code = [
  362. "#[cfg_attr(rustfmt, rustfmt_skip)]",
  363. "pub fn analyzer(opcode: u32, cpu: &mut ::cpu_context::CpuContext, analysis: &mut ::analysis::Analysis) {",
  364. table,
  365. "}",
  366. ];
  367. finalize_table_rust(
  368. OUT_DIR,
  369. "analyzer.rs",
  370. rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n"
  371. );
  372. }
  373. const cases0f = [];
  374. for(let opcode = 0; opcode < 0x100; opcode++)
  375. {
  376. let encoding = by_opcode0f[opcode];
  377. assert(encoding && encoding.length);
  378. let opcode_hex = hex(opcode, 2);
  379. let opcode_high_hex = hex(opcode | 0x100, 2);
  380. if(encoding[0].os)
  381. {
  382. cases0f.push({
  383. conditions: [`0x${opcode_hex}`],
  384. body: gen_instruction_body(encoding, 16),
  385. });
  386. cases0f.push({
  387. conditions: [`0x${opcode_high_hex}`],
  388. body: gen_instruction_body(encoding, 32),
  389. });
  390. }
  391. else
  392. {
  393. let block = {
  394. conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`],
  395. body: gen_instruction_body(encoding, undefined),
  396. };
  397. cases0f.push(block);
  398. }
  399. }
  400. const table0f = {
  401. type: "switch",
  402. condition: "opcode",
  403. cases: cases0f,
  404. default_case: {
  405. body: ["dbg_assert!(false);"]
  406. },
  407. };
  408. if(to_generate.analyzer0f)
  409. {
  410. const code = [
  411. "#![allow(unused)]",
  412. "#[cfg_attr(rustfmt, rustfmt_skip)]",
  413. "pub fn analyzer(opcode: u32, cpu: &mut ::cpu_context::CpuContext, analysis: &mut ::analysis::Analysis) {",
  414. table0f,
  415. "}"
  416. ];
  417. finalize_table_rust(
  418. OUT_DIR,
  419. "analyzer0f.rs",
  420. rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n"
  421. );
  422. }
  423. }