// wasm-libc-partition.mjs: carry a shared libc's suspend class in the libc itself, as the custom section // `hwjs.libc_partition`. // // node wasm-libc-partition.mjs --write PARTITION FILE... append the section to each FILE, built from PARTITION // node wasm-libc-partition.mjs --check PARTITION FILE exit 0 only if FILE carries exactly one section, and it // is the one --write builds from PARTITION // node wasm-libc-partition.mjs --print FILE print the section's version, digest and names // // A program's call to a libc name is prepared for a park only when the libc's published partition gives the name // the `suspend` class. The loader decides from that class whether a library that also defines the name may serve // the call ahead of libc. Until now only the partition's digest reached a target (hwjs.abi v2), so the loader // guessed the class from the program's own imports, and an address-take reads exactly like a prepared call. // // Section payload, all integers unsigned LEB128: // version 1 // digest 32 bytes, the sha256 of the partition file (hwjs.abi v2 carries its first 8) // count the number of names that follow // names count x (length, UTF-8 bytes): every `suspend` name in the partition, sorted by byte value // `native` and `refused` names are not listed: a name absent from the list is not prepared for a park. // // --write refuses a FILE whose hwjs.abi does not stamp this partition's digest, and a FILE that already carries the // section: the class list and the digest the loader checks it against come from one file or the section is not // written. import fs from 'node:fs'; import crypto from 'node:crypto'; const SECTION = 'hwjs.libc_partition'; const VERSION = 1; function uleb(b, p) { let v = 0, s = 0, x; do { if (p >= b.length) throw new Error('truncated LEB128'); x = b[p++]; v += (x & 0x7f) * 2 ** s; s += 7; } while (x & 0x80); return [v, p]; } function ulebHex64(b, p) { let v = 0n, s = 0n, x; do { if (p >= b.length) throw new Error('truncated LEB128'); x = b[p++]; v |= BigInt(x & 0x7f) << s; s += 7n; } while (x & 0x80); return [v.toString(16).padStart(16, '0'), p]; } function encUleb(n) { const out = []; do { let x = n % 128; n = Math.floor(n / 128); if (n) x |= 0x80; out.push(x); } while (n); return Buffer.from(out); } function customSections(b, file) { if (b.length < 8 || b.readUInt32LE(0) !== 0x6d736100) throw new Error(`${file}: not a wasm module`); const out = []; let p = 8; while (p < b.length) { const id = b[p++]; const [size, q] = uleb(b, p); if (q + size > b.length) throw new Error(`${file}: a section runs past the end of the file`); if (id === 0) { const [n, r] = uleb(b, q); out.push({ name: b.subarray(r, r + n).toString(), body: b.subarray(r + n, q + size) }); } p = q + size; } return out; } // The first 8 bytes of the partition digest hwjs.abi v2 stamps, as 16 hex digits, or null. function abiDigestLo64(b, file) { const abi = customSections(b, file).filter((s) => s.name === 'hwjs.abi'); if (abi.length !== 1) return null; let p = 0, v; const f = []; for (let i = 0; i < 8; i++) { [v, p] = uleb(abi[0].body, p); f.push(v); } if (f[0] < 2) return null; return ulebHex64(abi[0].body, p)[0]; } function readPartition(path) { const text = fs.readFileSync(path); const names = []; const seen = new Set(); let n = 0; for (const line of text.toString().split('\n')) { n++; if (line === '') continue; const m = /^(suspend|native|refused)(\+(?:nothrow|throws))? (\S+)$/.exec(line); if (!m) throw new Error(`${path}:${n}: not a partition line: ${JSON.stringify(line)}`); if (seen.has(m[3])) throw new Error(`${path}:${n}: ${m[3]} is listed twice`); seen.add(m[3]); if (m[1] === 'suspend') names.push(Buffer.from(m[3])); } names.sort(Buffer.compare); return { digest: crypto.createHash('sha256').update(text).digest(), names }; } function payload(part) { const parts = [encUleb(VERSION), part.digest, encUleb(part.names.length)]; for (const nm of part.names) parts.push(encUleb(nm.length), nm); return Buffer.concat(parts); } function section(body) { const name = Buffer.from(SECTION); const inner = Buffer.concat([encUleb(name.length), name, body]); return Buffer.concat([Buffer.from([0]), encUleb(inner.length), inner]); } function parseSection(body) { let p = 0, version, count, len; [version, p] = uleb(body, p); if (version !== VERSION) return { version, digest: null, names: null }; if (p + 32 > body.length) throw new Error('truncated digest'); const digest = body.subarray(p, p + 32).toString('hex'); p += 32; [count, p] = uleb(body, p); const names = []; for (let i = 0; i < count; i++) { [len, p] = uleb(body, p); if (p + len > body.length) throw new Error('truncated name'); names.push(body.subarray(p, p + len).toString()); p += len; } if (p !== body.length) throw new Error(`${body.length - p} trailing byte(s)`); return { version, digest, names }; } const [cmd, ...rest] = process.argv.slice(2); try { if (cmd === '--write' && rest.length >= 2) { const part = readPartition(rest[0]); const want = part.digest.toString('hex').slice(0, 16); const sec = section(payload(part)); for (const file of rest.slice(1)) { const b = fs.readFileSync(file); if (customSections(b, file).some((s) => s.name === SECTION)) throw new Error(`${file} already carries ${SECTION}`); const got = abiDigestLo64(b, file); if (got !== want) { throw new Error(`${file}'s hwjs.abi stamps partition digest ${got ?? '(none)'}, and ${rest[0]} is ${want}: ` + 'the class list would describe another partition than the one the loader checks it against'); } fs.writeFileSync(`${file}.tmp.${process.pid}`, Buffer.concat([b, sec])); fs.renameSync(`${file}.tmp.${process.pid}`, file); } console.log(`wasm-libc-partition: ${SECTION} v${VERSION}: ${part.names.length} suspend names, ${sec.length} bytes, ` + `partition ${want}…, written to ${rest.length - 1} file(s)`); } else if (cmd === '--check' && rest.length === 2) { const part = readPartition(rest[0]); const secs = customSections(fs.readFileSync(rest[1]), rest[1]).filter((s) => s.name === SECTION); if (secs.length !== 1) throw new Error(`${rest[1]} carries ${secs.length} ${SECTION} sections, not 1`); if (!payload(part).equals(secs[0].body)) throw new Error(`${rest[1]}'s ${SECTION} is not the one ${rest[0]} gives`); console.log(`wasm-libc-partition: check ok: ${part.names.length} suspend names, partition ${part.digest.toString('hex').slice(0, 16)}…`); } else if (cmd === '--print' && rest.length === 1) { const secs = customSections(fs.readFileSync(rest[0]), rest[0]).filter((s) => s.name === SECTION); if (secs.length !== 1) throw new Error(`${rest[0]} carries ${secs.length} ${SECTION} sections, not 1`); const s = parseSection(secs[0].body); console.log(`version ${s.version}\ndigest ${s.digest}\ncount ${s.names ? s.names.length : '?'}`); for (const nm of s.names || []) console.log(nm); } else { console.error('usage: wasm-libc-partition.mjs --write PARTITION FILE... | --check PARTITION FILE | --print FILE'); process.exit(64); } } catch (e) { console.error(`wasm-libc-partition: ${e.message}`); process.exit(1); }