wuica-cli 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +140 -30
  2. package/dist/data/arch/ADL-P.bin.br +0 -0
  3. package/dist/data/arch/BDW.bin.br +0 -0
  4. package/dist/data/arch/CFL.bin.br +0 -0
  5. package/dist/data/arch/CLX.bin.br +0 -0
  6. package/dist/data/arch/HSW.bin.br +0 -0
  7. package/dist/data/arch/ICL.bin.br +0 -0
  8. package/dist/data/arch/ICX.bin.br +0 -0
  9. package/dist/data/arch/IVB.bin.br +0 -0
  10. package/dist/data/arch/KBL.bin.br +0 -0
  11. package/dist/data/arch/RKL.bin.br +0 -0
  12. package/dist/data/arch/SKL.bin.br +0 -0
  13. package/dist/data/arch/SKX.bin.br +0 -0
  14. package/dist/data/arch/SNB.bin.br +0 -0
  15. package/dist/data/arch/TGL.bin.br +0 -0
  16. package/dist/data/arch/ZEN3.bin.br +0 -0
  17. package/dist/manifest.json +140 -61
  18. package/dist/wuica_wasm.wasm.br +0 -0
  19. package/index.d.ts +41 -3
  20. package/lib/cli.js +280 -17
  21. package/lib/examples.js +26 -0
  22. package/lib/files.js +25 -3
  23. package/lib/index.js +131 -28
  24. package/lib/objfile.js +216 -0
  25. package/lib/thread-worker.js +8 -5
  26. package/lib/threads.js +32 -21
  27. package/lib/wasm.js +30 -5
  28. package/lib/web/caveats.js +8 -0
  29. package/lib/web/examples.js +99 -0
  30. package/lib/web/showcase.js +368 -0
  31. package/package.json +1 -1
  32. package/dist/data/arch/ADL-P.json.br +0 -0
  33. package/dist/data/arch/BDW.json.br +0 -0
  34. package/dist/data/arch/CFL.json.br +0 -0
  35. package/dist/data/arch/CLX.json.br +0 -0
  36. package/dist/data/arch/HSW.json.br +0 -0
  37. package/dist/data/arch/ICL.json.br +0 -0
  38. package/dist/data/arch/ICX.json.br +0 -0
  39. package/dist/data/arch/IVB.json.br +0 -0
  40. package/dist/data/arch/KBL.json.br +0 -0
  41. package/dist/data/arch/RKL.json.br +0 -0
  42. package/dist/data/arch/SKL.json.br +0 -0
  43. package/dist/data/arch/SKX.json.br +0 -0
  44. package/dist/data/arch/SNB.json.br +0 -0
  45. package/dist/data/arch/TGL.json.br +0 -0
  46. package/dist/data/arch/ZEN3.json.br +0 -0
package/lib/index.js CHANGED
@@ -15,9 +15,10 @@ import { archList, DEFAULT_ARCH, ARCH_INFO, ARCH_ORDER } from './archs.js';
15
15
  import { insights } from './insights.js';
16
16
  import { instrDetails, detailInsights } from './details.js';
17
17
  export { detailInsights };
18
- import { readMaybeCompressed } from './files.js';
18
+ import { readMaybeCompressed, readMaybeCompressedSync, tableFile } from './files.js';
19
+ import { readObject, objdumpText, resolveFunction, objectKind } from './objfile.js';
19
20
  import { CODES, WARM_HEX, failure, tableFailure, analysisResult, compareFields } from './core.js';
20
- import { ThreadPool, threadLimit, threadOption, threadsFor } from './threads.js';
21
+ import { ThreadPool, threadLimit, threadOption, threadsForWork } from './threads.js';
21
22
  // the web page's reading of pasted assembly (copies of web/js in lib/web: tests-js/web_pkg_copies.mjs): the loop of a whole function, objdump lines,
22
23
  // exits as not taken, ';' comments, region markers
23
24
  import { assembleMarked, commentFixes, separatorNotes } from './web/asm-regions.js';
@@ -34,6 +35,8 @@ export function listLoops(source, { func = null } = {}) {
34
35
 
35
36
  export { ARCH_INFO, ARCH_ORDER, DEFAULT_ARCH, CODES, WARM_HEX, parseDiagnostics, insights };
36
37
  export { whatIf, VARIANTS as WHAT_IF_VARIANTS } from './whatif.js';
38
+ export { examples, findExample } from './examples.js';
39
+ export { objectKind } from './objfile.js';
37
40
 
38
41
  const DIST = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
39
42
 
@@ -216,8 +219,9 @@ class Wuica {
216
219
  let p = this.#loading.get(name);
217
220
  if (!p) {
218
221
  p = (async () => {
219
- const bytes = await readMaybeCompressed(path.join(this.#dataDir, 'arch', `${name}.json`));
220
- if (!this.#analyzer.hasArch(name)) this.#analyzer.loadArch(name, bytes);
222
+ const file = tableFile(this.#dataDir, name);
223
+ const bytes = await readMaybeCompressed(file);
224
+ if (!this.#analyzer.hasArch(name)) this.#analyzer.loadArch(name, bytes, () => readMaybeCompressedSync(file));
221
225
  })();
222
226
  this.#loading.set(name, p);
223
227
  p.finally(() => this.#loading.delete(name)).catch(() => {});
@@ -358,48 +362,124 @@ class Wuica {
358
362
  if (opts.error) return failure(CODES.REQUEST, opts.error);
359
363
  const code = await this.#code(req);
360
364
  if (code.code !== undefined) return code;
361
- const r = await this.#run(code.hex, arch, Wuica.#withAlignment(req, opts.options, code));
365
+ return Wuica.#analyzeResult(code, await this.#run(code.hex, arch, Wuica.#withAlignment(req, opts.options, code)));
366
+ }
367
+
368
+ // analyze()'s result from the code (#code) and the analysis (#run)
369
+ static #analyzeResult(code, r) {
362
370
  if (r.code !== undefined) return r;
363
371
  const stderr = [...code.stderr];
364
372
  if (r.decodeErrors > 0) stderr.push({ text: `Warning: ${r.decodeErrors} position(s) could not be decoded` });
365
373
  return { code: CODES.OK, ...r, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), stderr };
366
374
  }
367
375
 
368
- // POST /api/compare {source | hex, syntax, archs?, options}: one block on several microarchitectures (default: all).
369
- async compare(request = {}) {
370
- const opts = pickOptions(request, ['archs']);
371
- if (opts.error) return failure(CODES.REQUEST, opts.error);
372
- const code = await this.#code(request);
373
- if (code.code !== undefined) return code;
374
- if (request.archs !== undefined && !Array.isArray(request.archs)) return failure(CODES.REQUEST, '`archs` must be an array of ids');
375
- const ids = request.archs?.length ? uniqueArchs(request.archs, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
376
- const options = { ...Wuica.#withAlignment(request, opts.options, code), includeTrace: false, details: false };
377
- const resolved = ids.map((arch) => this.resolveArch(arch));
378
- // the microarchitectures in threads (if that means at least two threads), each as #run() would on this thread;
379
- // whatever the threads do not do (unknown ids, a thread that failed) is done here, one after another
380
- const fields = new Array(ids.length).fill(null);
381
- const known = resolved.flatMap((id, i) => (id ? [{ i, table: this.#configs[id].name, request: { hex: code.hex, arch: id, ...options } }] : []));
382
- const threads = threadsFor(new Set(known.map((j) => j.table)).size, this.#threads, this.#threadsAuto);
376
+ // Several blocks on one microarchitecture: [request] -> [analyze() result] in the same order (each exactly what
377
+ // analyze(arch, request) returns). The code is assembled here; the analyses run on the threads when the work is worth
378
+ // it (threads.js, threadsForWork).
379
+ async analyzeMany(arch, requests) {
380
+ if (!Array.isArray(requests)) return failure(CODES.REQUEST, '`requests` must be an array');
381
+ const prepared = await this.#prepare(requests, ['arch']);
382
+ const jobs = prepared.flatMap((p, i) => (p.failure ? [] : [{ i, hex: p.code.hex, arch, options: Wuica.#withAlignment(p.request, p.options, p.code), full: true }]));
383
+ const done = await this.#runJobs(jobs);
384
+ const out = prepared.map((p) => p.failure);
385
+ jobs.forEach((j, k) => { out[j.i] = Wuica.#analyzeResult(prepared[j.i].code, done[k]); });
386
+ return out;
387
+ }
388
+
389
+ // Several blocks on several microarchitectures: [request] -> [compare() result] in the same order (each exactly what
390
+ // compare(request) returns; `archs` is that of each request, else of the call, else all). Every block x CPU is one
391
+ // job for the threads.
392
+ async compareMany(requests, { archs } = {}) {
393
+ if (!Array.isArray(requests)) return failure(CODES.REQUEST, '`requests` must be an array');
394
+ const prepared = await this.#prepare(requests, ['archs']);
395
+ const jobs = [], rows = [];
396
+ prepared.forEach((p, i) => {
397
+ if (p.failure) return;
398
+ const list = p.request.archs ?? archs;
399
+ if (list !== undefined && !Array.isArray(list)) { p.failure = failure(CODES.REQUEST, '`archs` must be an array of ids'); return; }
400
+ const ids = list?.length ? uniqueArchs(list, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
401
+ const options = { ...Wuica.#withAlignment(p.request, p.options, p.code), includeTrace: false, details: false };
402
+ rows[i] = ids.map((a) => { jobs.push({ i, hex: p.code.hex, arch: a, options }); return a; });
403
+ });
404
+ const done = await this.#runJobs(jobs);
405
+ let k = 0;
406
+ return prepared.map((p, i) => {
407
+ if (p.failure) return p.failure;
408
+ const fields = rows[i].map(() => done[k++]);
409
+ return this.#compareResult(p.code, rows[i], fields);
410
+ });
411
+ }
412
+
413
+ // The requests checked and their code assembled, one after another: [{request, options, code} | {failure}]
414
+ async #prepare(requests, extra) {
415
+ const out = [];
416
+ for (const req of requests) {
417
+ if (typeof req !== 'object' || req === null) { out.push({ failure: failure(CODES.REQUEST, 'the request must be an object') }); continue; }
418
+ const opts = pickOptions(req, extra);
419
+ if (opts.error) { out.push({ failure: failure(CODES.REQUEST, opts.error) }); continue; }
420
+ const code = await this.#code(req);
421
+ if (code.code !== undefined) { out.push({ failure: code }); continue; }
422
+ out.push({ request: req, options: opts.options, code });
423
+ }
424
+ return out;
425
+ }
426
+
427
+ // [{hex, arch, options, full}] -> the analyses in the same order: analyze results (full) or compare() row fields. On
428
+ // the threads when the work is worth it (threadsForWork) or -threads asks; what they do not do (an unknown arch, a
429
+ // thread that failed) is done here, one after another.
430
+ async #runJobs(list) {
431
+ const out = new Array(list.length).fill(null);
432
+ const known = list.flatMap((j, i) => {
433
+ const id = this.resolveArch(j.arch);
434
+ return id ? [{ i, table: this.#configs[id].name, request: { hex: j.hex, arch: id, ...j.options }, full: !!j.full }] : [];
435
+ });
436
+ const threads = this.#threadsAuto ? threadsForWork(known, this.#threads) : Math.min(this.#threads, known.length);
383
437
  if (threads > 1) {
384
- this.#pool ??= new ThreadPool({ wasm: this.#wasm, uarch: this.#uarch, dataDir: this.#dataDir, limit: this.#threads });
438
+ if (!this.#pool) {
439
+ // the pool compiles the module for its threads once; its bytes are dropped after that
440
+ this.#pool = new ThreadPool({ wasm: this.#wasm, uarch: this.#uarch, dataDir: this.#dataDir, limit: this.#threads });
441
+ this.#wasm = null;
442
+ }
385
443
  if (!this.#pool.broken) {
386
444
  const done = await this.#pool.run(known, threads);
387
- known.forEach((j, k) => { fields[j.i] = done[k]; });
445
+ known.forEach((j, k) => { out[j.i] = done[k]; });
388
446
  }
389
447
  }
390
- const results = [];
391
- for (const [i, arch] of ids.entries()) {
392
- const id = resolved[i];
393
- const { name, year, prototype } = id ? this.#info(id) : { name: String(arch), year: null, prototype: false };
394
- const row = { arch: id ?? String(arch), name, year, prototype };
395
- results.push({ ...row, ...(fields[i] ?? compareFields(await this.#run(code.hex, arch, options))) });
448
+ for (const [i, j] of list.entries()) {
449
+ if (out[i] !== null) continue;
450
+ const r = await this.#run(j.hex, j.arch, j.options);
451
+ out[i] = j.full ? r : compareFields(r);
396
452
  }
453
+ return out;
454
+ }
455
+
456
+ // compare()'s result from the code, the microarchitectures asked for and their fields (#runJobs)
457
+ #compareResult(code, ids, fields) {
458
+ const results = ids.map((arch, i) => {
459
+ const id = this.resolveArch(arch);
460
+ const { name, year, prototype } = id ? this.#info(id) : { name: String(arch), year: null, prototype: false };
461
+ return { arch: id ?? String(arch), name, year, prototype, ...fields[i] };
462
+ });
397
463
  // a CPU that could not decode some instructions (FMA on SNB): its throughput leaves them out
398
464
  const decode = results.filter((r) => r.code === CODES.OK && r.decodeErrors > 0)
399
465
  .map((r) => ({ text: `Warning: ${r.arch}: ${r.decodeErrors} position(s) could not be decoded (instructions it does not have): its throughput leaves them out` }));
400
466
  return { code: CODES.OK, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), stderr: [...code.stderr, ...decode], results };
401
467
  }
402
468
 
469
+ // POST /api/compare {source | hex, syntax, archs?, options}: one block on several microarchitectures (default: all).
470
+ async compare(request = {}) {
471
+ const opts = pickOptions(request, ['archs']);
472
+ if (opts.error) return failure(CODES.REQUEST, opts.error);
473
+ const code = await this.#code(request);
474
+ if (code.code !== undefined) return code;
475
+ if (request.archs !== undefined && !Array.isArray(request.archs)) return failure(CODES.REQUEST, '`archs` must be an array of ids');
476
+ const ids = request.archs?.length ? uniqueArchs(request.archs, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
477
+ const options = { ...Wuica.#withAlignment(request, opts.options, code), includeTrace: false, details: false };
478
+ // each microarchitecture as #run() would do it here, on the threads when the work is worth it (#runJobs)
479
+ const fields = await this.#runJobs(ids.map((arch) => ({ hex: code.hex, arch, options })));
480
+ return this.#compareResult(code, ids, fields);
481
+ }
482
+
403
483
  // Stops compare()'s threads, if any (they also stop by themselves when idle, and never keep the process alive while
404
484
  // idle). The instance stays usable: the next compare() starts them again.
405
485
  async close() {
@@ -452,6 +532,29 @@ class Wuica {
452
532
  };
453
533
  }
454
534
 
535
+ // An object file (ELF or Mach-O, x86-64; objfile.js) as llvm-objdump -d's text of its code, which analyze() and
536
+ // compare() read as `source` (the objdump path: the loop at its address, exits stubbed, the alignment from it).
537
+ // -> {code: 0, text, format, functions: [{name, section, address, size}]} or a failure (another architecture says how
538
+ // to compile for x86-64). `func`: also resolves a -func name (exact, without Mach-O's "_", or a unique part): `func`.
539
+ disassemble(bytes, { name = 'input', func = null } = {}) {
540
+ const obj = readObject(bytes);
541
+ if (obj.error) return failure(CODES.REQUEST, obj.error);
542
+ if (!obj.functions.length) return failure(CODES.REQUEST, 'no functions in the code sections');
543
+ let resolved = null;
544
+ if (func !== null && func !== undefined) {
545
+ const r = resolveFunction(obj.functions, func);
546
+ if (r.error) return failure(CODES.REQUEST, r.error);
547
+ resolved = r.name;
548
+ }
549
+ let text;
550
+ try {
551
+ text = objdumpText(obj, (b) => this.#analyzer.decode(b, 'ALL'), name);
552
+ } catch (e) {
553
+ return failure(CODES.ANALYSIS, `the decoder failed (${e.message})`);
554
+ }
555
+ return { code: CODES.OK, text, format: obj.format, functions: obj.functions.map(({ name: n, section, address, size }) => ({ name: n, section, address, size })), ...(resolved !== null ? { func: resolved } : {}) };
556
+ }
557
+
455
558
  get restarts() { return this.#analyzer.restarts; }
456
559
  }
457
560
 
package/lib/objfile.js ADDED
@@ -0,0 +1,216 @@
1
+ // Object files as input (wuica foo.o): the container is read here (no dependency): ELF (relocatable objects,
2
+ // executables, shared objects) and Mach-O (objects and executables; a universal file's x86-64 slice), x86-64 only. The
3
+ // instructions come from the analyzer's own decoder (wuica_decode), and the result is the text llvm-objdump -d prints for
4
+ // the code sections (addresses, bytes, a mnemonic, branch targets as "0x1b <dot+0x1b>"), so that the objdump path of
5
+ // loop-find.js picks the loop: a .o and `objdump -d` of it give the same pick and the same throughput.
6
+
7
+ const ELF_X86_64 = 62, ELF_AARCH64 = 183, ELF_386 = 3;
8
+ const MACHO_X86_64 = 0x01000007, MACHO_ARM64 = 0x0100000c, MACHO_I386 = 7;
9
+ const td = new TextDecoder();
10
+
11
+ // What a file is, from its first bytes: {kind: 'elf' | 'macho' | 'fat' | 'coff' | 'pe' | 'archive', ...} or null.
12
+ export function objectKind(b) {
13
+ const at = (i, ...xs) => xs.every((x, k) => b[i + k] === x);
14
+ if (at(0, 0x7f, 0x45, 0x4c, 0x46)) return { kind: 'elf' };
15
+ if (at(0, 0xcf, 0xfa, 0xed, 0xfe)) return { kind: 'macho' };
16
+ if (at(0, 0xce, 0xfa, 0xed, 0xfe) || at(0, 0xfe, 0xed, 0xfa, 0xcf) || at(0, 0xfe, 0xed, 0xfa, 0xce)) return { kind: 'macho32' };
17
+ if (at(0, 0xca, 0xfe, 0xba, 0xbe)) return { kind: 'fat' };
18
+ if (at(0, 0x21, 0x3c, 0x61, 0x72, 0x63, 0x68, 0x3e, 0x0a)) return { kind: 'archive' };
19
+ if (at(0, 0x4d, 0x5a)) return { kind: 'pe' };
20
+ if (at(0, 0x64, 0x86) && b.length >= 20) return { kind: 'coff' };
21
+ return null;
22
+ }
23
+
24
+ const ARCH_HELP = 'compile for x86-64: clang --target=x86_64-linux-gnu -c (Linux objects) or clang -arch x86_64 -c (macOS)';
25
+
26
+ // The code of an object file: {format, functions: [{name, section, address, size, bytes}]} or {error}.
27
+ export function readObject(bytes) {
28
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
29
+ const k = objectKind(b);
30
+ if (!k) return { error: 'not an object file' };
31
+ try {
32
+ if (k.kind === 'elf') return readElf(b);
33
+ if (k.kind === 'macho') return readMachO(b, 0);
34
+ if (k.kind === 'fat') return readFat(b);
35
+ if (k.kind === 'macho32') return { error: `a 32-bit Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
36
+ if (k.kind === 'archive') return { error: 'an archive (.a): extract an object from it (ar x lib.a foo.o) and give that' };
37
+ return { error: `${k.kind === 'pe' ? 'a PE (Windows) executable' : 'a COFF object file'}: not supported yet; disassemble it and pipe the listing (llvm-objdump -d FILE | wuica)` };
38
+ } catch (e) {
39
+ return { error: `a damaged or truncated object file (${e.message})` };
40
+ }
41
+ }
42
+
43
+ function view(b) { return new DataView(b.buffer, b.byteOffset, b.byteLength); }
44
+ const u64 = (dv, o) => Number(dv.getBigUint64(o, true));
45
+ const cstr = (b, o) => { let e = o; while (e < b.length && b[e] !== 0) e++; return td.decode(b.subarray(o, e)); };
46
+
47
+ function readElf(b) {
48
+ if (b[4] !== 2) return { error: `a 32-bit ELF file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
49
+ if (b[5] !== 1) return { error: 'a big-endian ELF file: wuica analyzes x86-64 code' };
50
+ const dv = view(b);
51
+ const type = dv.getUint16(16, true), machine = dv.getUint16(18, true);
52
+ if (machine !== ELF_X86_64) {
53
+ const what = machine === ELF_AARCH64 ? 'an AArch64 (arm64)' : machine === ELF_386 ? 'a 32-bit x86' : `a (machine ${machine})`;
54
+ return { error: `${what} ELF file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
55
+ }
56
+ const shoff = u64(dv, 0x28), shentsize = dv.getUint16(0x3a, true), shnum = dv.getUint16(0x3c, true), shstrndx = dv.getUint16(0x3e, true);
57
+ const sh = [];
58
+ for (let i = 0; i < shnum; i++) {
59
+ const o = shoff + i * shentsize;
60
+ sh.push({ nameOff: dv.getUint32(o, true), type: dv.getUint32(o + 4, true), flags: u64(dv, o + 8), addr: u64(dv, o + 16), offset: u64(dv, o + 24), size: u64(dv, o + 32), link: dv.getUint32(o + 40, true), entsize: u64(dv, o + 56) });
61
+ }
62
+ const strtab = sh[shstrndx];
63
+ for (const s of sh) s.name = strtab ? cstr(b, strtab.offset + s.nameOff) : '';
64
+ const relocatable = type === 1;
65
+ // a relocatable object's code sections all start at 0 (-ffunction-sections: one per function): they are laid out one
66
+ // after another at multiples of 64, so that an address modulo 64 (the alignment of a loop) is the one in its section
67
+ // code sections: allocated and executable, with bytes in the file
68
+ const code = sh.map((s, i) => ({ ...s, index: i })).filter((s) => (s.flags & 0x6) === 0x6 && s.type !== 8 && s.size > 0);
69
+ if (!code.length) return { error: 'no code sections (.text) in the file' };
70
+ // the symbols: .symtab, else .dynsym (a stripped executable)
71
+ const symtab = sh.find((s) => s.type === 2) ?? sh.find((s) => s.type === 11);
72
+ const syms = [];
73
+ if (symtab) {
74
+ const names = sh[symtab.link];
75
+ for (let o = symtab.offset; o + 24 <= symtab.offset + symtab.size; o += 24) {
76
+ const info = b[o + 4], shndx = dv.getUint16(o + 6, true), type = info & 0xf;
77
+ const name = cstr(b, names.offset + dv.getUint32(o, true));
78
+ if (!name || (type !== 2 && type !== 0) || shndx === 0 || shndx >= 0xff00) continue;
79
+ syms.push({ name, shndx, value: u64(dv, o + 8), size: u64(dv, o + 16), func: type === 2 });
80
+ }
81
+ }
82
+ const functions = [];
83
+ let next = 0;
84
+ for (const s of code) {
85
+ const base = relocatable ? 0 : s.addr;
86
+ const at = relocatable ? next : s.addr;
87
+ next = Math.ceil((next + s.size) / 64) * 64;
88
+ let list = syms.filter((x) => x.shndx === s.index && !x.name.startsWith('.L'));
89
+ // functions if the file says which (STT_FUNC), else every label in it (hand-written code)
90
+ if (list.some((x) => x.func)) list = list.filter((x) => x.func);
91
+ functions.push(...ranges(list.map((x) => ({ name: x.name, start: x.value - base, size: x.size })), s.size, s.name).map((f) => ({
92
+ ...f, section: s.name, address: at + f.start, bytes: b.subarray(s.offset + f.start, s.offset + f.start + f.size),
93
+ })));
94
+ }
95
+ return { format: `elf64-x86-64${relocatable ? '' : type === 2 ? ' (executable)' : ' (shared object)'}`, functions };
96
+ }
97
+
98
+ // Function ranges in a section of `size` bytes: each symbol to its size, or to the next symbol (or the end); code before
99
+ // the first symbol (or a section without symbols) as one function named after the section.
100
+ function ranges(list, size, section) {
101
+ const sorted = [...list].filter((x) => x.start >= 0 && x.start < size).sort((a, c) => a.start - c.start || a.name.localeCompare(c.name));
102
+ const out = [];
103
+ const seen = new Set();
104
+ if (!sorted.length || sorted[0].start > 0) out.push({ name: section, start: 0, size: sorted.length ? sorted[0].start : size });
105
+ sorted.forEach((x, k) => {
106
+ if (seen.has(x.start)) return; // aliases: the first name
107
+ seen.add(x.start);
108
+ const next = sorted.slice(k + 1).find((y) => y.start > x.start)?.start ?? size;
109
+ out.push({ name: x.name, start: x.start, size: x.size > 0 ? Math.min(x.size, size - x.start) : next - x.start });
110
+ });
111
+ return out.filter((f) => f.size > 0);
112
+ }
113
+
114
+ function readFat(b) {
115
+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); // big-endian header
116
+ const n = dv.getUint32(4, false);
117
+ const archs = [];
118
+ for (let i = 0; i < n; i++) {
119
+ const o = 8 + i * 20;
120
+ const cpu = dv.getUint32(o, false), offset = dv.getUint32(o + 8, false), size = dv.getUint32(o + 12, false);
121
+ archs.push({ cpu, offset, size });
122
+ }
123
+ const x = archs.find((a) => a.cpu === MACHO_X86_64);
124
+ if (!x) return { error: `a universal Mach-O file without x86-64 code (${archs.map((a) => cpuName(a.cpu)).join(', ')}): wuica analyzes x86-64 code; ${ARCH_HELP}` };
125
+ return readMachO(b.subarray(x.offset, x.offset + x.size), 0);
126
+ }
127
+
128
+ const cpuName = (c) => (c === MACHO_ARM64 ? 'arm64' : c === MACHO_X86_64 ? 'x86_64' : c === MACHO_I386 ? 'i386' : `cpu ${c}`);
129
+
130
+ function readMachO(b) {
131
+ const dv = view(b);
132
+ const cpu = dv.getUint32(4, true), filetype = dv.getUint32(12, true), ncmds = dv.getUint32(16, true);
133
+ if (cpu !== MACHO_X86_64) return { error: `${cpu === MACHO_ARM64 ? 'an arm64' : `a ${cpuName(cpu)}`} Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
134
+ const sects = [];
135
+ let symtab = null;
136
+ let o = 32;
137
+ for (let i = 0; i < ncmds; i++) {
138
+ const cmd = dv.getUint32(o, true), size = dv.getUint32(o + 4, true);
139
+ if (cmd === 0x19) { // LC_SEGMENT_64
140
+ const nsects = dv.getUint32(o + 64, true);
141
+ for (let k = 0; k < nsects; k++) {
142
+ const s = o + 72 + k * 80;
143
+ sects.push({ name: cstr(b.subarray(0, s + 16), s), segment: cstr(b.subarray(0, s + 32), s + 16), addr: u64(dv, s + 32), size: u64(dv, s + 40), offset: dv.getUint32(s + 48, true), flags: dv.getUint32(s + 64, true) });
144
+ }
145
+ } else if (cmd === 0x2) { // LC_SYMTAB
146
+ symtab = { symoff: dv.getUint32(o + 8, true), nsyms: dv.getUint32(o + 12, true), stroff: dv.getUint32(o + 16, true) };
147
+ }
148
+ o += size;
149
+ }
150
+ // code: sections with instructions (S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS), with bytes in the file
151
+ const code = sects.map((s, i) => ({ ...s, index: i + 1 })).filter((s) => (s.flags & 0x80000400) !== 0 && (s.flags & 0xff) !== 1 && s.size > 0);
152
+ if (!code.length) return { error: 'no code sections (__text) in the file' };
153
+ const syms = [];
154
+ if (symtab) {
155
+ for (let k = 0; k < symtab.nsyms; k++) {
156
+ const e = symtab.symoff + k * 16;
157
+ const type = b[e + 4], sect = b[e + 5];
158
+ if (type & 0xe0 || (type & 0x0e) !== 0x0e) continue; // debugging entries; not defined in a section
159
+ const name = cstr(b, symtab.stroff + dv.getUint32(e, true));
160
+ // the assembler's local labels (ltmp0, l_..., L...) are not functions
161
+ if (!name || /^(?:ltmp\d+|l_|L)/.test(name)) continue;
162
+ syms.push({ name, sect, value: u64(dv, e + 8) });
163
+ }
164
+ }
165
+ const functions = [];
166
+ for (const s of code) {
167
+ const list = syms.filter((x) => x.sect === s.index).map((x) => ({ name: x.name, start: x.value - s.addr, size: 0 }));
168
+ const label = `${s.segment},${s.name}`;
169
+ functions.push(...ranges(list, s.size, label).map((f) => ({ ...f, section: label, address: s.addr + f.start, bytes: b.subarray(s.offset + f.start, s.offset + f.start + f.size) })));
170
+ }
171
+ return { format: `mach-o x86-64${filetype === 1 ? '' : ' (executable)'}`, functions };
172
+ }
173
+
174
+ // llvm-objdump -d's text of the functions: decode(bytes) -> [{addr, opcode, asm, category}] from the analyzer's decoder
175
+ // (addr relative to the bytes; a branch's target in `asm` relative to its own address, as XED prints it).
176
+ export function objdumpText(obj, decode, name = 'input') {
177
+ const lines = [`${name}:\tfile format ${obj.format}`, ''];
178
+ let section = null;
179
+ for (const f of obj.functions) {
180
+ if (f.section !== section) { lines.push(`Disassembly of section ${f.section}:`, ''); section = f.section; }
181
+ lines.push(`${f.address.toString(16).padStart(16, '0')} <${f.name}>:`);
182
+ const instrs = decode(f.bytes);
183
+ let pos = 0;
184
+ const bytesOf = (from, to) => [...f.bytes.subarray(from, to)].map((x) => x.toString(16).padStart(2, '0')).join(' ');
185
+ const line = (at, len, text) => lines.push(`${(f.address + at).toString(16).padStart(8)}: ${bytesOf(at, at + len).padEnd(29)}\t${text}`);
186
+ for (const i of instrs) {
187
+ for (; pos < i.addr; pos++) line(pos, 1, '<unknown>'); // bytes the decoder could not read
188
+ const len = i.opcode.length / 2;
189
+ let text = i.asm.trim().replace(/\s+/g, ' ');
190
+ const m = /^(\S+) (0x[0-9a-f]+)$/i.exec(text);
191
+ if (m && /^(?:COND_BR|UNCOND_BR|CALL)$/.test(i.category)) {
192
+ const t = f.address + i.addr + Number(BigInt.asIntN(64, BigInt(m[2])));
193
+ const inside = t >= f.address && t < f.address + f.bytes.length;
194
+ text = `${m[1]}\t0x${t.toString(16)}${inside ? ` <${f.name}${t > f.address ? `+0x${(t - f.address).toString(16)}` : ''}>` : ''}`;
195
+ }
196
+ line(i.addr, len, text);
197
+ pos = i.addr + len;
198
+ }
199
+ for (; pos < f.bytes.length; pos++) line(pos, 1, '<unknown>');
200
+ lines.push('');
201
+ }
202
+ return lines.join('\n');
203
+ }
204
+
205
+ // The function a -func name means among an object's functions: exact, else without Mach-O's leading underscore, else a
206
+ // unique part of a name. {name} or {error} (the candidates when ambiguous, the functions when none matches).
207
+ export function resolveFunction(functions, func) {
208
+ const names = [...new Set(functions.map((f) => f.name))];
209
+ if (names.includes(func)) return { name: func };
210
+ const under = names.filter((n) => n === `_${func}`);
211
+ if (under.length === 1) return { name: under[0] };
212
+ const part = names.filter((n) => n.includes(func));
213
+ if (part.length === 1) return { name: part[0] };
214
+ if (part.length > 1) return { error: `func: ${JSON.stringify(func)} is part of ${part.length} function names (${part.join(', ')}): give one of them` };
215
+ return { error: `func: ${JSON.stringify(func)} is not a function of the file (functions: ${names.join(', ') || 'none'})` };
216
+ }
@@ -4,8 +4,9 @@
4
4
  // on stdout).
5
5
  //
6
6
  // workerData: {module (WebAssembly.Module), uarch (bytes of uarch.json), dataDir, recycleBytes}
7
- // Messages in: {id, table, request}
7
+ // Messages in: {id, table, request, full}
8
8
  // Messages out: {type: 'ready'} | {type: 'init-error', message} | {id, fields, recycle}
9
+ // fields: a compare() row's fields, or with `full` the whole analysis result (analyzeMany).
9
10
  // fields null: the table could not be loaded, or the analysis trapped (it may only have hit this thread's memory
10
11
  // limit): the main thread does it again, so that the row is the one it would have made itself.
11
12
  // recycle: this thread should be stopped (its memory, which never shrinks, has grown beyond recycleBytes, or it trapped).
@@ -13,7 +14,7 @@
13
14
  import path from 'node:path';
14
15
  import { parentPort, workerData } from 'node:worker_threads';
15
16
  import { Analyzer } from './wasm.js';
16
- import { readMaybeCompressed } from './files.js';
17
+ import { readMaybeCompressed, readMaybeCompressedSync, tableFile } from './files.js';
17
18
  import { analysisResult, compareFields } from './core.js';
18
19
 
19
20
  const { module, uarch, dataDir, recycleBytes } = workerData;
@@ -26,10 +27,11 @@ try {
26
27
  }
27
28
 
28
29
  if (analyzer) {
29
- parentPort.on('message', async ({ id, table, request }) => {
30
+ parentPort.on('message', async ({ id, table, request, full }) => {
30
31
  if (!analyzer.hasArch(table)) {
31
32
  try {
32
- analyzer.loadArch(table, await readMaybeCompressed(path.join(dataDir, 'arch', `${table}.json`)));
33
+ const file = tableFile(dataDir, table);
34
+ analyzer.loadArch(table, await readMaybeCompressed(file), () => readMaybeCompressedSync(file));
33
35
  } catch {
34
36
  parentPort.postMessage({ id, fields: null, recycle: analyzer.memoryBytes === 0 }); // 0: the module trapped
35
37
  return;
@@ -40,7 +42,8 @@ if (analyzer) {
40
42
  parentPort.postMessage({ id, fields: null, recycle: true });
41
43
  return;
42
44
  }
43
- parentPort.postMessage({ id, fields: compareFields(analysisResult(response)), recycle: analyzer.memoryBytes > recycleBytes });
45
+ const result = analysisResult(response);
46
+ parentPort.postMessage({ id, fields: full ? result : compareFields(result), recycle: analyzer.memoryBytes > recycleBytes });
44
47
  });
45
48
  parentPort.postMessage({ type: 'ready' });
46
49
  }
package/lib/threads.js CHANGED
@@ -25,7 +25,7 @@ import os from 'node:os';
25
25
  import path from 'node:path';
26
26
  import { Worker, isMainThread } from 'node:worker_threads';
27
27
  import { Analyzer, capMemory } from './wasm.js';
28
- import { readMaybeCompressed } from './files.js';
28
+ import { readMaybeCompressed, tableFile } from './files.js';
29
29
  import { WARM_HEX } from './core.js';
30
30
 
31
31
  const WORKER = new URL('./thread-worker.js', import.meta.url);
@@ -56,14 +56,21 @@ export function threadOption(option, env = process.env) {
56
56
  return raw === 0 || raw === '0' ? 'auto' : raw;
57
57
  }
58
58
 
59
- // The threads for a compare of jobs with `tables` different tables: one per table, at most `limit`; with "auto", at
60
- // most one per two tables. A thread's start costs about as much as an analysis (it starts, loads its table, and its first
61
- // analysis runs on code that is not optimized yet, which on aethia makes the SHA-256 showcase take ~100-230 instead of
62
- // ~45 ms), so a thread pays off from its second analysis on: on aethia (8 cores, 16 threads) -arch all takes 0.60 s
63
- // with 4 or 8 threads, 0.67 s with 12 and 0.71 s with 15 (1.05 s without threads), and for a small block 8 threads are
64
- // as fast as none and 15 are 12% slower.
65
- export function threadsFor(tables, limit, auto) {
66
- return Math.min(limit, auto ? Math.ceil(tables / 2) : tables);
59
+ // The default number of threads for a set of jobs ([{table, request: {hex}}]: blocks x microarchitectures), from the
60
+ // work they are: the estimated time on this thread (each table loaded once, each analysis a fixed cost plus a cost per
61
+ // instruction). Below WORK.minMs no threads (a thread's start, its table and its first, unoptimized analysis cost more
62
+ // than they save); else one thread per WORK.perThreadMs, from 2 to WORK.max, at most the cores but one (and `limit`),
63
+ // and at most one per job. Measurements: docs/PORTING.md, "Threads".
64
+ export const WORK = Object.freeze({ tableMs: 8, jobMs: 1.2, instrMs: 0.009, minMs: 300, perThreadMs: 150, max: 8 });
65
+ export function workMs(jobs) {
66
+ const tables = new Set(jobs.map((j) => j.table)).size;
67
+ // ~4 bytes (8 hex digits) per instruction
68
+ return tables * WORK.tableMs + jobs.reduce((s, j) => s + WORK.jobMs + (j.request.hex.length / 8) * WORK.instrMs, 0);
69
+ }
70
+ export function threadsForWork(jobs, limit, cores = os.availableParallelism()) {
71
+ const ms = workMs(jobs);
72
+ if (ms < WORK.minMs || jobs.length < 2) return 1;
73
+ return Math.max(1, Math.min(limit, cores - 1, jobs.length, Math.max(2, Math.min(WORK.max, Math.ceil(ms / WORK.perThreadMs)))));
67
74
  }
68
75
 
69
76
  export class ThreadPool {
@@ -88,15 +95,18 @@ export class ThreadPool {
88
95
 
89
96
  get threads() { return this.#slots.length; }
90
97
 
91
- // jobs: [{table, request}] -> a promise of [fields | null] in the same order (null: not done, run it elsewhere).
92
- // A thread is started for each table no thread has, while there are fewer than `threads` (and `limit`).
98
+ // jobs: [{table, request, full}] -> a promise of [fields | null] in the same order (null: not done, run it elsewhere;
99
+ // full: the whole analysis result instead of a compare() row's fields). Threads are started while there are fewer
100
+ // than `threads` (and `limit`) and jobs wait.
93
101
  async run(jobs, threads = this.#limit) {
94
102
  this.#want = Math.min(this.#limit, threads);
95
103
  clearTimeout(this.#idleTimer);
96
104
  this.#idleTimer = null;
97
105
  if (!this.#workerData) {
98
106
  const maxBytes = maxMemoryBytes(this.#limit);
107
+ // (the module's bytes are not needed after this: the threads get the compiled module)
99
108
  this.#compiled ??= WebAssembly.compile(capMemory(this.#wasm, maxBytes / (64 * 1024)));
109
+ this.#wasm = null;
100
110
  try {
101
111
  const module = await this.#compiled;
102
112
  this.#workerData ??= { module, uarch: this.#uarch, dataDir: this.#dataDir, recycleBytes: maxBytes / 2 };
@@ -104,9 +114,9 @@ export class ThreadPool {
104
114
  this.broken = true;
105
115
  }
106
116
  }
107
- const out = Promise.all(jobs.map(({ table, request }) => new Promise((resolve) => {
117
+ const out = Promise.all(jobs.map(({ table, request, full = false }) => new Promise((resolve) => {
108
118
  if (this.broken) { resolve(null); return; }
109
- this.#queue.push({ id: this.#nextId++, table, request, resolve });
119
+ this.#queue.push({ id: this.#nextId++, table, request, full, resolve });
110
120
  })));
111
121
  // (not for a small block: its analyses are short, and the warm-up would compete with them for the CPU)
112
122
  if (this.#pump() && !this.#warmed && jobs[0]?.request.hex.length >= WARM_MIN_HEX) {
@@ -118,7 +128,7 @@ export class ThreadPool {
118
128
 
119
129
  // One analysis of WARM_HEX on an instance of the threads' module (see the top); the instance is dropped afterwards.
120
130
  async #warmUp({ table, request }) {
121
- const bytes = await readMaybeCompressed(path.join(this.#dataDir, 'arch', `${table}.json`));
131
+ const bytes = await readMaybeCompressed(tableFile(this.#dataDir, table));
122
132
  const a = new Analyzer(this.#workerData.module);
123
133
  a.loadUarch(this.#uarch);
124
134
  a.loadArch(table, bytes);
@@ -127,15 +137,17 @@ export class ThreadPool {
127
137
 
128
138
  #owner(table) { return this.#slots.find((s) => s.tables.has(table)); }
129
139
 
130
- // The job for a free thread: one of its tables, else one of a table no thread has.
140
+ // The job for a free thread: one of its tables, else one of a table no thread has, else any (its table is loaded
141
+ // here too: many blocks on one microarchitecture).
131
142
  #pick(slot) {
132
143
  let i = this.#queue.findIndex((j) => slot.tables.has(j.table));
133
144
  if (i < 0) i = this.#queue.findIndex((j) => !this.#owner(j.table));
145
+ if (i < 0) i = this.#queue.length ? 0 : -1;
134
146
  return i < 0 ? null : this.#queue.splice(i, 1)[0];
135
147
  }
136
148
 
137
- // Gives the waiting jobs to free threads, and starts a thread for each job of a table no thread has (up to the
138
- // limit). Returns the number of threads started.
149
+ // Gives the waiting jobs to free threads, and starts threads for the jobs left (up to the threads wanted): first
150
+ // for tables no thread has. Returns the number of threads started.
139
151
  #pump() {
140
152
  for (const s of this.#slots) {
141
153
  if (s.job || !this.#queue.length) continue;
@@ -143,9 +155,8 @@ export class ThreadPool {
143
155
  if (j) this.#start(s, j);
144
156
  }
145
157
  let started = 0;
146
- while (this.#slots.length < this.#want) {
147
- const i = this.#queue.findIndex((j) => !this.#owner(j.table));
148
- if (i < 0) break;
158
+ while (this.#slots.length < this.#want && this.#queue.length) {
159
+ const i = Math.max(0, this.#queue.findIndex((j) => !this.#owner(j.table)));
149
160
  this.#spawn(this.#queue.splice(i, 1)[0]);
150
161
  started++;
151
162
  }
@@ -157,7 +168,7 @@ export class ThreadPool {
157
168
  slot.job = job;
158
169
  slot.tables.add(job.table);
159
170
  slot.worker.ref();
160
- slot.worker.postMessage({ id: job.id, table: job.table, request: job.request });
171
+ slot.worker.postMessage({ id: job.id, table: job.table, request: job.request, full: job.full });
161
172
  }
162
173
 
163
174
  #spawn(job) {