run.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #!/usr/bin/env node
  2. "use strict";
  3. process.on("unhandledRejection", exn => { throw exn; });
  4. // Mapping between signals and x86 exceptions:
  5. // "Program received signal SIGILL, Illegal instruction." -> #UD (6)
  6. // "Program received signal SIGFPE, Arithmetic exception." -> #DE (0)
  7. // to be determined -> #GP
  8. // to be determined -> #NM
  9. // to be determined -> #TS
  10. // to be determined -> #NP
  11. // to be determined -> #SS
  12. // to be determined -> #PF
  13. // A #UD might indicate a bug in the test generation
  14. const assert = require("assert").strict;
  15. const fs = require("fs");
  16. const path = require("path");
  17. const os = require("os");
  18. const cluster = require("cluster");
  19. const MAX_PARALLEL_TESTS = +process.env.MAX_PARALLEL_TESTS || 99;
  20. const TEST_NAME = process.env.TEST_NAME;
  21. const SINGLE_TEST_TIMEOUT = 10000;
  22. const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
  23. const TEST_DIR = __dirname + "/build/";
  24. const DONE_MSG = "DONE";
  25. const TERMINATE_MSG = "DONE";
  26. const FORCE_JIT = process.argv.includes("--force-jit");
  27. // see --section-start= in makefile
  28. const V86_TEXT_OFFSET = 0x8000;
  29. const NASM_TEXT_OFFSET = 0x800000;
  30. // alternative representation for infinity for json
  31. const JSON_POS_INFINITY = "+INFINITY";
  32. const JSON_NEG_INFINITY = "-INFINITY";
  33. const JSON_POS_NAN = "+NAN";
  34. const JSON_NEG_NAN = "-NAN";
  35. const MASK_ARITH = 1 | 1 << 2 | 1 << 4 | 1 << 6 | 1 << 7 | 1 << 11;
  36. const FPU_TAG_ALL_INVALID = 0xAAAA;
  37. const FPU_STATUS_MASK = 0xFFFF & ~(1 << 9 | 1 << 5 | 1 << 3); // bits that are not correctly implemented by v86
  38. const FP_COMPARISON_SIGNIFICANT_DIGITS = 7;
  39. try {
  40. var V86 = require(`../../build/${TEST_RELEASE_BUILD ? "libv86" : "libv86-debug"}.js`).V86;
  41. }
  42. catch(e) {
  43. console.error(e);
  44. console.error("Failed to import build/libv86-debug.js. Run " +
  45. "`make build/libv86-debug.js` first.");
  46. process.exit(1);
  47. }
  48. function float_equal(x, y)
  49. {
  50. assert(typeof x === "number");
  51. assert(typeof y === "number");
  52. if(x === Infinity && y === Infinity || x === -Infinity && y === -Infinity || isNaN(x) && isNaN(y))
  53. {
  54. return true;
  55. }
  56. const epsilon = Math.pow(10, -FP_COMPARISON_SIGNIFICANT_DIGITS);
  57. return Math.abs(x - y) < epsilon;
  58. }
  59. function format_value(v)
  60. {
  61. if(typeof v === "number")
  62. {
  63. if((v >>> 0) !== v && (v | 0) !== v)
  64. {
  65. return String(v);
  66. }
  67. else
  68. {
  69. return "0x" + (v >>> 0).toString(16);
  70. }
  71. }
  72. else
  73. {
  74. return String(v);
  75. }
  76. }
  77. if(cluster.isMaster)
  78. {
  79. function extract_json(name, fixture_text)
  80. {
  81. let exception;
  82. if(fixture_text.includes("(signal SIGFPE)"))
  83. {
  84. exception = "DE";
  85. }
  86. if(fixture_text.includes("(signal SIGILL)"))
  87. {
  88. exception = "UD";
  89. }
  90. if(fixture_text.includes("(signal SIGSEGV)"))
  91. {
  92. exception = "GP";
  93. }
  94. if(fixture_text.includes("(signal SIGBUS)"))
  95. {
  96. exception = "PF";
  97. }
  98. if(!exception && fixture_text.includes("Program received signal"))
  99. {
  100. throw new Error("Test was killed during execution by gdb: " + name + "\n" + fixture_text);
  101. }
  102. fixture_text = fixture_text.toString()
  103. .replace(/-inf\b/g, JSON.stringify(JSON_NEG_INFINITY))
  104. .replace(/\binf\b/g, JSON.stringify(JSON_POS_INFINITY))
  105. .replace(/-nan\b/g, JSON.stringify(JSON_NEG_NAN))
  106. .replace(/\bnan\b/g, JSON.stringify(JSON_POS_NAN));
  107. const json_regex = /---BEGIN JSON---([\s\[\]\.\+\w":\-,]*)---END JSON---/;
  108. const regex_match = json_regex.exec(fixture_text);
  109. if (!regex_match || regex_match.length < 2) {
  110. throw new Error("Could not find JSON in fixture text: " + fixture_text + "\nTest: " + name);
  111. }
  112. let array = JSON.parse(regex_match[1]);
  113. return {
  114. array: array,
  115. exception,
  116. };
  117. }
  118. function send_work_to_worker(worker, message) {
  119. if(current_test < tests.length) {
  120. const test = tests[current_test];
  121. worker.send(test);
  122. current_test++;
  123. }
  124. else {
  125. worker.send(TERMINATE_MSG);
  126. worker.disconnect();
  127. setTimeout(() => {
  128. // The emulator currently doesn't cleanly exit, so this is necessary
  129. console.log("Worker killed");
  130. worker.kill();
  131. }, 100);
  132. finished_workers++;
  133. if(finished_workers === nr_of_cpus)
  134. {
  135. test_finished();
  136. }
  137. }
  138. }
  139. const dir_files = fs.readdirSync(TEST_DIR);
  140. const files = dir_files.filter((name) => {
  141. return name.endsWith(".asm");
  142. }).map(name => {
  143. return name.slice(0, -4);
  144. }).filter(name => {
  145. return !TEST_NAME || name === TEST_NAME;
  146. });
  147. const tests = files.map(name => {
  148. let fixture_name = name + ".fixture";
  149. let img_name = name + ".img";
  150. let fixture_text = fs.readFileSync(TEST_DIR + fixture_name);
  151. let fixture = extract_json(name, fixture_text);
  152. return {
  153. img_name: img_name,
  154. fixture: fixture,
  155. };
  156. });
  157. const nr_of_cpus = Math.min(
  158. os.cpus().length || 1,
  159. tests.length,
  160. MAX_PARALLEL_TESTS
  161. );
  162. console.log("Using %d cpus", nr_of_cpus);
  163. let current_test = 0;
  164. let failed_tests = [];
  165. let finished_workers = 0;
  166. for(let i = 0; i < nr_of_cpus; i++)
  167. {
  168. let worker = cluster.fork();
  169. worker.on("message", function(message) {
  170. if (message !== DONE_MSG) {
  171. failed_tests.push(message);
  172. }
  173. send_work_to_worker(this);
  174. });
  175. worker.on("online", send_work_to_worker.bind(null, worker));
  176. worker.on("exit", function(code, signal) {
  177. if(code !== 0 && code !== null) {
  178. console.log("Worker error code:", code);
  179. process.exit(code);
  180. }
  181. });
  182. worker.on("error", function(error) {
  183. console.error("Worker error: ", error.toString(), error);
  184. process.exit(1);
  185. });
  186. }
  187. function test_finished()
  188. {
  189. console.log(
  190. "\n[+] Passed %d/%d tests.",
  191. tests.length - failed_tests.length,
  192. tests.length
  193. );
  194. if (failed_tests.length > 0) {
  195. console.log("[-] Failed %d test(s).", failed_tests.length);
  196. failed_tests.forEach(function(test_failure) {
  197. console.error("\n[-] %s:", test_failure.img_name);
  198. test_failure.failures.forEach(function(failure) {
  199. console.error("\n\t" + failure.name);
  200. console.error("\tActual: " + failure.actual);
  201. console.error("\tExpected: " + failure.expected);
  202. });
  203. });
  204. process.exit(1);
  205. }
  206. }
  207. }
  208. else {
  209. function run_test(test)
  210. {
  211. if(!loaded)
  212. {
  213. first_test = test;
  214. return;
  215. }
  216. waiting_to_receive_next_test = false;
  217. current_test = test;
  218. console.info("Testing", test.img_name);
  219. var cpu = emulator.v86.cpu;
  220. assert(!emulator.running);
  221. cpu.reset();
  222. cpu.reset_memory();
  223. cpu.load_multiboot(fs.readFileSync(TEST_DIR + current_test.img_name).buffer);
  224. test_timeout = setTimeout(() => {
  225. console.error("Test " + test.img_name + " timed out after " + (SINGLE_TEST_TIMEOUT / 1000) + " seconds.");
  226. process.exit(2);
  227. }, SINGLE_TEST_TIMEOUT);
  228. if(FORCE_JIT)
  229. {
  230. cpu.jit_force_generate(cpu.instruction_pointer[0]);
  231. cpu.test_hook_did_finalize_wasm = function()
  232. {
  233. cpu.test_hook_did_finalize_wasm = null;
  234. // don't synchronously call into the emulator from this callback
  235. setTimeout(() => {
  236. emulator.run();
  237. }, 0);
  238. };
  239. }
  240. else
  241. {
  242. emulator.run();
  243. }
  244. }
  245. let loaded = false;
  246. let current_test = undefined;
  247. let first_test = undefined;
  248. let waiting_to_receive_next_test = false;
  249. let recorded_exceptions = [];
  250. let test_timeout;
  251. let emulator = new V86({
  252. autostart: false,
  253. memory_size: 2 * 1024 * 1024,
  254. log_level: 0,
  255. });
  256. emulator.add_listener("emulator-loaded", function()
  257. {
  258. loaded = true;
  259. if(first_test)
  260. {
  261. run_test(first_test);
  262. }
  263. });
  264. emulator.cpu_exception_hook = function(n)
  265. {
  266. emulator.v86.cpu.timestamp_counter[0] += 100000; // always make progress
  267. if(waiting_to_receive_next_test)
  268. {
  269. return true;
  270. }
  271. const exceptions = {
  272. 0: "DE",
  273. 6: "UD",
  274. 13: "GP",
  275. };
  276. const exception = exceptions[n];
  277. if(exception === undefined)
  278. {
  279. console.error("Unexpected CPU exception: " + n);
  280. process.exit(1);
  281. }
  282. const eip = emulator.v86.cpu.instruction_pointer[0];
  283. // XXX: On gdb execution is stopped at this point. On v86 we
  284. // currently don't have this ability, so we record the exception
  285. // and continue execution
  286. recorded_exceptions.push({ exception, eip });
  287. finish_test();
  288. return true;
  289. };
  290. emulator.bus.register("cpu-event-halt", function() {
  291. finish_test();
  292. });
  293. function finish_test()
  294. {
  295. if(waiting_to_receive_next_test)
  296. {
  297. return;
  298. }
  299. waiting_to_receive_next_test = true;
  300. clearTimeout(test_timeout);
  301. emulator.stop();
  302. var cpu = emulator.v86.cpu;
  303. const evaluated_fpu_regs = new Float64Array(8).map((_, i) => cpu.fpu_st[i + cpu.fpu_stack_ptr[0] & 7]);
  304. const evaluated_mmxs = cpu.reg_mmxs;
  305. const evaluated_xmms = cpu.reg_xmm32s;
  306. const evaluated_memory = new Int32Array(cpu.mem8.slice(0x120000 - 16 * 4, 0x120000).buffer);
  307. const evaluated_fpu_tag = cpu.fpu_load_tag_word();
  308. const evaluated_fpu_status = cpu.fpu_load_status_word() & FPU_STATUS_MASK;
  309. let individual_failures = [];
  310. assert(current_test.fixture.array);
  311. const FLOAT_TRANSLATION = {
  312. [JSON_POS_INFINITY]: Infinity,
  313. [JSON_NEG_INFINITY]: -Infinity,
  314. [JSON_POS_NAN]: NaN,
  315. [JSON_NEG_NAN]: NaN, // XXX: Ignore sign of NaN
  316. };
  317. let offset = 0;
  318. const expected_reg32 = current_test.fixture.array.slice(offset, offset += 8);
  319. const expected_eip = current_test.fixture.array[offset++];
  320. const expected_fpu_regs =
  321. current_test.fixture.array.slice(offset, offset += 8) .map(x => x in FLOAT_TRANSLATION ? FLOAT_TRANSLATION[x] : x);
  322. const expected_mmx_registers = current_test.fixture.array.slice(offset, offset += 16);
  323. const expected_xmm_registers = current_test.fixture.array.slice(offset, offset += 32);
  324. const expected_memory = current_test.fixture.array.slice(offset, offset += 16);
  325. const expected_eflags = current_test.fixture.array[offset++] & MASK_ARITH;
  326. const fpu_tag = current_test.fixture.array[offset++];
  327. const fpu_status = current_test.fixture.array[offset++] & FPU_STATUS_MASK;
  328. if(!current_test.fixture.exception)
  329. {
  330. for (let i = 0; i < cpu.reg32.length; i++) {
  331. let reg = cpu.reg32[i];
  332. if (reg !== expected_reg32[i]) {
  333. individual_failures.push({
  334. name: "cpu.reg32[" + i + "]",
  335. expected: expected_reg32[i],
  336. actual: reg,
  337. });
  338. }
  339. }
  340. if(fpu_tag !== FPU_TAG_ALL_INVALID)
  341. {
  342. for (let i = 0; i < evaluated_fpu_regs.length; i++) {
  343. if (expected_fpu_regs[i] !== "invalid" &&
  344. !float_equal(evaluated_fpu_regs[i], expected_fpu_regs[i])) {
  345. individual_failures.push({
  346. name: "st" + i,
  347. expected: expected_fpu_regs[i],
  348. actual: evaluated_fpu_regs[i],
  349. });
  350. }
  351. }
  352. if(fpu_status !== evaluated_fpu_status)
  353. {
  354. individual_failures.push({
  355. name: "fpu status word",
  356. expected: fpu_status,
  357. actual: evaluated_fpu_status,
  358. });
  359. }
  360. }
  361. else
  362. {
  363. for (let i = 0; i < evaluated_mmxs.length; i++) {
  364. if (evaluated_mmxs[i] !== expected_mmx_registers[i]) {
  365. individual_failures.push({
  366. name: "mm" + (i >> 1) + ".int32[" + (i & 1) + "] (cpu.reg_mmx[" + i + "])",
  367. expected: expected_mmx_registers[i],
  368. actual: evaluated_mmxs[i],
  369. });
  370. }
  371. }
  372. }
  373. for (let i = 0; i < evaluated_xmms.length; i++) {
  374. if (evaluated_xmms[i] !== expected_xmm_registers[i]) {
  375. individual_failures.push({
  376. name: "xmm" + (i >> 2) + ".int32[" + (i & 3) + "] (cpu.reg_xmm[" + i + "])",
  377. expected: expected_xmm_registers[i],
  378. actual: evaluated_xmms[i],
  379. });
  380. }
  381. }
  382. for (let i = 0; i < evaluated_memory.length; i++) {
  383. if (evaluated_memory[i] !== expected_memory[i]) {
  384. individual_failures.push({
  385. name: "mem[" + i + "]",
  386. expected: expected_memory[i],
  387. actual: evaluated_memory[i],
  388. });
  389. }
  390. }
  391. const seen_eflags = cpu.get_eflags() & MASK_ARITH;
  392. if(seen_eflags !== expected_eflags)
  393. {
  394. individual_failures.push({
  395. name: "eflags",
  396. expected: expected_eflags,
  397. actual: seen_eflags,
  398. });
  399. }
  400. }
  401. if(current_test.fixture.exception)
  402. {
  403. const seen_eip = (recorded_exceptions[0] || {}).eip;
  404. if(seen_eip - V86_TEXT_OFFSET !== expected_eip - NASM_TEXT_OFFSET)
  405. {
  406. individual_failures.push({
  407. name: "exception eip",
  408. expected: expected_eip - NASM_TEXT_OFFSET,
  409. actual: seen_eip === undefined ? "(none)" : seen_eip - V86_TEXT_OFFSET,
  410. });
  411. }
  412. }
  413. const seen_exception = (recorded_exceptions[0] || {}).exception;
  414. if(current_test.fixture.exception !== seen_exception)
  415. {
  416. individual_failures.push({
  417. name: "Exception",
  418. actual: seen_exception || "(none)",
  419. expected: current_test.fixture.exception,
  420. });
  421. }
  422. individual_failures = individual_failures.map(({ name, actual, expected }) => {
  423. return {
  424. name,
  425. actual: format_value(actual),
  426. expected: format_value(expected),
  427. };
  428. });
  429. recorded_exceptions = [];
  430. if (individual_failures.length > 0) {
  431. process.send({
  432. failures: individual_failures,
  433. img_name: current_test.img_name
  434. });
  435. }
  436. else {
  437. process.send(DONE_MSG);
  438. }
  439. }
  440. cluster.worker.on("message", function(message) {
  441. if(message === TERMINATE_MSG)
  442. {
  443. emulator.stop();
  444. emulator = null;
  445. }
  446. else
  447. {
  448. run_test(message);
  449. }
  450. });
  451. }