wuica-cli 0.1.9 → 0.1.12

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/lib/mcp.js CHANGED
@@ -9,8 +9,9 @@
9
9
 
10
10
  import fs from 'node:fs';
11
11
  import readline from 'node:readline';
12
- import { createWuica } from './index.js';
13
- import { whatIf, VARIANTS } from './whatif.js';
12
+ import { createWuica, listLoops } from './index.js';
13
+ import { whatIfRequest, VARIANTS, OPT_IN_VARIANTS } from './web/whatif-core.js';
14
+ import { diffRequest } from './web/block-diff.js';
14
15
 
15
16
  const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
16
17
 
@@ -19,29 +20,17 @@ export const SERVER_INFO = Object.freeze({ name: 'wuica', version: pkg.version }
19
20
  export const CAPABILITIES = Object.freeze({ tools: { listChanged: true } });
20
21
 
21
22
  const ASSUMPTIONS =
22
- 'The number is the predicted steady-state throughput in core clock cycles per iteration of the block: a block that ends ' +
23
- 'with a (conditional) branch is simulated as a loop body; any other block as if it were unrolled, i.e. repeated back to ' +
24
- 'back. Lower is faster. Assumptions: all memory accesses hit the L1 data cache, no branch mispredictions, no ' +
25
- 'interference from other code or hyperthreads; the result does not depend on register or memory values except through ' +
26
- 'dependencies. ZEN3, ADL-P and ICX are prototype models (experimental, from the fork jtl06/uiCA), less validated than ' +
27
- "uiCA's Intel models (SNB through RKL).";
23
+ 'tp is the predicted steady-state throughput in core cycles per iteration (lower is faster): a block that ends with a ' +
24
+ 'branch is simulated as a loop body, any other as if repeated back to back. Assumes all data in L1, no branch ' +
25
+ 'mispredictions, nothing else on the core. ZEN3, ADL-P and ICX are prototype models (the fork jtl06/uiCA), less ' +
26
+ "validated than uiCA's Intel models.";
28
27
 
29
28
  const INPUT_NOTE =
30
- 'Give the block either as `source` (x86-64 assembly in Intel (noprefix) or AT&T syntax: detected unless `syntax` says; one instruction per ' +
31
- 'line; labels and directives are allowed, e.g. "loop: add rax, [rsi]\\n dec rcx\\n jnz loop") or as `hex` (machine ' +
32
- 'code bytes, e.g. "4801d8"). A whole function (gcc -S or clang -S output, objdump -d lines with addresses, with or ' +
33
- 'without the bytes) is fine: by default (`loop: "auto"`) its innermost loop is analyzed (the first one in the code), ' +
34
- 'or the body without prologue and epilogue if it is a compiler\'s function without a loop; the deepest loop is ' +
35
- 'preferred (clang\'s "Inner Loop Header" notes count), among equals the first; branches out of the loop count as not taken (so an exit ' +
36
- 'to a label that is not in the text assembles); with addresses, the alignment offset is the loop\'s address mod 64 ' +
37
- 'unless options.alignmentOffset is given. The response\'s `loop` says what was analyzed (index, count, name, lines, ' +
38
- 'address, function, depth). `loop: "whole"` analyzes the whole text; `loop: N` the N-th loop (0-based: deepest first, ' +
39
- 'then in code order); `loop: ".LBB0_12"` a loop by its label; `func: "name"` only the loops of that function.';
29
+ 'The block: `source` (x86-64 assembly, Intel or AT&T, detected; a whole function, gcc/clang -S or objdump -d output ' +
30
+ 'is fine: its innermost loop is analyzed (the widest vector loop, else the largest); `loop` picks another: "whole", an index or a label; `func` one ' +
31
+ "function's) or `hex` (machine code).";
40
32
 
41
- const ERRORS_NOTE =
42
- 'Failures are tool errors whose JSON is {code, error, stderr}: code 1 = bad request (e.g. unknown arch, bad hex), ' +
43
- '2 = assembler error (stderr lines as llvm-mc prints them; positioned ones carry tag {line, column, severity, text}), ' +
44
- '3 = the analysis failed for this input.';
33
+ const ERRORS_NOTE = 'A failure is a tool error {code, error, stderr}: 1 bad request, 2 assembler error (positioned stderr), 3 analysis failed.';
45
34
 
46
35
  // ---- the input schemas (JSON Schema, draft-07 as before) ----------------------------------------------------------------
47
36
 
@@ -54,7 +43,7 @@ const codeShape = {
54
43
  hex: str('machine code as hex bytes, e.g. "4801d84801c349ffcf75f5" (spaces allowed)'),
55
44
  syntax: str('syntax of `source`: "auto" (default: detected from the text), "intel" (noprefix) or "att"', { enum: ['auto', 'intel', 'att'] }),
56
45
  loop: {
57
- description: 'what of `source` is analyzed: "auto" (default: the deepest loop of a whole function, else the text), "whole", the index of a loop (0-based), or its label',
46
+ description: 'what of `source` is analyzed: "auto" (default: of the deepest innermost loops, in the function of the first of them, the widest vector loop, then the most vector instructions, then the largest; else the text), "whole", the index of a loop (0-based), or its label',
58
47
  anyOf: [{ type: 'string', enum: ['auto', 'whole'] }, { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, { type: 'string', minLength: 1 }],
59
48
  },
60
49
  func: str('only the loops of this function (a label of `source`)', { minLength: 1 }),
@@ -66,17 +55,19 @@ const optionsShape = {
66
55
  description: 'simulation options of uiCA; all optional',
67
56
  type: 'object',
68
57
  properties: {
69
- alignmentOffset: int('offset of the block from a 64-byte boundary (default 0); affects the front end', 0, 63),
58
+ alignmentOffset: int('offset of the block from a 64-byte boundary (default 0; usually 0-63, other values are simulated as given); affects the front end', -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),
70
59
  initPolicy: str('initial register values: "diff" (default: all registers differ), "same", "stack"', { enum: ['diff', 'same', 'stack'] }),
71
60
  simpleFrontEnd: bool('model a front end limited only by the issue width (default false)'),
72
61
  noMicroFusion: bool('disable micro-fusion (default false)'),
73
62
  noMacroFusion: bool('disable macro-fusion (default false)'),
74
- minIterations: int('simulate at least this many iterations (default 10)', 1, 100000),
75
- minCycles: int('simulate at least this many cycles (default 500)', 1, 1000000),
63
+ minIterations: int('simulate at least this many iterations (default 10; the API server allows at most 1000)', 1, 100000),
64
+ minCycles: int('simulate at least this many cycles (default 500; the API server allows at most 20000)', 1, 1000000),
76
65
  },
77
66
  additionalProperties: false,
78
67
  };
79
68
 
69
+ const PER = { description: 'elements (bytes, floats, ...) one iteration of the loop processes: the result also gives cycles per element (`perElement`)', type: 'number', exclusiveMinimum: 0 };
70
+
80
71
  const json = (value) => ({ type: 'text', text: JSON.stringify(value, null, 1) });
81
72
  const omitBytes = ({ bytes, ...rest }) => rest;
82
73
 
@@ -88,23 +79,23 @@ export const INSTRUCTIONS =
88
79
  'wuica predicts the throughput of x86-64 basic blocks (loop bodies) with uiCA\'s cycle-level pipeline model, ' +
89
80
  'locally. Use `analyze` for one block on one microarchitecture (bottlenecks, per-port usage, full report), ' +
90
81
  '`what_if` for the effect of unrolling, an ideal front end, fusion, or removing the dependency chain, ' +
91
- '`compare_archs` to see a block on several microarchitectures, `list_archs` for the ids, `assemble` to check ' +
82
+ '`compare_archs` to see a block on several microarchitectures, `diff_blocks` for the effect of a code change ' +
83
+ '(before and after), `list_loops` for the loops of a text, `list_archs` for the ids, `assemble` to check ' +
92
84
  'that assembly text is accepted and see its encoding. ' + ASSUMPTIONS;
93
85
 
94
86
  const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
95
87
  const execution = { taskSupport: 'forbidden' };
96
88
 
97
89
  // The tools: [{name, title, description, inputSchema, annotations, execution, handler(args) -> CallToolResult}]. w: a
98
- // wuica instance (createWuica) or anything with its analyze, compare, assemble, archs and summarize.
90
+ // wuica instance (createWuica) or anything with its analyze, compare, whatIf, diff, assemble, archs and summarize.
99
91
  export function mcpTools(w) {
100
92
  return [
101
93
  {
102
94
  name: 'list_archs',
103
95
  title: 'List microarchitectures',
104
96
  description:
105
- 'Lists the microarchitecture models in order of release: id (to pass as `arch`), name, release year, and ' +
106
- '`prototype` (true for the experimental models ZEN3, ADL-P and ICX of the fork jtl06/uiCA, which are less ' +
107
- 'validated than uiCA\'s Intel models). `fields` selects fields (also available: table, xedChip).',
97
+ 'The microarchitecture models in order of release: id (the `arch` of the other tools), name, year, and `prototype` ' +
98
+ '(ZEN3, ADL-P, ICX: experimental models of the fork jtl06/uiCA). `fields` selects (also table, xedChip).',
108
99
  inputSchema: obj({
109
100
  fields: { description: 'fields to return (default: id, name, year, prototype)', type: 'array', items: { type: 'string', enum: ['id', 'name', 'year', 'prototype', 'table', 'xedChip'] } },
110
101
  }),
@@ -115,39 +106,22 @@ export function mcpTools(w) {
115
106
  name: 'analyze',
116
107
  title: 'Predict basic-block throughput (uiCA)',
117
108
  description:
118
- 'Simulates an x86-64 basic block on one microarchitecture with uiCA\'s pipeline model and returns the predicted ' +
119
- 'throughput, the bottleneck(s), the per-component limits and a per-instruction table. ' + INPUT_NOTE + ' ' +
120
- ASSUMPTIONS + '\n\nResult (JSON, format "json" or "both"): `tp` = cycles per iteration; `mode` = "loop" or ' +
121
- '"unroll"; `bottlenecks` = the components that limit the throughput (e.g. Dependencies = a loop-carried ' +
122
- 'dependency chain, Ports = execution-port pressure, Issue/Decoder/Predecoder/DSB/LSD = front end); `limits` = ' +
123
- 'the throughput that would be achieved if that component were the only bottleneck (the largest is the binding ' +
124
- 'one); `instructions[]` = per instruction: average uops per iteration issued/executed, `ports` = uops per ' +
125
- 'iteration on each execution port, `uopSource` = where the uops came from (MITE legacy decoders, DSB uop cache, ' +
126
- 'LSD loop buffer, MS microcode sequencer), `notes` M = macro-fused with the previous instruction, J = not ' +
127
- 'cacheable in the DSB because of the JCC erratum, X = instruction not supported by the model (no data: the ' +
128
- 'result is unreliable); `stderr` = assembler warnings and decode warnings (`decodeErrors` > 0: some bytes could ' +
129
- 'not be decoded); `insights` = a derived diagnosis: `utilization` (each limit and execution port as a fraction ' +
130
- 'of tp; 1 = saturated), `binding` (the limiting component: the same as `bottlenecks`; [] when uiCA names none, then ' +
131
- '`largest` is the largest limit, the nearest bound, which alone does not reach tp), `next` (the next limit and `maxSpeedup`, an upper ' +
132
- 'bound of the speedup if the binding component were removed), `unexplained` (cycles no single limit explains), ' +
133
- '`chain` (the loop-carried critical dependency chain: `index` into `instructions`, operand, latency, carried ' +
134
- 'into the next iteration), `hot` (the instructions with the largest share of the binding resource: fix these ' +
135
- 'first), `caveats` (known blind spots of the model the block meets, not simulated: rmw-index = a read-modify-write ' +
136
- 'to an indexed address, whose store forwarding between iterations depends on the data; exit = an exit before the ' +
137
- 'loop\'s branch, whose mispredict is not modelled; split = loads at an offset that is not a multiple of their width, ' +
138
- 'which may cross a cache line (on ZEN3, ADL-P and ICX, whose models charge crossings, only loads whose address register ' +
139
- 'is written other than by adding an immediate); `instructions` = indexes into `instructions`). With `details: true`, each instruction also has `allowedPorts` (uops.info notation, e.g. 1*p0156+1*p23), ' +
140
- '`uops`, `fusedUops`, `latencies` ("input->output:cycles"), `frontEnd` (length, offset = alignment offset + position in the block, crosses ' +
141
- '16/32/64-byte boundaries, lcp = length-changing prefix, microcoded, macro-fusion), and `insights` has `portSet` (the ' +
142
- 'ports behind the Ports limit and the instructions whose uops can only use them) and `issueSlots` (issue slots per ' +
143
- 'iteration: issued, or lost to the front end, a full reorder buffer (rob) or scheduler (rs), other). ' +
144
- 'Format "text" (or the second item of "both") is uiCA\'s complete text report. ' + ERRORS_NOTE,
109
+ 'One x86-64 block on one microarchitecture with uiCA\'s pipeline model. ' + INPUT_NOTE + ' ' + ASSUMPTIONS +
110
+ '\n\nResult (format "json"): `tp` (cycles per iteration), `mode` (loop or unroll), `bottlenecks` (Dependencies = a ' +
111
+ 'loop-carried chain, Ports, Issue, Decoder, Predecoder, DSB, LSD), `limits` (the tp each component alone would allow), ' +
112
+ '`loop` (what was analyzed) and `otherLoops`, `instructions[]` (per instruction: uops issued and executed per iteration, ' +
113
+ '`ports`, `uopSource` MITE/DSB/LSD/MS, `notes` M macro-fused, J JCC erratum, X not modelled; `line`, and `loc`, ' +
114
+ '`source`, `samples` when the input has them), `stderr`, and `insights`: `utilization` (each limit and port as a ' +
115
+ 'fraction of tp), `binding`, `largest` (when uiCA names no bottleneck), `next` (the next limit, `maxSpeedup`), `chain` ' +
116
+ '(the critical dependency chain), `hot` (the instructions to fix first), `caveats` (what the model does not simulate: ' +
117
+ 'rmw-index, exit, split, paths). `details: true` adds per instruction allowed ports, latencies and front-end facts, ' +
118
+ 'and the issue slots. Format "text" is uiCA\'s report; "both" (default) gives both. ' + ERRORS_NOTE,
145
119
  inputSchema: obj({
146
120
  arch: str('microarchitecture id (default "SKL"); see list_archs, e.g. SKL, ICL, TGL, RKL, ADL-P, ZEN3'),
147
121
  ...codeShape,
148
122
  options: optionsShape,
149
123
  format: str('"json" (summary), "text" (uiCA\'s report) or "both" (default)', { enum: ['json', 'text', 'both'] }),
150
- details: bool('true: per instruction also its allowed ports, latencies and front-end facts, and in insights the port set behind the Ports limit and the issue slots per cause (a slower analysis; default false)'),
124
+ details: bool('true: per instruction also its allowed ports, latencies and front-end facts, and the issue slots (slower; default false)'),
151
125
  }),
152
126
  annotations: readOnly, execution,
153
127
  handler: async ({ arch, format, details, ...request }) => {
@@ -163,52 +137,83 @@ export function mcpTools(w) {
163
137
  name: 'what_if',
164
138
  title: 'What-if experiments on a basic block',
165
139
  description:
166
- 'Re-analyzes an x86-64 basic block with one change each and reports the predicted throughput per ORIGINAL ' +
167
- 'iteration, the change `delta` (cycles; negative = faster) and `speedup` (base tp / variant tp) against the base: ' +
168
- 'unroll2/unroll4/unroll8 (n copies of the loop body and its branch once; registers are not renamed, so the ' +
169
- 'dependencies stay and only the loop overhead goes; loops only), acc2/acc3/acc4/acc8 (N accumulators: unrolled ×N ' +
170
- 'with the register of the loop-carried chain renamed into a free register in each copy, so the copies form N ' +
171
- 'independent chains, as N accumulators or N CRC streams written by hand; `renamed` says which registers; the ' +
172
- 'result\'s `accumulators.best` is the smallest N within 1% of the fastest, 1 = as it is: call it per arch for the ' +
173
- 'best N per CPU; not possible when the chain goes through memory or flags or an implicit operand), simpleFrontEnd (a front end limited only by the ' +
174
- 'issue width), noMacroFusion / noMicroFusion (switched; if the base already has the option set, the variant ' +
175
- 'switches it back), nochain (no analysis: the largest limit other than Dependencies, an estimate of the ' +
176
- 'throughput without the loop-carried chain; `estimate: true`). A variant that cannot be made or analyzed has ' +
177
- '`error`. Use it to decide whether unrolling, breaking the chain or front-end work is worth it. ' + INPUT_NOTE + ' ' +
178
- ASSUMPTIONS + ' ' + ERRORS_NOTE,
140
+ 'Re-analyzes a block with one change each; per variant `tp` per ORIGINAL iteration, `delta` (negative = faster), ' +
141
+ '`speedup`, or `error`: unroll2/4/8 (the body n times, the branch once), acc2/3/4/8 (unrolled with the chain\'s ' +
142
+ 'register renamed in each copy: N independent accumulators; `accumulators.best` = the smallest N within 1% of the ' +
143
+ 'fastest), simpleFrontEnd, noMacroFusion, noMicroFusion, nochain (an estimate without the loop-carried chain). Only ' +
144
+ 'when asked for: align (the 64 alignment offsets, 64 analyses: `tp` the median, `alignment` min, median, max, best, ' +
145
+ 'worst, spread). `per`: also cycles per element. ' + INPUT_NOTE + ' ' + ERRORS_NOTE,
179
146
  inputSchema: obj({
180
147
  arch: str('microarchitecture id (default "SKL"); see list_archs'),
181
148
  ...codeShape,
182
149
  options: optionsShape,
183
- variants: { description: `the experiments (default: all of ${VARIANTS.join(', ')})`, type: 'array', items: { type: 'string', enum: [...VARIANTS] } },
150
+ variants: { description: `the experiments (default: ${VARIANTS.join(', ')}; also align)`, type: 'array', items: { type: 'string', enum: [...VARIANTS, ...OPT_IN_VARIANTS] } },
151
+ per: PER,
184
152
  }),
185
153
  annotations: readOnly, execution,
186
- handler: async ({ arch, variants, ...request }) => result(await whatIf((a, req) => w.analyze(a, req), arch ?? 'SKL', request, variants ?? VARIANTS, { assemble: (text) => w.assemble(text, 'intel') })),
154
+ handler: async ({ arch, ...request }) => result(await (w.whatIf ? w.whatIf(arch ?? 'SKL', request) : whatIfRequest(w, arch ?? 'SKL', request))),
155
+ },
156
+ {
157
+ name: 'diff_blocks',
158
+ title: 'Compare two versions of a block',
159
+ description:
160
+ 'Two blocks, A (before) and B (after), on one microarchitecture, in one result: `a` and `b` (tp, bottlenecks, ' +
161
+ 'decodeErrors), `delta` (B - A), `speedup` (A / B), `verdict`, `perElement` (with `per`), `bottlenecks` (gone, new), ' +
162
+ '`limits` and `ports` (uops per iteration) before and after, and `instructions` (the ones changed, added or removed, ' +
163
+ 'with the change of their uops). Each block as analyze takes it; `options` apply to both unless a block has its own. ' +
164
+ 'A loop against a block without a branch is not comparable. A failure of one block starts with "A: " or "B: ".',
165
+ inputSchema: obj({
166
+ arch: str('microarchitecture id (default "SKL"); see list_archs'),
167
+ a: { description: 'block A (before)', type: 'object', properties: { ...codeShape, options: optionsShape }, additionalProperties: false },
168
+ b: { description: 'block B (after)', type: 'object', properties: { ...codeShape, options: optionsShape }, additionalProperties: false },
169
+ options: optionsShape,
170
+ per: {
171
+ description: 'elements per iteration: a number for both, or [A, B] (e.g. [8, 32] after unrolling ×4): also cycles per element',
172
+ anyOf: [{ type: 'number', exclusiveMinimum: 0 }, { type: 'array', items: { type: 'number', exclusiveMinimum: 0 }, minItems: 2, maxItems: 2 }],
173
+ },
174
+ }, ['a', 'b']),
175
+ annotations: readOnly, execution,
176
+ handler: async ({ arch, ...request }) => result(await (w.diff ? w.diff(arch ?? 'SKL', request) : diffRequest(w, arch ?? 'SKL', request))),
187
177
  },
188
178
  {
189
179
  name: 'compare_archs',
190
180
  title: 'Compare a block across microarchitectures',
191
181
  description:
192
- 'Predicts the throughput of one x86-64 basic block on several microarchitectures (default: all) and returns, per ' +
193
- 'microarchitecture, `tp` in cycles per iteration and the bottleneck(s) (a row with code != 0 failed on that ' +
194
- 'microarchitecture). Use it to see how a loop behaves on older vs. newer Intel cores or on AMD Zen 3. ' +
195
- INPUT_NOTE + ' ' + ASSUMPTIONS + ' ' + ERRORS_NOTE,
182
+ 'One block on several microarchitectures (default: all): per microarchitecture `tp` and `bottlenecks` (a row with ' +
183
+ 'code != 0 failed there); `per`: also cycles per element. ' + INPUT_NOTE + ' ' + ERRORS_NOTE,
196
184
  inputSchema: obj({
197
185
  ...codeShape,
198
186
  archs: { description: 'microarchitecture ids to compare (default: all of list_archs)', type: 'array', items: { type: 'string' } },
199
187
  options: optionsShape,
188
+ per: PER,
200
189
  }),
201
190
  annotations: readOnly, execution,
202
191
  handler: async (request) => result(await w.compare(request)),
203
192
  },
193
+ {
194
+ name: 'list_loops',
195
+ title: 'List the loops of assembly text',
196
+ description:
197
+ 'The loops of assembly text (a function or file; gcc/clang -S, objdump -d, perf annotate) without analyzing it: ' +
198
+ '`index` and `label` (what analyze\'s `loop` takes), `function`, `line`, `endLine`, `instructions`, `depth` (1 = ' +
199
+ 'outermost), `auto` (the one analyze picks by default). `func` keeps one function\'s loops.',
200
+ inputSchema: obj({
201
+ source: str('the assembly text'),
202
+ func: codeShape.func,
203
+ }, ['source']),
204
+ annotations: readOnly, execution,
205
+ handler: async ({ source, func }) => {
206
+ const ls = listLoops(source, { func: func ?? null });
207
+ if (!Array.isArray(ls)) return result({ code: 1, error: ls.error, stderr: [{ text: ls.error }] });
208
+ return result({ code: 0, loops: ls, ...(ls.length ? {} : { note: loopsNote(source) }) });
209
+ },
210
+ },
204
211
  {
205
212
  name: 'assemble',
206
213
  title: 'Assemble x86-64 code',
207
214
  description:
208
- 'Assembles x86-64 assembly text with LLVM\'s assembler (LLVM 22, the same bytes as llvm-mc) and returns ' +
209
- '{code: 0, hex, length, stderr} (stderr: warnings), or the assembler\'s errors as {code: 2, error, stderr} with ' +
210
- 'line/column tags. The syntax is detected unless given (Intel noprefix or AT&T); the text may switch with .intel_syntax noprefix / ' +
211
- '.att_syntax. Only .text is returned.',
215
+ 'Assembles x86-64 text with LLVM\'s assembler (LLVM 22, the bytes of llvm-mc): {code: 0, hex, length, stderr}, or ' +
216
+ '{code: 2, error, stderr} with line/column tags. The syntax is detected unless given. Only .text is returned.',
212
217
  inputSchema: obj({
213
218
  source: { description: 'the assembly text', type: 'string' },
214
219
  syntax: codeShape.syntax,
@@ -219,22 +224,37 @@ export function mcpTools(w) {
219
224
  ];
220
225
  }
221
226
 
227
+ // Why a text has no loops to list: a marked region (analyze takes the region, not a loop), or no backward branch.
228
+ function loopsNote(source) {
229
+ if (/^\s*(?:#|\/\/|;)\s*(?:LLVM-MCA-BEGIN|wuica-begin)(?![\w-])/im.test(source) || /^\s*mov[l]?\s+(?:ebx\s*,\s*111|\$111\s*,\s*%ebx)\s*$/im.test(source)) {
230
+ return 'the text has a marked region (LLVM-MCA-BEGIN, wuica-begin or IACA markers): analyze takes the region, not a loop';
231
+ }
232
+ return 'no backward branch to a label of the text: analyze takes the whole text (or a function\'s body)';
233
+ }
234
+
222
235
  // The tool as tools/list shows it (without the handler).
223
236
  export const toolListing = ({ handler, ...t }) => t;
224
237
 
225
238
  // ---- a validator for the keywords these schemas use ------------------------------------------------------------------------
226
239
  // type (object, array, string, integer, number, boolean), properties, required, additionalProperties: false, enum, items,
227
- // minimum, maximum, minLength, anyOf. Returns the first problem as text ("options.minIterations: expected an integer,
240
+ // minimum, maximum, exclusiveMinimum, minLength, minItems, maxItems, anyOf. Returns the first problem as text ("options.minIterations: expected an integer,
228
241
  // got \"many\""), or null.
229
242
  const kind = (v) => (v === null ? 'null' : Array.isArray(v) ? 'an array' : typeof v === 'object' ? 'an object' : typeof v === 'string' ? 'a string' : typeof v === 'boolean' ? 'a boolean' : typeof v === 'number' ? (Number.isInteger(v) ? 'an integer' : 'a number') : typeof v);
230
243
  const show = (v) => JSON.stringify(v)?.slice(0, 60) ?? String(v);
244
+ // what a schema of anyOf allows, in words: "an integer >= 0", "a non-empty string", "an array of 2 numbers > 0"
245
+ function describe(s, plural = false) {
246
+ if (s.enum) return s.enum.map((x) => JSON.stringify(x)).join(' or ');
247
+ const noun = s.type === 'string' && s.minLength ? 'non-empty string' : s.type === 'array' ? 'array' : String(s.type);
248
+ const bounds = `${s.minimum !== undefined ? ` >= ${s.minimum}` : ''}${s.exclusiveMinimum !== undefined ? ` > ${s.exclusiveMinimum}` : ''}`;
249
+ const of = s.type === 'array' && s.items ? ` of ${s.minItems !== undefined && s.minItems === s.maxItems ? `${s.minItems} ` : ''}${describe(s.items, true)}` : '';
250
+ return `${plural ? `${noun}s` : `${/^[aeiou]/.test(noun) ? 'an' : 'a'} ${noun}`}${of}${bounds}`;
251
+ }
231
252
  export function validate(schema, value, at = '') {
232
253
  const where = at || 'arguments';
233
254
  if (schema.anyOf) {
234
255
  const errs = schema.anyOf.map((s) => validate(s, value, at));
235
256
  if (errs.some((e) => e === null)) return null;
236
- const allowed = schema.anyOf.map((s) => (s.enum ? s.enum.map((x) => JSON.stringify(x)).join(' or ') : s.type === 'integer' ? `an integer${s.minimum !== undefined ? ` >= ${s.minimum}` : ''}` : s.minLength ? 'a non-empty string' : `a ${s.type}`));
237
- return `${where}: expected ${allowed.join(', or ')}, got ${show(value)}`;
257
+ return `${where}: expected ${schema.anyOf.map((s) => describe(s)).join(', or ')}, got ${show(value)}`;
238
258
  }
239
259
  switch (schema.type) {
240
260
  case 'object': {
@@ -254,6 +274,8 @@ export function validate(schema, value, at = '') {
254
274
  }
255
275
  case 'array': {
256
276
  if (!Array.isArray(value)) return `${where}: expected an array, got ${kind(value)}`;
277
+ if (schema.minItems !== undefined && value.length < schema.minItems) return `${where}: expected at least ${schema.minItems} items, got ${value.length}`;
278
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) return `${where}: expected at most ${schema.maxItems} items, got ${value.length}`;
257
279
  for (let i = 0; i < value.length; i++) { const e = schema.items ? validate(schema.items, value[i], `${where}[${i}]`) : null; if (e) return e; }
258
280
  return null;
259
281
  }
@@ -276,6 +298,7 @@ export function validate(schema, value, at = '') {
276
298
  if (schema.enum && !schema.enum.includes(value)) return `${where}: expected one of ${schema.enum.map((x) => JSON.stringify(x)).join(', ')}, got ${show(value)}`;
277
299
  if (schema.minimum !== undefined && value < schema.minimum) return `${where}: expected at least ${schema.minimum}, got ${value}`;
278
300
  if (schema.maximum !== undefined && value > schema.maximum) return `${where}: expected at most ${schema.maximum}, got ${value}`;
301
+ if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) return `${where}: expected more than ${schema.exclusiveMinimum}, got ${value}`;
279
302
  return null;
280
303
  }
281
304
 
package/lib/objfile.js CHANGED
@@ -23,23 +23,52 @@ export function objectKind(b) {
23
23
 
24
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
25
 
26
- // The code of an object file: {format, functions: [{name, section, address, size, bytes}]} or {error}.
26
+ // The code of an object file: {format, functions: [{name, section, address, size, bytes[, symbol]}]} or {error}.
27
+ // Names are unique (uniqueNames): a function whose symbol name occurs more than once has its address in its name, and
28
+ // `symbol` is the name in the file.
29
+ /** @returns {any} */
27
30
  export function readObject(bytes) {
28
31
  const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
29
32
  const k = objectKind(b);
30
33
  if (!k) return { error: 'not an object file' };
31
34
  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)` };
35
+ const r = readContainer(b, k);
36
+ if (r.functions) uniqueNames(r.functions);
37
+ return r;
38
38
  } catch (e) {
39
39
  return { error: `a damaged or truncated object file (${e.message})` };
40
40
  }
41
41
  }
42
42
 
43
+ // A static executable (or a relocatable object made by ld -r) has local symbols with the same name: static functions of
44
+ // different translation units, their .cold parts, glibc's helpers. In llvm-objdump -d's text each function's header
45
+ // ("0000000000401000 <step>:") becomes a label, and a label defined twice fails to assemble. So every function whose
46
+ // name occurs more than once is named NAME.0xADDR (its address; a plain label as loop-find.js reads one), all of them:
47
+ // none is the NAME of a -func, which says that NAME is ambiguous (resolveFunction). A file without repeated names keeps
48
+ // its names: its text is llvm-objdump's, as before.
49
+ function uniqueNames(functions) {
50
+ const count = new Map();
51
+ for (const f of functions) count.set(f.name, (count.get(f.name) ?? 0) + 1);
52
+ const taken = new Set(functions.map((f) => f.name));
53
+ for (const f of functions) {
54
+ if (count.get(f.name) === 1) continue;
55
+ let name = `${f.name}.0x${f.address.toString(16)}`;
56
+ for (let k = 2; taken.has(name); k++) name = `${f.name}.0x${f.address.toString(16)}.${k}`; // (a symbol of that name too)
57
+ taken.add(name);
58
+ f.symbol = f.name;
59
+ f.name = name;
60
+ }
61
+ }
62
+
63
+ function readContainer(b, k) {
64
+ if (k.kind === 'elf') return readElf(b);
65
+ if (k.kind === 'macho') return readMachO(b);
66
+ if (k.kind === 'fat') return readFat(b);
67
+ if (k.kind === 'macho32') return { error: `a 32-bit Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
68
+ if (k.kind === 'archive') return { error: 'an archive (.a): extract an object from it (ar x lib.a foo.o) and give that' };
69
+ 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)` };
70
+ }
71
+
43
72
  function view(b) { return new DataView(b.buffer, b.byteOffset, b.byteLength); }
44
73
  const u64 = (dv, o) => Number(dv.getBigUint64(o, true));
45
74
  const cstr = (b, o) => { let e = o; while (e < b.length && b[e] !== 0) e++; return td.decode(b.subarray(o, e)); };
@@ -122,7 +151,7 @@ function readFat(b) {
122
151
  }
123
152
  const x = archs.find((a) => a.cpu === MACHO_X86_64);
124
153
  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);
154
+ return readMachO(b.subarray(x.offset, x.offset + x.size));
126
155
  }
127
156
 
128
157
  const cpuName = (c) => (c === MACHO_ARM64 ? 'arm64' : c === MACHO_X86_64 ? 'x86_64' : c === MACHO_I386 ? 'i386' : `cpu ${c}`);
@@ -132,6 +161,7 @@ function readMachO(b) {
132
161
  const cpu = dv.getUint32(4, true), filetype = dv.getUint32(12, true), ncmds = dv.getUint32(16, true);
133
162
  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
163
  const sects = [];
164
+ /** @type {{symoff: number, nsyms: number, stroff: number} | null} */
135
165
  let symtab = null;
136
166
  let o = 32;
137
167
  for (let i = 0; i < ncmds; i++) {
@@ -203,14 +233,24 @@ export function objdumpText(obj, decode, name = 'input') {
203
233
  }
204
234
 
205
235
  // 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).
236
+ // unique part of a name. {name} or {error} (the candidates when ambiguous, the functions when none matches). A name the
237
+ // file gives to several functions (uniqueNames: NAME.0xADDR) is ambiguous: the error lists them with their addresses.
207
238
  export function resolveFunction(functions, func) {
208
239
  const names = [...new Set(functions.map((f) => f.name))];
209
240
  if (names.includes(func)) return { name: func };
241
+ for (const symbol of [func, `_${func}`]) {
242
+ const same = functions.filter((f) => f.symbol === symbol);
243
+ if (!same.length) continue;
244
+ const shown = same.slice(0, 10).map((f) => `0x${f.address.toString(16)}`);
245
+ const at = `${shown.slice(0, -1).join(', ')}${same.length > 2 ? ',' : ''} and ${shown[shown.length - 1]}${same.length > 10 ? ` (and ${same.length - 10} more: -funcs lists them)` : ''}`;
246
+ return { error: `func: ${JSON.stringify(func)} names ${same.length} functions of the file, at ${at} (static functions of different source files, or parts of one): give it with its address, -func ${same[0].name}${same.length === 2 ? ` or -func ${same[1].name}` : ''}` };
247
+ }
210
248
  const under = names.filter((n) => n === `_${func}`);
211
249
  if (under.length === 1) return { name: under[0] };
212
250
  const part = names.filter((n) => n.includes(func));
213
251
  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'})` };
252
+ // (a static executable has thousands of functions: a long list is left to -funcs)
253
+ const list = (xs) => (xs.length <= 20 ? xs.join(', ') : `${xs.slice(0, 20).join(', ')}, and ${xs.length - 20} more: -funcs lists them`);
254
+ if (part.length > 1) return { error: `func: ${JSON.stringify(func)} is part of ${part.length} function names (${list(part)}): give one of them` };
255
+ return { error: `func: ${JSON.stringify(func)} is not a function of the file (functions: ${list(names) || 'none'})` };
216
256
  }
@@ -17,33 +17,36 @@ import { Analyzer } from './wasm.js';
17
17
  import { readMaybeCompressed, readMaybeCompressedSync, tableFile } from './files.js';
18
18
  import { analysisResult, compareFields } from './core.js';
19
19
 
20
+ if (!parentPort) throw new Error('thread-worker.js runs as a worker thread');
21
+ const port = parentPort;
20
22
  const { module, uarch, dataDir, recycleBytes } = workerData;
23
+ /** @type {Analyzer | null} */
21
24
  let analyzer = null;
22
25
  try {
23
26
  analyzer = new Analyzer(module);
24
27
  analyzer.loadUarch(uarch);
25
28
  } catch (e) {
26
- parentPort.postMessage({ type: 'init-error', message: String(e?.message ?? e) });
29
+ port.postMessage({ type: 'init-error', message: String(e?.message ?? e) });
27
30
  }
28
31
 
29
32
  if (analyzer) {
30
- parentPort.on('message', async ({ id, table, request, full }) => {
33
+ port.on('message', async ({ id, table, request, full }) => {
31
34
  if (!analyzer.hasArch(table)) {
32
35
  try {
33
36
  const file = tableFile(dataDir, table);
34
37
  analyzer.loadArch(table, await readMaybeCompressed(file), () => readMaybeCompressedSync(file));
35
38
  } catch {
36
- parentPort.postMessage({ id, fields: null, recycle: analyzer.memoryBytes === 0 }); // 0: the module trapped
39
+ port.postMessage({ id, fields: null, recycle: analyzer.memoryBytes === 0 }); // 0: the module trapped
37
40
  return;
38
41
  }
39
42
  }
40
43
  const response = analyzer.analyze(request);
41
44
  if (response.trapped || analyzer.memoryBytes === 0) { // trapped, or could not be restarted after an earlier trap
42
- parentPort.postMessage({ id, fields: null, recycle: true });
45
+ port.postMessage({ id, fields: null, recycle: true });
43
46
  return;
44
47
  }
45
48
  const result = analysisResult(response);
46
- parentPort.postMessage({ id, fields: full ? result : compareFields(result), recycle: analyzer.memoryBytes > recycleBytes });
49
+ port.postMessage({ id, fields: full ? result : compareFields(result), recycle: analyzer.memoryBytes > recycleBytes });
47
50
  });
48
- parentPort.postMessage({ type: 'ready' });
51
+ port.postMessage({ type: 'ready' });
49
52
  }
package/lib/threads.js CHANGED
@@ -74,15 +74,20 @@ export function threadsForWork(jobs, limit, cores = os.availableParallelism()) {
74
74
  }
75
75
 
76
76
  export class ThreadPool {
77
+ /** @type {any} */
77
78
  #workerData = null;
78
79
  #wasm; #uarch; #dataDir;
80
+ /** @type {Promise<WebAssembly.Module> | null} */
79
81
  #compiled = null; // promise of the module with the threads' memory limit
80
82
  #limit;
83
+ /** @type {any[]} */
81
84
  #slots = []; // {worker, ready, job, tables: Set}
82
85
  #warmed = false;
83
86
  #want; // the threads the latest run() may start
87
+ /** @type {any[]} */
84
88
  #queue = []; // {id, table, request, resolve}
85
89
  #nextId = 1;
90
+ /** @type {ReturnType<typeof setTimeout> | null} */
86
91
  #idleTimer = null;
87
92
  broken = false;
88
93
 
@@ -100,7 +105,7 @@ export class ThreadPool {
100
105
  // than `threads` (and `limit`) and jobs wait.
101
106
  async run(jobs, threads = this.#limit) {
102
107
  this.#want = Math.min(this.#limit, threads);
103
- clearTimeout(this.#idleTimer);
108
+ clearTimeout(this.#idleTimer ?? undefined);
104
109
  this.#idleTimer = null;
105
110
  if (!this.#workerData) {
106
111
  const maxBytes = maxMemoryBytes(this.#limit);
@@ -173,6 +178,7 @@ export class ThreadPool {
173
178
 
174
179
  #spawn(job) {
175
180
  const worker = new Worker(WORKER, { workerData: this.#workerData, stdout: true, stderr: true });
181
+ /** @type {{worker: Worker, ready: boolean, job: any, tables: Set<string>}} */
176
182
  const slot = { worker, ready: false, job: null, tables: new Set() };
177
183
  this.#slots.push(slot);
178
184
  this.#start(slot, job);
@@ -222,7 +228,7 @@ export class ThreadPool {
222
228
 
223
229
  // Stops the threads; waiting and running jobs resolve to null. The next run() starts new ones.
224
230
  async close() {
225
- clearTimeout(this.#idleTimer);
231
+ clearTimeout(this.#idleTimer ?? undefined);
226
232
  this.#idleTimer = null;
227
233
  const slots = this.#slots.splice(0);
228
234
  for (const j of this.#queue.splice(0)) j.resolve(null);
package/lib/wasm.js CHANGED
@@ -9,8 +9,11 @@ const enc = new TextEncoder();
9
9
  const dec = new TextDecoder();
10
10
 
11
11
  export class Analyzer {
12
+ /** @type {any} */
12
13
  #module;
14
+ /** @type {any} */
13
15
  #x = null;
16
+ /** @type {Uint8Array | Buffer | null} */
14
17
  #uarch = null; // bytes of uarch.json, kept to reload after a trap
15
18
  #tables = new Map(); // table name -> its bytes, or a function that reads them again (for a reload after a trap)
16
19
  #binary = false; // the module reads binary tables (wuica_load_arch_bin)
@@ -68,6 +71,7 @@ export class Analyzer {
68
71
 
69
72
  // bytes: the binary form of the table (data/arch/<name>.bin, see crates/wuica-core/src/table_bin.rs) or its JSON.
70
73
  // reload: a function that returns the bytes again (then they are not kept: they are only needed after a trap)
74
+ /** @param {string} name @param {Uint8Array} bytes @param {(() => Uint8Array) | null} [reload] */
71
75
  loadArch(name, bytes, reload = null) {
72
76
  this.#live();
73
77
  this.#loadTable(name, bytes);
@@ -190,16 +194,18 @@ export function codeModeError(text) {
190
194
  return null;
191
195
  }
192
196
 
193
- // GNU as's {load}/{store} pseudo-prefixes at the start of a line, which LLVM's assembler rejects.
194
- export function stripHints(text) {
195
- return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1');
196
- }
197
+ // The text as the assembler module gets it (a NUL as a space, {load}/{store}, clang 23's .prefalign, ...): one
198
+ // preparation, web/js/assembler.js prepareSource, shared with the page
199
+ export { stripHints, prepareSource } from './web/assembler.js';
200
+ import { prepareSource } from './web/assembler.js';
197
201
 
198
202
  const OUT_CAP = 1 << 20;
199
203
  const ERR_CAP = 1 << 16;
200
204
 
201
205
  export class Assembler {
206
+ /** @type {any} */
202
207
  #module;
208
+ /** @type {any} */
203
209
  #x = null;
204
210
 
205
211
  constructor(module) {
@@ -212,7 +218,7 @@ export class Assembler {
212
218
 
213
219
  #live() {
214
220
  if (this.#x) return;
215
- const x = new WebAssembly.Instance(this.#module, {}).exports;
221
+ const x = /** @type {any} */ (new WebAssembly.Instance(this.#module, {}).exports);
216
222
  x._initialize?.();
217
223
  this.#x = x;
218
224
  }
@@ -221,7 +227,7 @@ export class Assembler {
221
227
  assemble(text, syntax) {
222
228
  this.#live();
223
229
  const x = this.#x;
224
- const src = enc.encode(stripHints(text) + '\0');
230
+ const src = enc.encode(prepareSource(text) + '\0');
225
231
  let textPtr = 0, outPtr = 0, errPtr = 0;
226
232
  try {
227
233
  textPtr = x.malloc(src.length); outPtr = x.malloc(OUT_CAP); errPtr = x.malloc(ERR_CAP);