wuica-cli 0.1.7 → 0.1.10
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/README.md +233 -57
- 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 +145 -66
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +205 -13
- package/lib/cli.js +467 -49
- package/lib/core.js +9 -1
- package/lib/details.js +4 -23
- package/lib/examples.js +27 -0
- package/lib/files.js +26 -3
- package/lib/index.js +228 -42
- package/lib/mcp.js +107 -84
- package/lib/objfile.js +218 -0
- package/lib/thread-worker.js +15 -9
- package/lib/threads.js +40 -23
- package/lib/wasm.js +42 -11
- package/lib/web/ab-diff.js +217 -0
- package/lib/web/accum.js +10 -2
- package/lib/web/asm-regions.js +24 -17
- package/lib/web/asm-tokens.js +357 -0
- package/lib/web/assembler.js +36 -6
- package/lib/web/block-diff.js +165 -0
- package/lib/web/bound-core.js +211 -0
- package/lib/web/branch-label.js +155 -0
- package/lib/web/caveats.js +115 -3
- package/lib/web/details.js +91 -0
- package/lib/web/examples.js +103 -0
- package/lib/web/loop-find.js +139 -16
- package/lib/web/markdown.js +437 -0
- package/lib/web/showcase.js +368 -0
- package/lib/web/whatif-core.js +339 -0
- package/package.json +3 -1
- package/dist/data/arch/ADL-P.json.br +0 -0
- package/dist/data/arch/BDW.json.br +0 -0
- package/dist/data/arch/CFL.json.br +0 -0
- package/dist/data/arch/CLX.json.br +0 -0
- package/dist/data/arch/HSW.json.br +0 -0
- package/dist/data/arch/ICL.json.br +0 -0
- package/dist/data/arch/ICX.json.br +0 -0
- package/dist/data/arch/IVB.json.br +0 -0
- package/dist/data/arch/KBL.json.br +0 -0
- package/dist/data/arch/RKL.json.br +0 -0
- package/dist/data/arch/SKL.json.br +0 -0
- package/dist/data/arch/SKX.json.br +0 -0
- package/dist/data/arch/SNB.json.br +0 -0
- package/dist/data/arch/TGL.json.br +0 -0
- package/dist/data/arch/ZEN3.json.br +0 -0
- package/lib/insights.js +0 -100
- package/lib/whatif.js +0 -136
package/lib/web/asm-regions.js
CHANGED
|
@@ -42,6 +42,11 @@ const sectionName = (args) => (/^\s*("?)([^",\s]+)\1/.exec(args)?.[2] ?? '');
|
|
|
42
42
|
// opts (loop-find.js, preparePaste): pick {begin, end}: lines (1-based) of the code to analyze when nothing is marked (the
|
|
43
43
|
// loop: its first instruction at or after `begin` to the end of line `end`); stubs: symbols to define right after the
|
|
44
44
|
// analyzed code (the loop's exits: its conditional branches out of it are then short and not taken).
|
|
45
|
+
/**
|
|
46
|
+
* @param {string} text
|
|
47
|
+
* @param {{pick?: {begin: number, end: number} | null, stubs?: string[]}} [opts]
|
|
48
|
+
* @returns {any}
|
|
49
|
+
*/
|
|
45
50
|
export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
46
51
|
text = String(text ?? '');
|
|
47
52
|
if (!QUICK.test(text) && !pick && !stubs.length) return null;
|
|
@@ -49,10 +54,15 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
49
54
|
const labels = [];
|
|
50
55
|
const inserts = []; // {line, col, label}
|
|
51
56
|
const regions = [];
|
|
52
|
-
|
|
53
|
-
|
|
57
|
+
/** @type {any} */
|
|
58
|
+
let region = null;
|
|
59
|
+
let pendingBegin = false;
|
|
60
|
+
/** @type {{line: number, message: string} | null} */
|
|
61
|
+
let error = null;
|
|
62
|
+
const locs = [], files = new Map();
|
|
54
63
|
let inText = true, prev = false;
|
|
55
64
|
const stack = [];
|
|
65
|
+
/** @type {any} */
|
|
56
66
|
let iaca = null; // {kind: '111' | '222', line, col} of a mov that can be an IACA marker
|
|
57
67
|
let block = false;
|
|
58
68
|
const label = (line, col) => { const name = `.Lwuica_${labels.length}`; labels.push(name); inserts.push({ line, col, label: name }); return labels.length - 1; };
|
|
@@ -98,7 +108,7 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
98
108
|
}
|
|
99
109
|
const sts = statements(line);
|
|
100
110
|
for (const st of sts) {
|
|
101
|
-
const lead = LABELS.exec(st.text)[0].length;
|
|
111
|
+
const lead = /** @type {RegExpExecArray} */ (LABELS.exec(st.text))[0].length;
|
|
102
112
|
const body = st.text.slice(lead);
|
|
103
113
|
if (!body) continue;
|
|
104
114
|
const col = st.at + lead;
|
|
@@ -122,18 +132,11 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
122
132
|
const name = d?.[1].toLowerCase() ?? '';
|
|
123
133
|
const args = d?.[2] ?? '';
|
|
124
134
|
// an objdump line with its bytes (loop-find.js) starts the picked code like an instruction
|
|
125
|
-
if (name === 'byte' && pickPending && inText && i + 1 >= pick
|
|
135
|
+
if (name === 'byte' && pickPending && inText && i + 1 >= Number(pick?.begin)) { region.begin = label(i, col); pickPending = false; }
|
|
126
136
|
if (name === 'loc') {
|
|
127
137
|
const m = /^(\d+)\s+(\d+)/.exec(args);
|
|
128
138
|
if (m && inText) locs.push({ label: label(i, col), file: Number(m[1]), line: Number(m[2]) });
|
|
129
|
-
//
|
|
130
|
-
// (a symbol of it, which the debug sections can use, is defined as 0 in the trailer)
|
|
131
|
-
const v = /\bview\s+(\S+)/.exec(body);
|
|
132
|
-
if (v) {
|
|
133
|
-
const at = col + v.index;
|
|
134
|
-
lines[i] = lines[i].slice(0, at) + ' '.repeat(v[0].length) + lines[i].slice(at + v[0].length);
|
|
135
|
-
if (/^[A-Za-z_.$][\w.$]*$/.test(v[1])) views.add(v[1]);
|
|
136
|
-
}
|
|
139
|
+
// (the directive itself is not assembled: assembler.js withoutLineTable)
|
|
137
140
|
} else if (name === 'file') {
|
|
138
141
|
const m = /^(\d+)\s/.exec(args);
|
|
139
142
|
const q = quoted(args);
|
|
@@ -148,7 +151,7 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
148
151
|
}
|
|
149
152
|
if (/^[\w.$@]+\s*=/.test(body)) continue; // a symbol assignment
|
|
150
153
|
// an instruction
|
|
151
|
-
if (pickPending && inText && i + 1 >= pick
|
|
154
|
+
if (pickPending && inText && i + 1 >= Number(pick?.begin)) { region.begin = label(i, col); pickPending = false; }
|
|
152
155
|
// (a mov that can be an IACA marker is decided by the next statement)
|
|
153
156
|
const im = IACA_MOV.exec(body);
|
|
154
157
|
if (im) iaca = { kind: im[1] ?? im[2], line: i, col, inText };
|
|
@@ -183,9 +186,8 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
183
186
|
const lineCount = lines.length;
|
|
184
187
|
const parts = [];
|
|
185
188
|
for (let k = 0; k < labels.length; k += 32) parts.push(`.long ${labels.slice(k, k + 32).map((n) => `.Lwuica_z-${n}`).join(', ')}`);
|
|
186
|
-
const sets = [...views].map((n) => `.set ${n}, 0\n`).join('');
|
|
187
189
|
const tail = stubsPlaced ? '' : `${stubs.map((n) => `${n}:`).join('\n')}\n`; // the exits at the end of the code
|
|
188
|
-
const out = `${lines.join('\n')}\n
|
|
190
|
+
const out = `${lines.join('\n')}\n.text\n${tail}.Lwuica_z:\n.long ${MAGIC}\n${parts.join('\n')}\n`;
|
|
189
191
|
if (region) delete region.closed;
|
|
190
192
|
return { text: out, labels, regions, region, locs, files, shifts, lineCount, error };
|
|
191
193
|
}
|
|
@@ -232,7 +234,9 @@ const base = (p) => String(p).split(/[\\/]/).pop();
|
|
|
232
234
|
|
|
233
235
|
// The analyzed bytes and the source lines of a plan: {bytes, region, source} or {error}.
|
|
234
236
|
export function cutPlan(plan, code, offsets) {
|
|
235
|
-
let start = 0, end = code.length
|
|
237
|
+
let start = 0, end = code.length;
|
|
238
|
+
/** @type {any} */
|
|
239
|
+
let region = null;
|
|
236
240
|
if (plan.region) {
|
|
237
241
|
const r = plan.region;
|
|
238
242
|
if (plan.error) return { error: plan.error };
|
|
@@ -241,6 +245,7 @@ export function cutPlan(plan, code, offsets) {
|
|
|
241
245
|
if (!(end > start)) return { error: { line: r.line, message: 'the marked region has no machine code in .text' } };
|
|
242
246
|
region = r.auto ? { auto: true } : { name: r.name, line: r.line, index: 0, count: plan.regions.length };
|
|
243
247
|
}
|
|
248
|
+
/** @type {any} */
|
|
244
249
|
let source = null;
|
|
245
250
|
if (plan.locs.length) {
|
|
246
251
|
const at = plan.locs.map((l) => ({ off: offsets[l.label], file: l.file, line: l.line }))
|
|
@@ -378,7 +383,9 @@ export async function assembleMarked(assemble, text, opts = {}) {
|
|
|
378
383
|
index: prep.choice === 'body' ? null : prep.choice, count: prep.loops.length, name: loopName(prep),
|
|
379
384
|
line: prep.pick.begin, endLine: prep.pick.end, lines: prep.pick.lines, address: prep.address, alignment: prep.alignment,
|
|
380
385
|
};
|
|
381
|
-
|
|
386
|
+
// the source line of each analyzed instruction: of the pick, or of the whole text (not with a marked region)
|
|
387
|
+
const lines = prep.exactLines === false ? null : prep.pick ? prep.pick.lines : r.region ? null : prep.lines ?? null;
|
|
388
|
+
const out = { ...r, loop, loops: prep.loops, body: prep.body, choosable: prep.choosable, alignment: prep.alignment, lines, lineInfo: prep.lineInfo ?? null, profile: prep.profile ?? null };
|
|
382
389
|
if (r.ok && prep.notes.length) out.diagnostics = [...r.diagnostics, ...prep.notes];
|
|
383
390
|
return out;
|
|
384
391
|
}
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
// Assembly syntax highlighting, the DOM-free half: the tokens of a line of x86-64 assembly (Intel or AT&T syntax, gcc
|
|
2
|
+
// and clang output, objdump -d lines with or without the byte column). The page's editor overlay and any later consumer
|
|
3
|
+
// (the CLI, a report) colour them through the class names (className) so that they agree; the npm package ships a copy
|
|
4
|
+
// (packages/wuica/lib/web, web-modules.json). tests-js/web_asm_tokens.mjs tests it.
|
|
5
|
+
//
|
|
6
|
+
// tokenize(line, syntax, opts) -> [{start, end, kind}]: every character of the line in exactly one token, in order;
|
|
7
|
+
// never throws; linear in the length of the line. Kinds (a small set: the page is deliberately plain):
|
|
8
|
+
// label a label's definition ("loop:", ".LBB0_3:", "1:", objdump's "<f>:" header)
|
|
9
|
+
// mnemonic the instruction's mnemonic: the first word after the labels and prefixes (by position, not by a list;
|
|
10
|
+
// AT&T's size suffix is part of it: addq)
|
|
11
|
+
// prefix lock, rep*, notrack, bnd, data16, segment prefixes before the mnemonic, {vex}, {evex}, ...
|
|
12
|
+
// register general-purpose (64/32/16/8-bit, ah/bh/ch/dh), rip/eip, xmm/ymm/zmm, k0-k7, segment, x87 st(i)/st, mm,
|
|
13
|
+
// control and debug registers; the mask register in {k1}
|
|
14
|
+
// number immediates and displacements: 42, -8 (the sign is punct), 0x1f, 1fh, 0b101, $42 (AT&T, with its $)
|
|
15
|
+
// size dword ptr, ymmword ptr (one token), byte/word/... without ptr, offset, and the operand decorations
|
|
16
|
+
// {z}, {1to8}, {sae}, {rn-sae} (their letters; the braces are punct)
|
|
17
|
+
// symbol a label's use: a branch target, a memory operand's symbol (.LCPI0_0, printf@PLT, 1b, 1f), $sym's sym,
|
|
18
|
+
// objdump's <f+0x10> name
|
|
19
|
+
// directive .p2align, .globl, .section, ... (the operands are tokens of their own)
|
|
20
|
+
// comment # ..., // ..., /* ... */ (on the line; tokenizeText follows one over several lines), a ';' that starts
|
|
21
|
+
// the line, and a ';' after a statement when the assembly diagnostics say the rest was taken as a comment
|
|
22
|
+
// (asm-regions.js commentFixes: the assembler's rule; without diagnostics a ';' separates statements, as
|
|
23
|
+
// LLVM and GNU as read it)
|
|
24
|
+
// punct , [ ] ( ) { } < > + - * : % $ = and a ';' that separates statements
|
|
25
|
+
// address objdump's address column (" 4005d0:", with its colon)
|
|
26
|
+
// bytes objdump's byte column ("48 83 c0 01")
|
|
27
|
+
// space white space
|
|
28
|
+
// text anything else: a quoted string, a stray character
|
|
29
|
+
// error only where the caller passes diagnostics with a column range (opts.diagnostics); never guessed
|
|
30
|
+
//
|
|
31
|
+
// tokenizeLine(line, syntax, opts) -> {tokens, open}: one line of a text for a caller that tokenizes a text a line at a
|
|
32
|
+
// time (the page's editor: only the lines in view); syntax 'intel' or 'att' (detected once for the text by the caller);
|
|
33
|
+
// opts {objdump: the line is read as objdump's (objdumpLine, when objdumpText says the text is objdump's), block: a block
|
|
34
|
+
// comment is open at its start, diagnostics: the line's}; open: a block comment is open at its end. tokenizeText is the
|
|
35
|
+
// same, line after line.
|
|
36
|
+
// tokenizeText(text, syntax, opts) -> one token list per line: the syntax detected once for the text ('auto':
|
|
37
|
+
// loop-find.js detectSyntax), objdump text recognised once (a line with objdump's indented address and tab, its byte
|
|
38
|
+
// column or its function header; then every address-prefixed line is read as objdump's), block comments followed across
|
|
39
|
+
// lines; opts.diagnostics [{line, column, endColumn?, severity}] of the whole text.
|
|
40
|
+
// className(kind) -> 'tok-' + kind; ansi(line, tokens) -> the line with ANSI colours (not used by the CLI yet).
|
|
41
|
+
|
|
42
|
+
import { detectSyntax } from './loop-find.js';
|
|
43
|
+
import { commentFixes } from './asm-regions.js';
|
|
44
|
+
|
|
45
|
+
export const KINDS = Object.freeze(['label', 'mnemonic', 'prefix', 'register', 'number', 'size', 'symbol', 'directive', 'comment',
|
|
46
|
+
'punct', 'address', 'bytes', 'space', 'text', 'error']);
|
|
47
|
+
|
|
48
|
+
export const className = (kind) => `tok-${kind}`;
|
|
49
|
+
const ANSI = { label: 33, mnemonic: 1, prefix: 35, register: 36, number: 32, size: 35, symbol: 33, directive: 34, comment: 2, address: 2, bytes: 2, error: 31 };
|
|
50
|
+
export const ansi = (line, tokens) => tokens.map((t) => (ANSI[t.kind] ? `\x1b[${ANSI[t.kind]}m${line.slice(t.start, t.end)}\x1b[0m` : line.slice(t.start, t.end))).join('');
|
|
51
|
+
|
|
52
|
+
// ---- the words ------------------------------------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
// The registers, one table for both syntaxes (lower case; AT&T writes them with %, which is punct).
|
|
55
|
+
const REGISTERS = new Set([
|
|
56
|
+
...['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp', 'esp',
|
|
57
|
+
'ax', 'bx', 'cx', 'dx', 'si', 'di', 'bp', 'sp', 'al', 'bl', 'cl', 'dl', 'sil', 'dil', 'bpl', 'spl', 'ah', 'bh', 'ch', 'dh',
|
|
58
|
+
'rip', 'eip', 'ip', 'cs', 'ds', 'es', 'fs', 'gs', 'ss', 'st'],
|
|
59
|
+
...Array.from({ length: 8 }, (_, i) => [`r${i + 8}`, `r${i + 8}d`, `r${i + 8}w`, `r${i + 8}b`, `r${i + 8}l`, `k${i}`, `mm${i}`, `st${i}`, `cr${i}`, `dr${i}`]).flat(),
|
|
60
|
+
...Array.from({ length: 32 }, (_, i) => [`xmm${i}`, `ymm${i}`, `zmm${i}`]).flat(),
|
|
61
|
+
'cr8', 'tmm0', 'tmm1', 'tmm2', 'tmm3', 'tmm4', 'tmm5', 'tmm6', 'tmm7',
|
|
62
|
+
]);
|
|
63
|
+
export const isRegister = (word) => REGISTERS.has(String(word).toLowerCase());
|
|
64
|
+
|
|
65
|
+
const SIZES = new Set(['byte', 'word', 'dword', 'qword', 'tbyte', 'tword', 'oword', 'fword', 'xword', 'mmword', 'xmmword', 'ymmword', 'zmmword', 'real4', 'real8', 'real10']);
|
|
66
|
+
const SIZE_WORDS = new Set(['ptr', 'offset', 'short', 'near', 'far']);
|
|
67
|
+
// prefixes before the mnemonic (as loop-find.js and ab-diff.js read them)
|
|
68
|
+
const PREFIXES = new Set(['lock', 'rep', 'repe', 'repz', 'repne', 'repnz', 'bnd', 'notrack', 'xacquire', 'xrelease', 'data16', 'data32',
|
|
69
|
+
'addr32', 'addr16', 'cs', 'ds', 'es', 'ss', 'fs', 'gs', 'rex', 'rex64']);
|
|
70
|
+
|
|
71
|
+
// ---- the scanner ----------------------------------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
const WS = /[ \t\f\v\r\n]+/y;
|
|
74
|
+
const IDENT = /[A-Za-z_.$@?][\w.$@?]*/y;
|
|
75
|
+
const NUM = /[0-9][\w]*/y; // a number or a numeric label reference (1b, 1f), classified below
|
|
76
|
+
const LABEL = /(?:[A-Za-z_.$@?][\w.$@?]*|[0-9]+|"[^"\n]*")(?=[ \t]*:(?!:))/y;
|
|
77
|
+
const BRANCH = /^(?:j[a-z]{1,4}|call[lqw]?|loop[a-z]{0,2}|xbegin)$/i;
|
|
78
|
+
const STRING = /"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?/y;
|
|
79
|
+
const OD_ADDR = /([ \t]*)([0-9a-fA-F]+:)(?=[ \t]|$)/y;
|
|
80
|
+
const OD_BYTES = /((?:[0-9a-fA-F]{2} )*[0-9a-fA-F]{2})(?= ?(?:\t| |[ \t]*$))/y;
|
|
81
|
+
const OD_HEADER = /^([ \t]*)([0-9a-fA-F]+)([ \t]+)(<[^>]*>)([ \t]*:)([ \t]*)$/;
|
|
82
|
+
const SIZE_PTR = /([A-Za-z]+[0-9]*)([ \t]+)(ptr)\b/iy;
|
|
83
|
+
|
|
84
|
+
const match = (re, s, i) => { re.lastIndex = i; const m = re.exec(s); return m && m.index === i ? m : null; };
|
|
85
|
+
const isNumber = (w) => /^(?:0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9][0-9a-fA-F]*[hH]|[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[0-9]+[oOqQ])$/.test(w);
|
|
86
|
+
|
|
87
|
+
// The comment and separator structure of a line: [{start, end, code: bool, sep: bool}] (code: a statement's text;
|
|
88
|
+
// sep: a ';' that separates statements; the rest comments). block: a block comment is open at the start of the line.
|
|
89
|
+
function segments(line, block, commentFrom) {
|
|
90
|
+
const out = [];
|
|
91
|
+
let i = 0, start = 0, q = false;
|
|
92
|
+
const n = line.length;
|
|
93
|
+
const push = (a, b, type) => { if (b > a) out.push({ start: a, end: b, type }); };
|
|
94
|
+
if (block) {
|
|
95
|
+
const e = line.indexOf('*/');
|
|
96
|
+
if (e < 0) return { segs: [{ start: 0, end: n, type: 'comment' }], open: true };
|
|
97
|
+
push(0, e + 2, 'comment');
|
|
98
|
+
i = start = e + 2;
|
|
99
|
+
}
|
|
100
|
+
// a ';' that starts the line (after white space) is a comment (loop-find.js leadingSemicolons)
|
|
101
|
+
const lead = /^[ \t]*;/.exec(line.slice(i, Math.min(n, i + 256)));
|
|
102
|
+
if (lead && !block) { push(0, lead[0].length - 1, 'code'); push(lead[0].length - 1, n, 'comment'); return { segs: out, open: false }; }
|
|
103
|
+
for (; i < n; i++) {
|
|
104
|
+
const c = line[i];
|
|
105
|
+
if (q) { if (c === '\\') i++; else if (c === '"') q = false; continue; }
|
|
106
|
+
if (c === '"') { q = true; continue; }
|
|
107
|
+
if (i === commentFrom) { push(start, i, 'code'); push(i, n, 'comment'); return { segs: out, open: false }; }
|
|
108
|
+
if (c === '#' || (c === '/' && line[i + 1] === '/')) { push(start, i, 'code'); push(i, n, 'comment'); return { segs: out, open: false }; }
|
|
109
|
+
if (c === '/' && line[i + 1] === '*') {
|
|
110
|
+
push(start, i, 'code');
|
|
111
|
+
const e = line.indexOf('*/', i + 2);
|
|
112
|
+
if (e < 0) { push(i, n, 'comment'); return { segs: out, open: true }; }
|
|
113
|
+
push(i, e + 2, 'comment');
|
|
114
|
+
i = e + 1; start = e + 2;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (c === ';') { push(start, i, 'code'); push(i, i + 1, 'sep'); start = i + 1; }
|
|
118
|
+
}
|
|
119
|
+
push(start, n, 'code');
|
|
120
|
+
return { segs: out, open: false };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// The tokens of one statement's text, line[a, b): labels, prefixes, mnemonic or directive, operands.
|
|
124
|
+
function statement(line, a, b, att, objdump, out) {
|
|
125
|
+
const s = line.slice(0, b); // the regexes stop at b (a slice of the line up to it: linear overall)
|
|
126
|
+
let i = a;
|
|
127
|
+
const tok = (end, kind) => { if (end > i) { out.push({ start: i, end, kind }); i = end; } };
|
|
128
|
+
const space = () => { const m = match(WS, s, i); if (m) tok(i + m[0].length, 'space'); };
|
|
129
|
+
space();
|
|
130
|
+
if (objdump && i < b) {
|
|
131
|
+
// objdump: the address, the byte column, then the instruction
|
|
132
|
+
const m = match(OD_ADDR, s, i);
|
|
133
|
+
if (m) {
|
|
134
|
+
tok(i + m[2].length, 'address');
|
|
135
|
+
space();
|
|
136
|
+
const by = match(OD_BYTES, s, i);
|
|
137
|
+
if (by) { tok(i + by[1].length, 'bytes'); space(); }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// labels
|
|
141
|
+
for (;;) {
|
|
142
|
+
const m = match(LABEL, s, i);
|
|
143
|
+
if (!m) break;
|
|
144
|
+
tok(i + m[0].length, 'label');
|
|
145
|
+
space();
|
|
146
|
+
tok(i + 1, 'punct'); // the ':'
|
|
147
|
+
space();
|
|
148
|
+
}
|
|
149
|
+
if (i >= b) return;
|
|
150
|
+
// prefixes, then the mnemonic or a directive
|
|
151
|
+
let first = true, branch = false;
|
|
152
|
+
for (;;) {
|
|
153
|
+
if (s[i] === '{') { // a pseudo-prefix: {vex}, {evex}, {disp32}
|
|
154
|
+
const e = s.indexOf('}', i);
|
|
155
|
+
if (e < 0 || !/^\{[\w ]+\}$/.test(s.slice(i, e + 1))) break;
|
|
156
|
+
tok(e + 1, 'prefix'); space();
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const m = match(IDENT, s, i);
|
|
160
|
+
if (!m) break;
|
|
161
|
+
const w = m[0], lw = w.toLowerCase();
|
|
162
|
+
const after = s[i + w.length];
|
|
163
|
+
if (first && w[0] === '.') { tok(i + w.length, 'directive'); space(); break; }
|
|
164
|
+
if ((PREFIXES.has(lw) || /^rex\.\w+$/.test(lw)) && after !== ':' && after !== ',' && /\S/.test(s.slice(i + w.length, b))) { tok(i + w.length, 'prefix'); space(); first = false; continue; }
|
|
165
|
+
if (after === ':' || after === '=') break; // not a mnemonic: an assignment or a segment
|
|
166
|
+
tok(i + w.length, 'mnemonic'); space();
|
|
167
|
+
branch = BRANCH.test(w);
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
operands(s, i, b, att, out, branch);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// The operands (and whatever else follows a mnemonic or directive), s[i, b). branch: a direct branch's mnemonic: a bare
|
|
174
|
+
// number as its first operand is its target (objdump: "jne 401126 <loop+0x6>"), a symbol.
|
|
175
|
+
function operands(s, i, b, att, out, branch = false) {
|
|
176
|
+
const tok = (end, kind) => { if (end > i) { out.push({ start: i, end, kind }); i = end; } };
|
|
177
|
+
let brace = false; // inside { } (a mask or decoration)
|
|
178
|
+
let target = branch; // the next operand is a branch target
|
|
179
|
+
while (i < b) {
|
|
180
|
+
const c = s[i];
|
|
181
|
+
let m;
|
|
182
|
+
if ((m = match(WS, s, i))) { tok(i + m[0].length, 'space'); continue; }
|
|
183
|
+
if (c === '%') {
|
|
184
|
+
tok(i + 1, 'punct');
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (c === '$' && /[0-9]/.test(s[i + 1] ?? '')) {
|
|
188
|
+
m = match(NUM, s, i + 1);
|
|
189
|
+
tok(i + 1 + m[0].length, isNumber(m[0]) ? 'number' : 'symbol');
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (c === '"' || c === "'") { m = match(STRING, s, i); tok(i + m[0].length, 'text'); continue; }
|
|
193
|
+
if ((m = match(NUM, s, i))) {
|
|
194
|
+
const w = m[0];
|
|
195
|
+
if (brace && /^1to\d+$/i.test(w)) tok(i + w.length, 'size');
|
|
196
|
+
else if (target && /^(?:0[xX])?[0-9a-fA-F]+$/.test(w)) tok(i + w.length, 'symbol');
|
|
197
|
+
else tok(i + w.length, isNumber(w) ? 'number' : /^[0-9]+[bf]$/i.test(w) ? 'symbol' : 'text');
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if ((m = match(IDENT, s, i))) {
|
|
201
|
+
const w = m[0], lw = w.toLowerCase();
|
|
202
|
+
if (c === '$') { tok(i + 1, 'punct'); continue; } // $sym: the $ alone, the symbol next
|
|
203
|
+
if (REGISTERS.has(lw)) {
|
|
204
|
+
// st(1): the register with its parentheses
|
|
205
|
+
if (lw === 'st' && /^\(\d\)$/.test(s.slice(i + 2, i + 5)) && i + 5 <= b) { tok(i + 5, 'register'); continue; }
|
|
206
|
+
tok(i + w.length, 'register');
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (SIZES.has(lw)) {
|
|
210
|
+
const p = match(SIZE_PTR, s, i);
|
|
211
|
+
tok(p && p.index + p[0].length <= b && p[1].toLowerCase() === lw ? i + p[0].length : i + w.length, 'size');
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (SIZE_WORDS.has(lw) || (brace && /^(?:z|sae|r[nduz]-sae)$/i.test(w))) { tok(i + w.length, 'size'); continue; }
|
|
215
|
+
tok(i + w.length, 'symbol');
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
target = false;
|
|
219
|
+
if (c === '{') brace = true;
|
|
220
|
+
else if (c === '}') brace = false;
|
|
221
|
+
tok(i + 1, '[](){}<>,+-*:%$=!~&|^/'.includes(c) ? 'punct' : 'text');
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// After the tokens are made: the diagnostics' column ranges (1-based columns, end exclusive or the end of the token at
|
|
226
|
+
// the column) become 'error', splitting tokens where they begin and end.
|
|
227
|
+
function markErrors(tokens, ranges) {
|
|
228
|
+
if (!ranges.length) return tokens;
|
|
229
|
+
const out = [];
|
|
230
|
+
for (const t of tokens) {
|
|
231
|
+
let parts = [{ ...t }];
|
|
232
|
+
for (const [a, b] of ranges) {
|
|
233
|
+
if (b <= t.start || a >= t.end) continue;
|
|
234
|
+
const next = [];
|
|
235
|
+
for (const p of parts) {
|
|
236
|
+
if (b <= p.start || a >= p.end || p.kind === 'error') { next.push(p); continue; }
|
|
237
|
+
if (a > p.start) next.push({ start: p.start, end: a, kind: p.kind });
|
|
238
|
+
next.push({ start: Math.max(a, p.start), end: Math.min(b, p.end), kind: 'error' });
|
|
239
|
+
if (b < p.end) next.push({ start: b, end: p.end, kind: p.kind });
|
|
240
|
+
}
|
|
241
|
+
parts = next;
|
|
242
|
+
}
|
|
243
|
+
out.push(...parts);
|
|
244
|
+
}
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// The column ranges [start, end) of a line's error diagnostics: from the column to endColumn, else to the end of the
|
|
249
|
+
// word at the column (to the end of the line for a column past the code).
|
|
250
|
+
function errorRanges(line, diags) {
|
|
251
|
+
const out = [];
|
|
252
|
+
for (const d of diags) {
|
|
253
|
+
if (d.severity && d.severity !== 'error') continue;
|
|
254
|
+
const col = Number(d.column);
|
|
255
|
+
if (!(col >= 1)) continue;
|
|
256
|
+
const a = Math.min(col - 1, line.length);
|
|
257
|
+
let b = Number(d.endColumn) > col ? Number(d.endColumn) - 1 : -1;
|
|
258
|
+
if (b < 0) b = a + Math.max(1, (/^\S*/.exec(line.slice(a, a + 256))?.[0] ?? '').length);
|
|
259
|
+
out.push([a, Math.min(b, Math.max(line.length, a + 1))]);
|
|
260
|
+
}
|
|
261
|
+
return out.filter(([a, b]) => b > a && a < line.length);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// The column (0-based) from which the line is a comment because of a ';' the assembler could not read as a separator
|
|
265
|
+
// (asm-regions.js commentFixes, given the line's diagnostics), or -1.
|
|
266
|
+
function semicolonComment(line, diags) {
|
|
267
|
+
const errs = diags.filter((d) => d.severity === 'error' || /taken as a comment/.test(d.message ?? ''));
|
|
268
|
+
if (!errs.length) return -1;
|
|
269
|
+
const { fixes } = commentFixes(errs.map((d) => ({ ...d, line: 1, severity: 'error', column: d.message && /taken as a comment/.test(d.message) ? d.column + 1 : d.column })), line);
|
|
270
|
+
const fixed = fixes.get(1);
|
|
271
|
+
if (!fixed) return -1;
|
|
272
|
+
for (let i = 0; i < line.length; i++) if (line[i] !== fixed[i]) return i;
|
|
273
|
+
return -1;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function lineTokens(line, att, objdump, block, diags) {
|
|
277
|
+
const n = line.length;
|
|
278
|
+
if (!n) return { tokens: [], open: block };
|
|
279
|
+
const out = [];
|
|
280
|
+
const header = objdump && !block ? OD_HEADER.exec(line) : null;
|
|
281
|
+
if (header) {
|
|
282
|
+
let at = 0;
|
|
283
|
+
for (const [k, kind] of [[1, 'space'], [2, 'address'], [3, 'space'], [4, 'label'], [5, 'punct'], [6, 'space']]) {
|
|
284
|
+
if (header[k]) out.push({ start: at, end: at + header[k].length, kind });
|
|
285
|
+
at += header[k].length;
|
|
286
|
+
}
|
|
287
|
+
return { tokens: out, open: false };
|
|
288
|
+
}
|
|
289
|
+
const commentFrom = diags.length ? semicolonComment(line, diags) : -1;
|
|
290
|
+
const { segs, open } = segments(line, block, commentFrom);
|
|
291
|
+
let firstCode = true;
|
|
292
|
+
for (const g of segs) {
|
|
293
|
+
if (g.type === 'comment') out.push({ start: g.start, end: g.end, kind: 'comment' });
|
|
294
|
+
else if (g.type === 'sep') out.push({ start: g.start, end: g.end, kind: 'punct' });
|
|
295
|
+
else { statement(line, g.start, g.end, att, objdump && firstCode, out); firstCode = false; }
|
|
296
|
+
}
|
|
297
|
+
const ranges = diags.length ? errorRanges(line, diags).filter(([a]) => commentFrom < 0 || a < commentFrom) : [];
|
|
298
|
+
return { tokens: ranges.length ? markErrors(out, ranges) : out, open };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// A line whose tokens cannot be made (not expected): one text token.
|
|
302
|
+
const whole = (line) => (line.length ? [{ start: 0, end: line.length, kind: 'text' }] : []);
|
|
303
|
+
|
|
304
|
+
// The objdump form of one line on its own: an address column ended by a tab (as objdump writes it), a byte column, or
|
|
305
|
+
// the function header (objdump indents the address; a numeric label at the start of the line, "2:\tdecq %rcx", stays a
|
|
306
|
+
// label).
|
|
307
|
+
const looksObjdump = (line) => /^[ \t]+[0-9a-fA-F]+:\t/.test(line) || /^[ \t]*[0-9a-fA-F]+:[ \t]+(?:[0-9a-fA-F]{2} )*[0-9a-fA-F]{2}(?:\t| )/.test(line) || OD_HEADER.test(line);
|
|
308
|
+
|
|
309
|
+
// The tokens of one line. syntax: 'intel', 'att' or 'auto' (detectSyntax of the line, else Intel). opts: {objdump
|
|
310
|
+
// (true/false; default: from the line), diagnostics: [{column, endColumn?, severity, message}] of this line, block
|
|
311
|
+
// (a block comment is open at its start)}.
|
|
312
|
+
export function tokenize(line, syntax = 'auto', opts = {}) {
|
|
313
|
+
const s = typeof line === 'string' ? line : String(line ?? '');
|
|
314
|
+
try {
|
|
315
|
+
const att = syntax === 'att' || (syntax !== 'intel' && detectSyntax(s) === 'att');
|
|
316
|
+
const od = typeof opts.objdump === 'boolean' ? opts.objdump : looksObjdump(s);
|
|
317
|
+
return lineTokens(s, att, od, !!opts.block, Array.isArray(opts.diagnostics) ? opts.diagnostics : []).tokens;
|
|
318
|
+
} catch {
|
|
319
|
+
return whole(s);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// The tokens of every line of a text (lines split at \n; a CR before it is white space). syntax 'auto': detected
|
|
324
|
+
// once for the text. opts: {diagnostics: [{line (1-based), column, endColumn?, severity, message}]}.
|
|
325
|
+
export function tokenizeText(text, syntax = 'auto', opts = {}) {
|
|
326
|
+
const t = typeof text === 'string' ? text : String(text ?? '');
|
|
327
|
+
const lines = t.split('\n');
|
|
328
|
+
let att = syntax === 'att', od = false;
|
|
329
|
+
try {
|
|
330
|
+
if (syntax !== 'att' && syntax !== 'intel') att = detectSyntax(t) === 'att';
|
|
331
|
+
od = objdumpText(lines);
|
|
332
|
+
} catch { /* plain */ }
|
|
333
|
+
const byLine = new Map();
|
|
334
|
+
for (const d of Array.isArray(opts.diagnostics) ? opts.diagnostics : []) if (d && d.line >= 1) (byLine.get(d.line) ?? byLine.set(d.line, []).get(d.line)).push(d);
|
|
335
|
+
let block = false;
|
|
336
|
+
return lines.map((l, k) => {
|
|
337
|
+
const r = tokenizeLine(l, att ? 'att' : 'intel', { objdump: od && objdumpLine(l), block, diagnostics: byLine.get(k + 1) ?? [] });
|
|
338
|
+
block = r.open;
|
|
339
|
+
return r.tokens;
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// One line with the state it starts and ends in (see the top): {tokens, open}; never throws (a line that cannot be
|
|
344
|
+
// read is one text token, and closes a block comment).
|
|
345
|
+
export function tokenizeLine(line, syntax = 'intel', opts = {}) {
|
|
346
|
+
const s = typeof line === 'string' ? line : String(line ?? '');
|
|
347
|
+
try {
|
|
348
|
+
return lineTokens(s, syntax === 'att', !!opts.objdump, !!opts.block, Array.isArray(opts.diagnostics) ? opts.diagnostics : []);
|
|
349
|
+
} catch {
|
|
350
|
+
return { tokens: whole(s), open: false };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
// The text (its lines) is objdump's: one line looks like objdump's on its own (then every line with an address column
|
|
354
|
+
// is read as objdump's: objdumpLine).
|
|
355
|
+
export const objdumpText = (lines) => lines.some(looksObjdump);
|
|
356
|
+
// in objdump text: a line with an address column or the header
|
|
357
|
+
export const objdumpLine = (l) => /^[ \t]*[0-9a-fA-F]+:/.test(l) || OD_HEADER.test(l);
|
package/lib/web/assembler.js
CHANGED
|
@@ -38,9 +38,37 @@ export function parseDiagnostics(text) {
|
|
|
38
38
|
return out;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
//
|
|
41
|
+
// The text as the module gets it, the one preparation for the page and the npm package (lib/wasm.js): no byte order
|
|
42
|
+
// mark at the start (not code: LLVM would reject it), a NUL character as a space (the module reads a C string, which
|
|
43
|
+
// ends at the first NUL: clang -g -S writes NULs into the comments of its .debug_str bytes, and the text after one,
|
|
44
|
+
// with the labels it defines, would be lost), stripHints, and no line table (withoutLineTable). Lines and columns stay
|
|
45
|
+
// where they are.
|
|
46
|
+
export function prepareSource(text) {
|
|
47
|
+
return withoutLineTable(stripHints(String(text).replace(/^\uFEFF/, '').replace(/\0/g, ' ')));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The line table's directives, a `.loc` and a numbered `.file` on a line of their own (after labels), blanked (the columns stay): the
|
|
51
|
+
// bytes of the code do not depend on them (asm-regions.js reads the lines from them before), while LLVM 22 rejects some
|
|
52
|
+
// of gcc's: DWARF 5 (gcc 11 and later -g) with ".file 0" gives "unassigned file number in '.loc'", a "view N" operand
|
|
53
|
+
// "unknown sub-directive". A view's symbol (.LVU3), which the debug sections can use, is defined as 0 after the text.
|
|
54
|
+
const LINE_TABLE = /^([ \t]*(?:[\w.$@]+:[ \t]*)*)(\.loc[ \t][^\n;#]*|\.file[ \t]+\d+[ \t](?:"(?:[^"\\\n]|\\.)*"|[^\n;#"])*)/gm;
|
|
55
|
+
export function withoutLineTable(text) {
|
|
56
|
+
const views = new Set();
|
|
57
|
+
const out = text.replace(LINE_TABLE, (_, lead, d) => {
|
|
58
|
+
const v = /\bview[ \t]+([A-Za-z_.$][\w.$]*)/.exec(d);
|
|
59
|
+
if (d.startsWith('.loc') && v) views.add(v[1]);
|
|
60
|
+
return lead + ' '.repeat(d.length);
|
|
61
|
+
});
|
|
62
|
+
return views.size ? `${out}\n${[...views].map((n) => `.set ${n}, 0`).join('\n')}\n` : out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Removes GNU as's {load} / {store} pseudo-prefixes at the start of a line (LLVM 22 says "unknown prefix"), and reads
|
|
66
|
+
// directives of newer compilers that the bundled LLVM 22 does not know: clang 23's `.prefalign LOG2, END, FILL` (a
|
|
67
|
+
// function's preferred alignment) as `.p2align LOG2`, the alignment clang 22 wrote there (after labels, in any case, up to
|
|
68
|
+
// a ';' or '#': what follows stays). Lines stay where they are.
|
|
42
69
|
export function stripHints(text) {
|
|
43
|
-
return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1')
|
|
70
|
+
return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1')
|
|
71
|
+
.replace(/^([ \t]*(?:[\w.$@]+:[ \t]*)*)\.prefalign[ \t]+(\d+)[^\n#;]*/gim, '$1.p2align $2');
|
|
44
72
|
}
|
|
45
73
|
|
|
46
74
|
// LLVM (like GNU as) reads ';' as a separator between statements, not as a comment, so "add rax, 1 ; note" fails with
|
|
@@ -79,8 +107,10 @@ export function isWasm(bytes) {
|
|
|
79
107
|
}
|
|
80
108
|
|
|
81
109
|
export class WasmAssembler {
|
|
82
|
-
|
|
83
|
-
#
|
|
110
|
+
/** @type {any} */
|
|
111
|
+
#module; // a WebAssembly.Module, or a function that makes the exports (create())
|
|
112
|
+
/** @type {any} */
|
|
113
|
+
#x = null; // the instance's exports
|
|
84
114
|
|
|
85
115
|
// source: the bytes of wuica_asm.wasm, a WebAssembly.Module, or (tests) a function that returns a fresh object with
|
|
86
116
|
// the exports.
|
|
@@ -114,7 +144,7 @@ export class WasmAssembler {
|
|
|
114
144
|
if (i.kind !== 'function') throw new Error(`wuica_asm.wasm: unsupported import ${i.module}.${i.name}`);
|
|
115
145
|
(imports[i.module] ??= {})[i.name] = () => 52;
|
|
116
146
|
}
|
|
117
|
-
x = (await WebAssembly.instantiate(this.#module, imports)).exports;
|
|
147
|
+
x = (await WebAssembly.instantiate(/** @type {WebAssembly.Module} */ (this.#module), imports)).exports;
|
|
118
148
|
}
|
|
119
149
|
for (const name of ['memory', 'malloc', 'free', 'wuica_assemble']) {
|
|
120
150
|
if (!x[name]) throw new Error(`wuica_asm.wasm: export "${name}" is missing`);
|
|
@@ -155,7 +185,7 @@ export class WasmAssembler {
|
|
|
155
185
|
if (!(syntax in SYNTAX)) throw new TypeError(`unknown syntax: ${syntax}`);
|
|
156
186
|
if (!this.#x) await this.#instantiate();
|
|
157
187
|
// (a byte order mark at the start is not code: LLVM would reject it)
|
|
158
|
-
const plain =
|
|
188
|
+
const plain = prepareSource(text);
|
|
159
189
|
const mode = codeModeError(plain);
|
|
160
190
|
if (mode) return { ok: false, diagnostics: [{ severity: 'error', ...mode }] };
|
|
161
191
|
const source = new TextEncoder().encode(plain + '\0');
|