wuica-cli 0.0.0-stage → 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.
- package/LICENSE +661 -0
- package/README.md +546 -2
- package/bin/wuica-mcp.js +16 -0
- package/bin/wuica.js +25 -0
- package/dist/data/arch/ADL-P.bin.br +0 -0
- package/dist/data/arch/BDW.bin.br +0 -0
- package/dist/data/arch/CFL.bin.br +0 -0
- package/dist/data/arch/CLX.bin.br +0 -0
- package/dist/data/arch/HSW.bin.br +0 -0
- package/dist/data/arch/ICL.bin.br +0 -0
- package/dist/data/arch/ICX.bin.br +0 -0
- package/dist/data/arch/IVB.bin.br +0 -0
- package/dist/data/arch/KBL.bin.br +0 -0
- package/dist/data/arch/RKL.bin.br +0 -0
- package/dist/data/arch/SKL.bin.br +0 -0
- package/dist/data/arch/SKX.bin.br +0 -0
- package/dist/data/arch/SNB.bin.br +0 -0
- package/dist/data/arch/TGL.bin.br +0 -0
- package/dist/data/arch/ZEN3.bin.br +0 -0
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +160 -0
- package/dist/wuica_asm.wasm.br +0 -0
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +410 -0
- package/lib/archs.js +44 -0
- package/lib/cli.js +693 -0
- package/lib/core.js +36 -0
- package/lib/details.js +60 -0
- package/lib/examples.js +26 -0
- package/lib/files.js +40 -0
- package/lib/index.js +577 -0
- package/lib/insights.js +100 -0
- package/lib/mcp.js +366 -0
- package/lib/objfile.js +216 -0
- package/lib/thread-worker.js +49 -0
- package/lib/threads.js +235 -0
- package/lib/wasm.js +246 -0
- package/lib/web/accum.js +202 -0
- package/lib/web/asm-regions.js +415 -0
- package/lib/web/assembler.js +188 -0
- package/lib/web/caveats.js +214 -0
- package/lib/web/examples.js +99 -0
- package/lib/web/loop-find.js +492 -0
- package/lib/web/showcase.js +368 -0
- package/lib/whatif.js +136 -0
- package/licenses/LICENSE-LLVM.txt +279 -0
- package/licenses/LICENSE-XED.txt +178 -0
- package/package.json +58 -4
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
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// A worker thread of the library's thread pool (threads.js): an analyzer instance of the shared compiled module (whose
|
|
2
|
+
// memory has a smaller limit than the main thread's), with the tables of the microarchitectures it is given. It answers
|
|
3
|
+
// one job at a time with the fields of a compare() row. Nothing in here writes to stdout (the MCP server speaks JSON-RPC
|
|
4
|
+
// on stdout).
|
|
5
|
+
//
|
|
6
|
+
// workerData: {module (WebAssembly.Module), uarch (bytes of uarch.json), dataDir, recycleBytes}
|
|
7
|
+
// Messages in: {id, table, request, full}
|
|
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).
|
|
10
|
+
// fields null: the table could not be loaded, or the analysis trapped (it may only have hit this thread's memory
|
|
11
|
+
// limit): the main thread does it again, so that the row is the one it would have made itself.
|
|
12
|
+
// recycle: this thread should be stopped (its memory, which never shrinks, has grown beyond recycleBytes, or it trapped).
|
|
13
|
+
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
16
|
+
import { Analyzer } from './wasm.js';
|
|
17
|
+
import { readMaybeCompressed, readMaybeCompressedSync, tableFile } from './files.js';
|
|
18
|
+
import { analysisResult, compareFields } from './core.js';
|
|
19
|
+
|
|
20
|
+
const { module, uarch, dataDir, recycleBytes } = workerData;
|
|
21
|
+
let analyzer = null;
|
|
22
|
+
try {
|
|
23
|
+
analyzer = new Analyzer(module);
|
|
24
|
+
analyzer.loadUarch(uarch);
|
|
25
|
+
} catch (e) {
|
|
26
|
+
parentPort.postMessage({ type: 'init-error', message: String(e?.message ?? e) });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (analyzer) {
|
|
30
|
+
parentPort.on('message', async ({ id, table, request, full }) => {
|
|
31
|
+
if (!analyzer.hasArch(table)) {
|
|
32
|
+
try {
|
|
33
|
+
const file = tableFile(dataDir, table);
|
|
34
|
+
analyzer.loadArch(table, await readMaybeCompressed(file), () => readMaybeCompressedSync(file));
|
|
35
|
+
} catch {
|
|
36
|
+
parentPort.postMessage({ id, fields: null, recycle: analyzer.memoryBytes === 0 }); // 0: the module trapped
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const response = analyzer.analyze(request);
|
|
41
|
+
if (response.trapped || analyzer.memoryBytes === 0) { // trapped, or could not be restarted after an earlier trap
|
|
42
|
+
parentPort.postMessage({ id, fields: null, recycle: true });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const result = analysisResult(response);
|
|
46
|
+
parentPort.postMessage({ id, fields: full ? result : compareFields(result), recycle: analyzer.memoryBytes > recycleBytes });
|
|
47
|
+
});
|
|
48
|
+
parentPort.postMessage({ type: 'ready' });
|
|
49
|
+
}
|
package/lib/threads.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Worker threads for compare(): the analyses of one block on several microarchitectures run in parallel, one per thread
|
|
2
|
+
// at a time (thread-worker.js). The module is compiled once for all threads, and each thread loads only the tables of
|
|
3
|
+
// the microarchitectures it is given.
|
|
4
|
+
//
|
|
5
|
+
// - Memory: the threads' module has a smaller memory limit than the main thread's (maxMemoryBytes: a quarter of the
|
|
6
|
+
// RAM shared by the threads, from 256 MiB to 1 GiB each), so that an input that needs a lot of memory cannot take it
|
|
7
|
+
// on every thread at once. An analysis that traps in a thread (it may only have hit that limit) is given back to the
|
|
8
|
+
// caller, which runs it on its own thread, so the result is the same as without threads. A thread whose memory has
|
|
9
|
+
// grown beyond half its limit (it never shrinks) is stopped after its job.
|
|
10
|
+
// - The pool is started by the first compare() that uses threads and kept for the next ones; its threads are started
|
|
11
|
+
// as jobs need them, up to the number run() is given (and `limit`). While no job runs they do not keep the process alive, and
|
|
12
|
+
// after IDLE_MS without a job they are stopped (close() stops them at once).
|
|
13
|
+
// - A table is pinned to the thread that loaded it: a job goes to a thread that has its table, else a table no thread
|
|
14
|
+
// has goes to the first free thread (or a new one). So every table is loaded once, whatever the number of compares.
|
|
15
|
+
// A new thread gets its first job at once (it waits in the thread's queue while the thread starts).
|
|
16
|
+
// - Warm-up: V8 compiles the module's functions when they are first called (and optimizes the hot ones later, in the
|
|
17
|
+
// background), and the compiled code belongs to the module, which the threads share. While new threads start
|
|
18
|
+
// (~80 ms), this thread analyzes a block once on an instance of their module, so that they find most of the code
|
|
19
|
+
// compiled (on aethia the first analysis of the SHA-256 showcase in 8 new threads at once takes ~100 instead of
|
|
20
|
+
// ~230 ms).
|
|
21
|
+
// - A thread that cannot start or stops unexpectedly does not fail anything: its jobs resolve to null and the caller
|
|
22
|
+
// runs them on its own thread. After a start failure the pool is `broken` and the caller stops using it.
|
|
23
|
+
|
|
24
|
+
import os from 'node:os';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { Worker, isMainThread } from 'node:worker_threads';
|
|
27
|
+
import { Analyzer, capMemory } from './wasm.js';
|
|
28
|
+
import { readMaybeCompressed, tableFile } from './files.js';
|
|
29
|
+
import { WARM_HEX } from './core.js';
|
|
30
|
+
|
|
31
|
+
const WORKER = new URL('./thread-worker.js', import.meta.url);
|
|
32
|
+
export const IDLE_MS = 30_000;
|
|
33
|
+
const WARM_MIN_HEX = 2 * 1024; // the smallest block (hex digits: 1 KB of code, ~250 instructions) that gets a warm-up
|
|
34
|
+
const MIB = 2 ** 20;
|
|
35
|
+
|
|
36
|
+
// The memory limit of a thread's analyzer, for `threads` threads.
|
|
37
|
+
export function maxMemoryBytes(threads, total = os.totalmem()) {
|
|
38
|
+
return Math.min(1024 * MIB, Math.max(256 * MIB, Math.floor(total / 4 / Math.max(1, threads) / (64 * 1024)) * 64 * 1024));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The most threads compare() uses: `option` (createWuica's `threads`), else the environment variable WUICA_THREADS,
|
|
42
|
+
// else "auto": os.availableParallelism() (on the main thread; 1 inside a worker thread). 1 means no threads.
|
|
43
|
+
export function threadLimit(option, env = process.env) {
|
|
44
|
+
const raw = threadOption(option, env);
|
|
45
|
+
if (raw === 'auto') return isMainThread ? Math.max(1, os.availableParallelism()) : 1;
|
|
46
|
+
const n = Number(raw);
|
|
47
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
48
|
+
throw new TypeError(`${option !== undefined && option !== null ? 'threads' : 'WUICA_THREADS'}: expected a non-negative integer or "auto", got ${JSON.stringify(raw)}`);
|
|
49
|
+
}
|
|
50
|
+
return n;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// The option as given (option, else WUICA_THREADS), "auto" if there is none (also for 0).
|
|
54
|
+
export function threadOption(option, env = process.env) {
|
|
55
|
+
const raw = option ?? (env.WUICA_THREADS === undefined || env.WUICA_THREADS === '' ? 'auto' : env.WUICA_THREADS);
|
|
56
|
+
return raw === 0 || raw === '0' ? 'auto' : raw;
|
|
57
|
+
}
|
|
58
|
+
|
|
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)))));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export class ThreadPool {
|
|
77
|
+
#workerData = null;
|
|
78
|
+
#wasm; #uarch; #dataDir;
|
|
79
|
+
#compiled = null; // promise of the module with the threads' memory limit
|
|
80
|
+
#limit;
|
|
81
|
+
#slots = []; // {worker, ready, job, tables: Set}
|
|
82
|
+
#warmed = false;
|
|
83
|
+
#want; // the threads the latest run() may start
|
|
84
|
+
#queue = []; // {id, table, request, resolve}
|
|
85
|
+
#nextId = 1;
|
|
86
|
+
#idleTimer = null;
|
|
87
|
+
broken = false;
|
|
88
|
+
|
|
89
|
+
// wasm: the bytes of the analyzer module; uarch: the bytes of uarch.json; limit: the most threads.
|
|
90
|
+
constructor({ wasm, uarch, dataDir, limit }) {
|
|
91
|
+
this.#wasm = wasm; this.#uarch = uarch; this.#dataDir = dataDir;
|
|
92
|
+
this.#limit = limit;
|
|
93
|
+
this.#want = limit;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
get threads() { return this.#slots.length; }
|
|
97
|
+
|
|
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.
|
|
101
|
+
async run(jobs, threads = this.#limit) {
|
|
102
|
+
this.#want = Math.min(this.#limit, threads);
|
|
103
|
+
clearTimeout(this.#idleTimer);
|
|
104
|
+
this.#idleTimer = null;
|
|
105
|
+
if (!this.#workerData) {
|
|
106
|
+
const maxBytes = maxMemoryBytes(this.#limit);
|
|
107
|
+
// (the module's bytes are not needed after this: the threads get the compiled module)
|
|
108
|
+
this.#compiled ??= WebAssembly.compile(capMemory(this.#wasm, maxBytes / (64 * 1024)));
|
|
109
|
+
this.#wasm = null;
|
|
110
|
+
try {
|
|
111
|
+
const module = await this.#compiled;
|
|
112
|
+
this.#workerData ??= { module, uarch: this.#uarch, dataDir: this.#dataDir, recycleBytes: maxBytes / 2 };
|
|
113
|
+
} catch {
|
|
114
|
+
this.broken = true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const out = Promise.all(jobs.map(({ table, request, full = false }) => new Promise((resolve) => {
|
|
118
|
+
if (this.broken) { resolve(null); return; }
|
|
119
|
+
this.#queue.push({ id: this.#nextId++, table, request, full, resolve });
|
|
120
|
+
})));
|
|
121
|
+
// (not for a small block: its analyses are short, and the warm-up would compete with them for the CPU)
|
|
122
|
+
if (this.#pump() && !this.#warmed && jobs[0]?.request.hex.length >= WARM_MIN_HEX) {
|
|
123
|
+
this.#warmed = true;
|
|
124
|
+
this.#warmUp(jobs[0]).catch(() => {});
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// One analysis of WARM_HEX on an instance of the threads' module (see the top); the instance is dropped afterwards.
|
|
130
|
+
async #warmUp({ table, request }) {
|
|
131
|
+
const bytes = await readMaybeCompressed(tableFile(this.#dataDir, table));
|
|
132
|
+
const a = new Analyzer(this.#workerData.module);
|
|
133
|
+
a.loadUarch(this.#uarch);
|
|
134
|
+
a.loadArch(table, bytes);
|
|
135
|
+
a.analyze({ hex: WARM_HEX, arch: request.arch });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#owner(table) { return this.#slots.find((s) => s.tables.has(table)); }
|
|
139
|
+
|
|
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).
|
|
142
|
+
#pick(slot) {
|
|
143
|
+
let i = this.#queue.findIndex((j) => slot.tables.has(j.table));
|
|
144
|
+
if (i < 0) i = this.#queue.findIndex((j) => !this.#owner(j.table));
|
|
145
|
+
if (i < 0) i = this.#queue.length ? 0 : -1;
|
|
146
|
+
return i < 0 ? null : this.#queue.splice(i, 1)[0];
|
|
147
|
+
}
|
|
148
|
+
|
|
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.
|
|
151
|
+
#pump() {
|
|
152
|
+
for (const s of this.#slots) {
|
|
153
|
+
if (s.job || !this.#queue.length) continue;
|
|
154
|
+
const j = this.#pick(s);
|
|
155
|
+
if (j) this.#start(s, j);
|
|
156
|
+
}
|
|
157
|
+
let started = 0;
|
|
158
|
+
while (this.#slots.length < this.#want && this.#queue.length) {
|
|
159
|
+
const i = Math.max(0, this.#queue.findIndex((j) => !this.#owner(j.table)));
|
|
160
|
+
this.#spawn(this.#queue.splice(i, 1)[0]);
|
|
161
|
+
started++;
|
|
162
|
+
}
|
|
163
|
+
this.#idle();
|
|
164
|
+
return started;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#start(slot, job) {
|
|
168
|
+
slot.job = job;
|
|
169
|
+
slot.tables.add(job.table);
|
|
170
|
+
slot.worker.ref();
|
|
171
|
+
slot.worker.postMessage({ id: job.id, table: job.table, request: job.request, full: job.full });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
#spawn(job) {
|
|
175
|
+
const worker = new Worker(WORKER, { workerData: this.#workerData, stdout: true, stderr: true });
|
|
176
|
+
const slot = { worker, ready: false, job: null, tables: new Set() };
|
|
177
|
+
this.#slots.push(slot);
|
|
178
|
+
this.#start(slot, job);
|
|
179
|
+
worker.on('message', (m) => {
|
|
180
|
+
if (m.type === 'ready') {
|
|
181
|
+
slot.ready = true;
|
|
182
|
+
} else if (m.type === 'init-error') {
|
|
183
|
+
this.#fail(slot, true);
|
|
184
|
+
} else if (slot.job && m.id === slot.job.id) {
|
|
185
|
+
const job = slot.job;
|
|
186
|
+
slot.job = null;
|
|
187
|
+
worker.unref();
|
|
188
|
+
job.resolve(m.fields);
|
|
189
|
+
if (m.recycle) this.#remove(slot);
|
|
190
|
+
this.#pump();
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
worker.on('error', () => this.#fail(slot, !slot.ready));
|
|
194
|
+
worker.on('exit', () => this.#fail(slot, !slot.ready));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Stops a thread and forgets it (its tables are no longer pinned to it). False if it was gone already.
|
|
198
|
+
#remove(slot) {
|
|
199
|
+
const i = this.#slots.indexOf(slot);
|
|
200
|
+
if (i < 0) return false;
|
|
201
|
+
this.#slots.splice(i, 1);
|
|
202
|
+
slot.worker.terminate().catch(() => {});
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// A thread that failed: its job (and, if it never started, every waiting job) is given back to the caller.
|
|
207
|
+
#fail(slot, atStart) {
|
|
208
|
+
if (!this.#remove(slot)) return;
|
|
209
|
+
slot.job?.resolve(null);
|
|
210
|
+
slot.job = null;
|
|
211
|
+
if (atStart) this.broken = true;
|
|
212
|
+
if (this.broken) for (const j of this.#queue.splice(0)) j.resolve(null);
|
|
213
|
+
this.#pump();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// No job left: the threads are stopped after IDLE_MS (a timer that does not keep the process alive).
|
|
217
|
+
#idle() {
|
|
218
|
+
if (this.#queue.length || this.#slots.some((s) => s.job) || this.#idleTimer || !this.#slots.length) return;
|
|
219
|
+
this.#idleTimer = setTimeout(() => { this.#idleTimer = null; this.close(); }, IDLE_MS);
|
|
220
|
+
this.#idleTimer.unref();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Stops the threads; waiting and running jobs resolve to null. The next run() starts new ones.
|
|
224
|
+
async close() {
|
|
225
|
+
clearTimeout(this.#idleTimer);
|
|
226
|
+
this.#idleTimer = null;
|
|
227
|
+
const slots = this.#slots.splice(0);
|
|
228
|
+
for (const j of this.#queue.splice(0)) j.resolve(null);
|
|
229
|
+
await Promise.all(slots.map((s) => {
|
|
230
|
+
s.job?.resolve(null);
|
|
231
|
+
s.job = null;
|
|
232
|
+
return s.worker.terminate().catch(() => {});
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
}
|