// wasm-leb-width.mjs: how many bytes of a linked module's code are spent on LEB padding, and whether two // modules hold the same code at two encodings. // // node wasm-leb-width.mjs FILE [--max-pct P] [--refuse-debug] // print the padded bytes; with --max-pct, exit 1 at or above P%; // with --refuse-debug, exit 1 if FILE carries a .debug_* section // node wasm-leb-width.mjs --same A B exit 0 only if A and B hold the same module up to LEB width: // every non-debug section byte-identical, and where the code // differs, every function decoding to the same instructions and // carrying the same branch hints on the same ones // node wasm-leb-width.mjs --twin SHIPPED TWIN --same, and SHIPPED carries no .debug_* section and TWIN does: // TWIN is SHIPPED's own link with its DWARF kept // // wasm-ld writes every relocated immediate (a call's function index, a global.get of the stack pointer or the // status channel, the i32.const of a data or table address, a call_indirect's type) as a five-byte LEB, so that // a relocation can be applied in place. A final link has nothing left to apply, and --compress-relocations // writes each at its minimal width. Measured on the shipped images before the flag was passed: 10.6% of glibc // bash, 9.3% of glibc libc.so's code, 7.8% of lua, 9.6% of vmlinux. The status-channel lowering is call-dense // (lua carries 34,254 padded call immediates against 4,532 in its plain build), so it pays the most. // // The decoder reads every immediate of every instruction the toolchain emits; a body that does not end exactly // at its declared length is an error, never a silent undercount. libexec/wasm-branch-hints.mjs walks the same // opcode set. import fs from 'node:fs'; import crypto from 'node:crypto'; class Mod { constructor(file) { this.file = file; const b = this.b = fs.readFileSync(file); if (b.length < 8 || b.readUInt32LE(0) !== 0x6d736100) throw new Error(`${file}: not a wasm module`); this.sections = []; let p = 8; while (p < b.length) { const at = p, id = b[p++]; const [size, q] = uleb(b, p); let name = null; if (id === 0) { const [n, r] = uleb(b, q); name = b.subarray(r, r + n).toString(); } this.sections.push({ id, name, at, start: q, end: q + size }); p = q + size; } this.nImportedFns = 0; const imp = this.sections.find((s) => s.id === 2); if (imp) { let [n, q] = uleb(b, imp.start); for (; n > 0; n--) { let l; [l, q] = uleb(b, q); q += l; [l, q] = uleb(b, q); q += l; const kind = b[q++]; if (kind === 0) { [, q] = uleb(b, q); this.nImportedFns++; } else if (kind === 1) { q++; let f; [f, q] = uleb(b, q); [, q] = uleb(b, q); if (f & 1) [, q] = uleb(b, q); } else if (kind === 2) { let f; [f, q] = uleb(b, q); [, q] = uleb(b, q); if (f & 1) [, q] = uleb(b, q); if (f & 4) [, q] = uleb(b, q); } else if (kind === 3) q += 2; else if (kind === 4) { q++; [, q] = uleb(b, q); } else throw new Error(`${file}: import kind ${kind}`); } } this.bodies = []; const code = this.code = this.sections.find((s) => s.id === 10); if (code) { let [n, q] = uleb(b, code.start); for (; n > 0; n--) { const [size, r] = uleb(b, q); this.bodies.push({ sizeAt: q, start: r, end: r + size }); q = r + size; } if (q !== code.end) throw new Error(`${file}: the code section has ${code.end - q} bytes after its last body`); } } } function uleb(b, p) { let r = 0, s = 0, x; do { x = b[p++]; r += (x & 0x7f) * 2 ** s; s += 7; } while (x & 0x80); return [r, p]; } function sleb(b, p) { let r = 0n, s = 0n, x; do { x = b[p++]; r |= BigInt(x & 0x7f) << s; s += 7n; } while (x & 0x80); if (x & 0x40) r -= 1n << s; return [r, p]; } const minU = (v) => { let n = 1; while (v >= 128) { v = Math.floor(v / 128); n++; } return n; }; const minS = (v) => { let n = 1; while (v < -64n || v > 63n) { v >>= 7n; n++; } return n; }; // Decode one body. Returns { insns: [{ at, key }], padded, imms } where key is the instruction with its // immediates as values (so two encodings of one instruction have one key), at is its offset from the body // start (the branch-hint section's origin), padded counts the bytes above minimal width. function decodeBody(m, body) { const b = m.b, end = body.end; let p = body.start, padded = 0, imms = 0; const U = () => { const s = p; const [v, q] = uleb(b, p); p = q; const w = (q - s) - minU(v); if (w) { padded += w; imms++; } return v; }; const S = () => { const s = p; const [v, q] = sleb(b, p); p = q; const w = (q - s) - minS(v); if (w) { padded += w; imms++; } return v; }; const bytes = (n) => { const v = b.subarray(p, p + n).toString('hex'); p += n; return v; }; const memarg = () => { const a = U(); const mem = (a & 0x40) ? U() : 0; return `${a}.${mem}.${U()}`; }; const blocktype = () => { const t = b[p]; if (t === 0x40 || (t & 0xc0) === 0x40) { p++; return `t${t}`; } return `x${S()}`; }; let locals = []; for (let n = U(); n > 0; n--) locals.push(`${U()}x${b[p++]}`); const insns = [{ at: 0, key: `locals ${locals.join(',')}` }]; while (p < end) { const at = p - body.start, op = b[p++]; let k = op.toString(16); if (op === 0x02 || op === 0x03 || op === 0x04 || op === 0x06) k += ' ' + blocktype(); else if ([0x0c, 0x0d, 0x07, 0x08, 0x09, 0x18, 0x10, 0x12, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0xd2].includes(op)) k += ' ' + U(); else if (op === 0x0e) { const t = []; for (let n = U() + 1; n > 0; n--) t.push(U()); k += ' ' + t.join(','); } else if (op === 0x11 || op === 0x13) k += ` ${U()} ${U()}`; else if (op === 0x1c) { const t = []; for (let n = U(); n > 0; n--) t.push(b[p++]); k += ' ' + t.join(','); } else if (op === 0x1f) { k += ' ' + blocktype(); for (let n = U(); n > 0; n--) { const c = b[p++]; k += ` c${c}`; if (c === 0 || c === 1) k += ':' + U(); k += ':' + U(); } } else if (op >= 0x28 && op <= 0x3e) k += ' ' + memarg(); else if (op === 0x3f || op === 0x40) k += ' ' + U(); else if (op === 0x41 || op === 0x42) k += ' ' + S(); else if (op === 0x43) k += ' ' + bytes(4); else if (op === 0x44) k += ' ' + bytes(8); else if (op === 0xd0) k += ' ' + S(); else if (op === 0xfc) { const s = U(); k += '.' + s; if (s === 8 || s === 10 || s === 12 || s === 14) k += ` ${U()} ${U()}`; else if (s === 9 || s === 11 || s === 13 || s === 15 || s === 16 || s === 17) k += ' ' + U(); else if (s > 17) throw new Error(`${m.file}: 0xfc ${s} at byte ${p}: an instruction this decoder does not know`); } else if (op === 0xfd) { const s = U(); k += '.' + s; if (s <= 11 || s === 92 || s === 93) k += ' ' + memarg(); else if (s === 12 || s === 13) k += ' ' + bytes(16); else if (s >= 21 && s <= 34) k += ' ' + bytes(1); else if (s >= 84 && s <= 91) k += ` ${memarg()} ${bytes(1)}`; } else if (op === 0xfe) { const s = U(); k += '.' + s; if (s === 3) k += ' ' + bytes(1); else k += ' ' + memarg(); } else if (op === 0x05 || op === 0x0b || op === 0x0f || op === 0x00 || op === 0x01 || op === 0x19 || op === 0x0a || op === 0x1a || op === 0x1b || op === 0xd1 || (op >= 0x45 && op <= 0xc4)) { /* no immediate */ } else throw new Error(`${m.file}: opcode 0x${op.toString(16)} at byte ${p - 1}: an instruction this decoder does not know`); insns.push({ at, key: k }); } if (p !== end) throw new Error(`${m.file}: a body decoded to byte ${p} and ends at ${end}`); return { insns, padded, imms }; } function hints(m) { const s = m.sections.find((x) => x.id === 0 && x.name === 'metadata.code.branch_hint'); const out = new Map(); if (!s) return out; const b = m.b; let [nl, p] = uleb(b, s.start); p += nl; let n; [n, p] = uleb(b, p); for (; n > 0; n--) { let f, c; [f, p] = uleb(b, p); [c, p] = uleb(b, p); const hs = []; for (; c > 0; c--) { let o, sz; [o, p] = uleb(b, p); [sz, p] = uleb(b, p); hs.push([o, b[p]]); p += sz; } out.set(f, hs); } return out; } const hash = (m, s) => crypto.createHash('sha256').update(m.b.subarray(s.start, s.end)).digest('hex'); const label = (s) => (s.id === 0 ? s.name : `section ${s.id}`); const isDebug = (s) => s.id === 0 && s.name.startsWith('.debug_'); const args = process.argv.slice(2); try { if (args[0] === '--twin' || args[0] === '--same') { const [a, t] = [new Mod(args[1]), new Mod(args[2])]; const bad = []; if (args[0] === '--twin') { if (a.sections.some(isDebug)) bad.push(`${a.file} carries ${a.sections.filter(isDebug).map(label).join(' ')}`); if (!t.sections.some(isDebug)) bad.push(`${t.file} carries no .debug_* section to keep`); } const sa = a.sections.filter((s) => !isDebug(s)), st = t.sections.filter((s) => !isDebug(s)); if (sa.map(label).join() !== st.map(label).join()) bad.push(`the non-debug section lists differ: [${sa.map(label)}] against [${st.map(label)}]`); let codeSame = true; for (let i = 0; i < Math.min(sa.length, st.length); i++) { if (hash(a, sa[i]) === hash(t, st[i])) continue; if (sa[i].id === 10) { codeSame = false; continue; } if (sa[i].id === 0 && sa[i].name === 'metadata.code.branch_hint') continue; bad.push(`${label(sa[i])} differs`); } let fns = 0, nh = 0; if (!codeSame) { if (a.bodies.length !== t.bodies.length) bad.push(`${a.bodies.length} bodies against ${t.bodies.length}`); const ha = hints(a), ht = hints(t); for (let i = 0; i < a.bodies.length && i < t.bodies.length; i++) { const x = decodeBody(a, a.bodies[i]).insns, y = decodeBody(t, t.bodies[i]).insns; const f = i + a.nImportedFns; if (x.length !== y.length || x.some((v, j) => v.key !== y[j].key)) { if (fns++ < 3) bad.push(`function ${f} decodes differently`); continue; } const ord = (ins, hs) => (hs || []).map(([o, v]) => `${ins.findIndex((z) => z.at === o)}:${v}`).join(); const oa = ord(x, ha.get(f)), ot = ord(y, ht.get(f)); if (oa !== ot || oa.includes('-1:')) { if (nh++ < 3) bad.push(`function ${f}'s branch hints are on different instructions`); } } if (fns) bad.push(`${fns} function(s) decode differently`); if (nh) bad.push(`${nh} function(s) carry different branch hints`); if ([...ha.values()].flat().length !== [...ht.values()].flat().length) bad.push('the branch-hint counts differ'); } if (bad.length) { console.error(`wasm-leb-width: ${t.file} is not ${args[0] === '--twin' ? 'the debug twin of' : 'the same module as'} ${a.file}:\n ${bad.join('\n ')}`); process.exit(1); } console.log(`wasm-leb-width: ${args[0].slice(2)} ok: ${a.bodies.length} functions, ${codeSame ? 'the same code bytes' : 'the same instructions at two encodings'}, ` + `${[...hints(a).values()].flat().length} branch hints, every other non-debug section byte-identical`); } else { const file = args[0]; const mi = args.indexOf('--max-pct'), max = mi >= 0 ? Number(args[mi + 1]) : null; const m = new Mod(file); let padded = 0, imms = 0; for (const body of m.bodies) { const r = decodeBody(m, body); padded += r.padded; imms += r.imms; } const codeBytes = m.code ? m.code.end - m.code.start : 0; const pct = codeBytes ? (100 * padded) / codeBytes : 0; console.log(`wasm-leb-width: ${file}: code=${codeBytes} padded=${padded} (${pct.toFixed(2)}% of the code, ${imms} immediates) functions=${m.bodies.length}`); let fail = false; if (max !== null && pct >= max) { console.error(`wasm-leb-width: ${file}: ${pct.toFixed(2)}% of the code is LEB padding, at or above the ${max}% bound: it was linked without --compress-relocations`); fail = true; } const dbg = m.sections.filter(isDebug); if (args.includes('--refuse-debug') && dbg.length) { console.error(`wasm-leb-width: ${file} carries ${dbg.map(label).join(' ')} (${dbg.reduce((n, s) => n + s.end - s.start, 0)} bytes): its DWARF belongs in the link's sidecar, not in the shipped image`); fail = true; } if (fail) process.exit(1); } } catch (e) { console.error(`wasm-leb-width: ${e.message}`); process.exit(2); }