Files
unkernel/js/core/kmod.ts

677 lines
26 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Loadable kernel modules: the host side of the kernel's module backend
// (arch/wasm/kernel/kmod.c, asm/kmod.h; .agents/kernel/kmod.md). The guest
// loads a .ko (insmod, modprobe: an ELF file around the side modules,
// arch/wasm/include/asm/module.h) and the kernel hands this host the side
// module of its form. A module is a wasm side module (wasm-ld -shared
// --experimental-pic, its dylink.0 section first) of the kernel's own form: memory64 and table64 for vmlinux,
// lowered by Binaryen for vmlinux32.wasm, linked with --shared-memory for a
// kernel on a shared memory (SMP). It imports env.memory,
// env.__indirect_function_table, env.__memory_base and env.__table_base
// (and their 32-bit copies when lowered), the kernel's globals by name
// (__stack_pointer, current, on SMP kw_irq_flags and kw_irq_word), and its
// symbols: functions it calls (env.NAME), function addresses (GOT.func.NAME)
// and data addresses (GOT.mem.NAME); a driver of a host device also imports
// that device's unkernel.* functions.
//
// The kernel resolves the symbols (a table index or an address each) and
// picks where the module's data goes and which table slots its functions
// take; this host compiles the image the kernel hands over (from kernel
// memory: the guest read the file), instantiates it with those values and
// writes nothing it was not told to. Every CPU of an SMP kernel has an
// instance of the kernel with its own table, and a KmodHost of its own
// (Kernel for CPU 0, runCpu() for the others): the loading CPU's host links
// the module (its data written, relocated and its constructors run once),
// and every other CPU's host then instantiates it at the same bases from the
// kernel's record (wasm_kmod_sync), as do CPUs started later and a restored
// snapshot's, without writing its data again: a shared-memory module's start
// function skips that behind the flag in its memory; for the others this
// host puts the module's memory back as it was after instantiating.
//
// What each import reads and writes is described in kmod.c. Errors go back
// to the kernel as text (and to this host's log); a thrown exception never
// reaches the kernel. Universal: no node: imports, no DOM.
const ENOENT = 2n, ENOEXEC = 8n, EBADF = 9n, EINVAL = 22n, ENAMETOOLONG = 36n;
/** enum kw_kmod_form (asm/kmod.h). */
const FORM_WASM32 = 0n, FORM_WASM64 = 1n;
/** enum kw_kmod_kind (asm/kmod.h). */
const KIND_FUNC = 1, KIND_FUNC_ADDR = 2, KIND_DATA = 3;
/** KW_KMOD_WEAK; dylink.0's WASM_SYMBOL_BINDING_WEAK. */
const FLAG_WEAK = 1;
/** sizeof(struct kw_kmod_slot) (kmod.c): {index, name}. */
const SLOT_SIZE = 16;
/** Records the host walks at most in one list (a loop in it is a kernel bug). */
const MAX_RECORDS = 65536;
/** The kernel's globals a module may import by name (env.NAME globals). */
const KERNEL_GLOBALS = new Set(["__stack_pointer", "current", "kw_irq_flags", "kw_irq_word"]);
/** The globals this host makes for each module. */
const BASES = new Set(["__memory_base", "__table_base", "__memory_base32", "__table_base32"]);
/** A module the host cannot take: the message goes to the kernel. */
export class KmodError extends Error {
constructor(message: string) {
super(message);
this.name = "KmodError";
}
}
type ValType = "i32" | "i64" | "f32" | "f64" | "v128" | "funcref" | "externref" | "other";
/** One import of a side module, as its import section declares it. */
export interface SideImport {
module: string;
name: string;
kind: "function" | "table" | "memory" | "global" | "tag";
/** A global's type and mutability. */
global?: { type: ValType; mutable: boolean };
/** A memory's or table's limits: 64-bit indices, shared. */
limits?: { address64: boolean; shared: boolean; min: number; max?: number };
}
/** What parseSideModule() reads from a side module's bytes. */
export interface SideModuleInfo {
/** dylink.0 WASM_DYLINK_MEM_INFO: bytes of data and bss, log2 of their alignment, table slots, log2 of their alignment. */
memSize: number;
memAlign: number;
tableSize: number;
tableAlign: number;
/** WASM_DYLINK_NEEDED: libraries it names (the kernel's loader ignores them). */
needed: string[];
imports: SideImport[];
/** "module\0name" of each import dylink.0 marks weak (wasm-ld names a GOT import's symbol env.NAME there). */
weak: Set<string>;
}
/** A bounds-checked reader of a module's bytes. */
class Reader {
pos: number;
end: number;
bytes: Uint8Array;
constructor(bytes: Uint8Array, pos = 0, end = bytes.length) {
this.bytes = bytes;
this.pos = pos;
this.end = end;
}
fail(what: string): never {
throw new KmodError(`malformed module: ${what} at byte ${this.pos}`);
}
byte(): number {
if (this.pos >= this.end) this.fail("unexpected end");
return this.bytes[this.pos++]!;
}
/** An unsigned LEB128 of at most `bits` bits (as a number: exact to 2^53). */
uleb(bits = 32): number {
let r = 0, mul = 1, i = 0;
for (;;) {
const b = this.byte();
r += (b & 0x7f) * mul;
mul *= 128;
if (!(b & 0x80)) break;
if (++i * 7 >= bits) this.fail("LEB128 too long");
}
return r;
}
name(): string {
const n = this.uleb();
if (n > this.end - this.pos) this.fail("name past its section");
let s: string;
try {
s = new TextDecoder("utf-8", { fatal: true }).decode(this.bytes.subarray(this.pos, this.pos + n));
} catch {
this.fail("a name that is not UTF-8");
}
this.pos += n;
return s;
}
sub(): Reader {
const n = this.uleb();
if (n > this.end - this.pos) this.fail("size past its section");
const r = new Reader(this.bytes, this.pos, this.pos + n);
this.pos += n;
return r;
}
}
const VALTYPES: Record<number, ValType> = { 0x7f: "i32", 0x7e: "i64", 0x7d: "f32", 0x7c: "f64", 0x7b: "v128", 0x70: "funcref", 0x6f: "externref" };
function limits(r: Reader, table: boolean): NonNullable<SideImport["limits"]> {
const flags = r.byte();
if (flags & ~0x07) r.fail(`limits flags ${flags}`);
const address64 = !!(flags & 0x04);
const min = r.uleb(address64 ? 64 : 32);
const max = flags & 0x01 ? r.uleb(address64 ? 64 : 32) : undefined;
if (table && flags & 0x02) r.fail("a shared table");
return { address64, shared: !!(flags & 0x02), min, max };
}
function importSection(r: Reader): SideImport[] {
const out: SideImport[] = [];
for (let n = r.uleb(); n > 0; n--) {
const module = r.name(), name = r.name(), kind = r.byte();
if (kind === 0) {
r.uleb();
out.push({ module, name, kind: "function" });
} else if (kind === 1) {
const t = r.byte();
if (t === 0x64 || t === 0x63) r.uleb(); // a typed reference: its heap type
out.push({ module, name, kind: "table", limits: limits(r, true) });
} else if (kind === 2) {
out.push({ module, name, kind: "memory", limits: limits(r, false) });
} else if (kind === 3) {
const t = r.byte(), mut = r.byte();
if (mut > 1) r.fail("global mutability");
out.push({ module, name, kind: "global", global: { type: VALTYPES[t] ?? "other", mutable: mut === 1 } });
} else if (kind === 4) {
r.byte();
r.uleb();
out.push({ module, name, kind: "tag" });
} else r.fail(`import kind ${kind}`);
}
return out;
}
/**
* Read a side module's sections: its dylink.0 section (which must be the
* first) and its imports. Throws KmodError for anything else (not wasm,
* truncated, no dylink.0).
*/
export function parseSideModule(bytes: Uint8Array): SideModuleInfo {
if (bytes.length < 8 || bytes[0] !== 0 || bytes[1] !== 0x61 || bytes[2] !== 0x73 || bytes[3] !== 0x6d)
throw new KmodError("not a wasm module (no \\0asm magic)");
if (bytes[4] !== 1 || bytes[5] || bytes[6] || bytes[7])
throw new KmodError(`wasm binary version ${bytes[4]! | (bytes[5]! << 8)} (not 1)`);
const r = new Reader(bytes, 8);
const info: SideModuleInfo = { memSize: -1, memAlign: 0, tableSize: 0, tableAlign: 0, needed: [], imports: [], weak: new Set() };
let first = true, dylink = false;
while (r.pos < r.end) {
const id = r.byte();
const s = r.sub();
if (id === 0) {
const name = s.name();
if (name === "dylink.0") {
if (!first) throw new KmodError("dylink.0 is not the first section");
dylink = true;
while (s.pos < s.end) {
const type = s.byte();
const sub = s.sub();
if (type === 1) {
info.memSize = sub.uleb();
info.memAlign = sub.uleb();
info.tableSize = sub.uleb();
info.tableAlign = sub.uleb();
} else if (type === 2) {
for (let n = sub.uleb(); n > 0; n--) info.needed.push(sub.name());
} else if (type === 4) {
for (let n = sub.uleb(); n > 0; n--) {
const m = sub.name(), f = sub.name(), flags = sub.uleb();
if (flags & FLAG_WEAK) info.weak.add(`${m}\0${f}`);
}
}
// 3 (export info), 5 (runtime path) and newer kinds: nothing to do.
}
}
} else if (id === 2) {
info.imports = importSection(s);
}
first = false;
}
if (!dylink) throw new KmodError("no dylink.0 section: not a side module (wasm-ld -shared --experimental-pic)");
if (info.memSize < 0) throw new KmodError("dylink.0 has no memory info");
if (info.memAlign > 30 || info.tableAlign > 30) throw new KmodError("dylink.0 alignment out of range");
return info;
}
/** A table with 64-bit indices (BigInt) or 32-bit ones. */
interface AnyTable {
readonly length: number | bigint;
get(index: number | bigint): unknown;
set(index: number | bigint, value: unknown): void;
grow(delta: number | bigint, value?: unknown): number | bigint;
}
/** One symbol import, in the order the kernel resolves them (kw_kmod_import()). */
interface SymImport {
/** Its index among WebAssembly.Module.imports(). */
at: number;
module: string;
name: string;
kind: number;
weak: boolean;
}
interface Compiled {
module: WebAssembly.Module;
info: SideModuleInfo;
symbols: SymImport[];
}
/** struct kw_kmod_rec (kmod.c). */
interface Rec {
addr: number;
next: number;
id: bigint;
name: string;
image: number;
imageLen: number;
mem: number;
memSize: number;
tableBase: number;
tableSize: number;
values: number;
nrValues: number;
slots: number;
nrSlots: number;
}
/** A module instantiated in this CPU's kernel instance. */
interface Loaded {
id: bigint;
name: string;
instance: WebAssembly.Instance;
rec: Rec;
/** The slots of its record set here: table index -> function. */
slots: Map<number, unknown>;
}
export interface KmodHostOptions {
/** This host's CPU, for messages. */
cpu: number;
memory: () => WebAssembly.Memory;
/** The kernel is the wasm64 one (memory64, table64), not the lowered one. */
memory64: () => boolean;
/** This CPU's kernel instance's exports (its table and globals). */
exports: () => WebAssembly.Exports | undefined;
/**
* CPU 0's host imports ("unkernel"), for a module that drives a host
* device. Undefined on the other CPUs, where such an import is a stub that
* ends the session (`fatal`): device imports answer on CPU 0 alone.
*/
hostImports?: () => Record<string, unknown> | undefined;
fatal?: (msg: string) => void;
log: (msg: string) => void;
}
/** A loaded module's public view (Kernel.kmod.loaded, tests). */
export interface KmodLoaded {
id: bigint;
name: string;
mem: number;
memSize: number;
tableBase: number;
tableSize: number;
}
export class KmodHost {
#o: KmodHostOptions;
#pending = new Map<bigint, Compiled>();
#next = 1n;
#loaded = new Map<bigint, Loaded>();
constructor(o: KmodHostOptions) {
this.#o = o;
}
/** What this CPU's instance holds. */
get loaded(): KmodLoaded[] {
return [...this.#loaded.values()].map((l) => ({ id: l.id, name: l.name, mem: l.rec.mem, memSize: l.rec.memSize, tableBase: l.rec.tableBase, tableSize: l.rec.tableSize }));
}
#u8(): Uint8Array {
return new Uint8Array(this.#o.memory().buffer);
}
#dv(): DataView {
return new DataView(this.#o.memory().buffer);
}
#u64(addr: number): number {
const v = this.#dv().getBigUint64(addr, true);
if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new KmodError(`kernel record at 0x${addr.toString(16)}: ${v} out of range`);
return Number(v);
}
#cstr(addr: number, max = 512): string {
if (!addr) return "";
const m = this.#u8();
let end = addr;
while (end < m.length && end - addr < max && m[end]) end++;
return new TextDecoder().decode(m.slice(addr, end));
}
/** Write `msg` into the kernel's buffer (NUL-terminated, cut to fit). */
#err(buf: bigint, len: bigint, msg: string): void {
const n = Number(len);
if (!buf || n <= 0) return;
const b = new TextEncoder().encode(msg);
const k = Math.min(b.length, n - 1);
const m = this.#u8();
m.set(b.subarray(0, k), Number(buf));
m[Number(buf) + k] = 0;
}
#fail(buf: bigint, len: bigint, what: string, e: unknown): bigint {
const msg = e instanceof Error ? e.message : String(e);
this.#o.log(`[host] ${this.#o.cpu ? `CPU ${this.#o.cpu}: ` : ""}kmod: ${what}: ${msg}`);
this.#err(buf, len, msg);
return -ENOEXEC;
}
#rec(addr: number): Rec {
const q = (i: number) => this.#u64(addr + 8 * i);
return {
addr, next: q(0), id: this.#dv().getBigUint64(addr + 8, true), name: this.#cstr(q(2), 64) || "?",
image: q(3), imageLen: q(4), mem: q(5), memSize: q(6), tableBase: q(7), tableSize: q(8),
values: q(9), nrValues: q(10), slots: q(11), nrSlots: q(12),
};
}
#table(): { t: AnyTable; big: boolean } {
const t = this.#o.exports()?.__indirect_function_table as unknown as AnyTable | undefined;
if (!t) throw new KmodError("the kernel exports no __indirect_function_table");
return { t, big: typeof t.length === "bigint" };
}
#grow(top: number): void {
const { t, big } = this.#table();
const n = Number(t.length);
if (top <= n) return;
try {
t.grow(big ? BigInt(top - n) : top - n, null);
} catch (e) {
throw new KmodError(`cannot grow the function table to ${top} (${(e as Error).message}): a kernel linked without --growable-table?`);
}
}
#set(index: number, fn: unknown): void {
const { t, big } = this.#table();
t.set(big ? BigInt(index) : index, fn);
}
#get(index: number): unknown {
const { t, big } = this.#table();
if (index <= 0 || index >= Number(t.length)) return undefined;
return t.get(big ? BigInt(index) : index);
}
/** Compile and classify a module's bytes: they must be of this kernel's form. */
#compile(bytes: Uint8Array): Compiled {
const info = parseSideModule(bytes);
const mem = info.imports.find((i) => i.kind === "memory");
if (!mem || mem.module !== "env" || mem.name !== "memory") throw new KmodError("it does not import env.memory");
const memory = this.#o.memory();
const kernel64 = this.#o.memory64(), shared = typeof SharedArrayBuffer !== "undefined" && memory.buffer instanceof SharedArrayBuffer;
const form = (m64: boolean, sh: boolean) => `${m64 ? "wasm64 (vmlinux)" : "lowered (vmlinux32.wasm)"}${sh ? " on a shared memory (SMP)" : ""}`;
if (mem.limits!.address64 !== kernel64 || mem.limits!.shared !== shared)
throw new KmodError(`it is built for a ${form(mem.limits!.address64, mem.limits!.shared)} kernel, this one is ${form(kernel64, shared)}`);
const table = info.imports.find((i) => i.kind === "table");
if (table && (table.module !== "env" || table.name !== "__indirect_function_table"))
throw new KmodError(`it imports a table ${table.module}.${table.name}`);
if (table && table.limits!.address64 !== this.#table().big)
throw new KmodError(`its table is ${table.limits!.address64 ? "64" : "32"}-bit, the kernel's is not`);
let module: WebAssembly.Module;
try {
// `bytes` is a copy out of the memory: some engines refuse to
// compile from a view of a shared one.
module = new WebAssembly.Module(bytes as BufferSource);
} catch (e) {
throw new KmodError(`does not compile: ${(e as Error).message}`);
}
const imports = WebAssembly.Module.imports(module);
if (imports.length !== info.imports.length) throw new KmodError("the engine sees other imports than its import section");
const symbols: SymImport[] = [];
imports.forEach((imp, at) => {
const d = info.imports[at]!;
if (d.module !== imp.module || d.name !== imp.name) throw new KmodError("the engine sees other imports than its import section");
// wasm-ld names a weak symbol's GOT import env.NAME in dylink.0.
const weak = info.weak.has(`${imp.module}\0${imp.name}`) || (imp.module.startsWith("GOT.") && info.weak.has(`env\0${imp.name}`));
const sym = (kind: number) => symbols.push({ at, module: imp.module, name: imp.name, kind, weak });
if (imp.module === "GOT.mem" && imp.kind === "global") sym(KIND_DATA);
else if (imp.module === "GOT.func" && imp.kind === "global") sym(KIND_FUNC_ADDR);
else if (imp.module === "env" && imp.kind === "function") sym(KIND_FUNC);
else if (imp.module === "env" && (imp.kind === "memory" || imp.kind === "table")) return;
else if (imp.module === "env" && imp.kind === "global" && (BASES.has(imp.name) || KERNEL_GLOBALS.has(imp.name))) return;
else if (imp.module === "unkernel" && imp.kind === "function") return;
else throw new KmodError(`unsupported import ${imp.module}.${imp.name} (${imp.kind})`);
if ((imp.module === "GOT.mem" || imp.module === "GOT.func") && d.global!.type !== "i64" && d.global!.type !== "i32")
throw new KmodError(`${imp.module}.${imp.name} is not an integer global`);
});
return { module, info, symbols };
}
/** Set the slots of the record (its exports that had none) that this host has not set yet. */
#applySlots(l: Loaded, r: Rec): void {
for (let i = 0; i < r.nrSlots; i++) {
const a = r.slots + SLOT_SIZE * i;
const index = this.#u64(a);
if (l.slots.has(index)) continue;
const name = this.#cstr(this.#u64(a + 8));
const fn = l.instance.exports[name];
if (typeof fn !== "function") throw new KmodError(`slot ${index}: ${r.name} exports no function ${name}`);
this.#set(index, fn);
l.slots.set(index, fn);
}
}
/**
* Instantiate `c` as record `r` in this CPU's kernel instance. `first`:
* the module is new (its start function writes its data); otherwise its
* memory already holds its state, which the instance must not change.
*/
#instantiate(c: Compiled, r: Rec, first: boolean): WebAssembly.Instance {
const ex = this.#o.exports()!;
const memory = this.#o.memory();
const { t } = this.#table();
const imports = WebAssembly.Module.imports(c.module);
if (r.nrValues !== c.symbols.length) throw new KmodError(`the kernel resolved ${r.nrValues} symbols, the module has ${c.symbols.length}`);
const obj: Record<string, Record<string, unknown>> = { env: {}, "GOT.mem": {}, "GOT.func": {}, unkernel: {} };
const global = (d: SideImport, v: number) => new WebAssembly.Global({ value: d.global!.type as "i32" | "i64", mutable: d.global!.mutable }, (d.global!.type === "i64" ? BigInt(v) : v) as never);
const symAt = new Map<number, SymImport>(c.symbols.map((s) => [s.at, s]));
const valueAt = new Map<number, number>(c.symbols.map((s, k) => [s.at, this.#u64(r.values + 8 * k)]));
const hx = this.#o.hostImports?.();
imports.forEach((imp, at) => {
const d = c.info.imports[at]!;
const into = obj[imp.module]!;
const sym = symAt.get(at);
if (sym) {
const v = valueAt.get(at)!;
if (sym.kind !== KIND_FUNC) {
into[imp.name] = global(d, v);
} else if (!v) {
if (!sym.weak) throw new KmodError(`function ${imp.name} resolved to 0`);
into[imp.name] = () => {
throw new Error(`kmod ${r.name}: call to the undefined weak function ${imp.name}`);
};
} else {
const fn = this.#get(v);
if (typeof fn !== "function") throw new KmodError(`function ${imp.name} resolved to table slot ${v}, which holds no function`);
into[imp.name] = fn;
}
return;
}
if (imp.module === "unkernel") {
const fn = hx?.[imp.name];
if (this.#o.hostImports && typeof fn !== "function") throw new KmodError(`this host has no unkernel.${imp.name}`);
into[imp.name] = fn ?? (() => {
const msg = `CPU ${this.#o.cpu}: module ${r.name} called unkernel.${imp.name}, which only CPU 0's host serves`;
this.#o.fatal?.(msg);
throw new Error(msg);
});
return;
}
if (imp.kind === "memory") into[imp.name] = memory;
else if (imp.kind === "table") into[imp.name] = t;
else if (imp.name === "__memory_base" || imp.name === "__memory_base32") into[imp.name] = global(d, r.mem);
else if (imp.name === "__table_base" || imp.name === "__table_base32") into[imp.name] = global(d, r.tableBase);
else {
const g = ex[imp.name];
if (!(g instanceof WebAssembly.Global)) throw new KmodError(`the kernel exports no global ${imp.name}`);
into[imp.name] = g;
}
});
// A module on an unshared memory writes its data segments and zeroes
// its bss at every instantiation: keep what it has.
const keep = !first && r.memSize && !(typeof SharedArrayBuffer !== "undefined" && memory.buffer instanceof SharedArrayBuffer)
? this.#u8().slice(r.mem, r.mem + r.memSize) : undefined;
let instance: WebAssembly.Instance;
try {
instance = new WebAssembly.Instance(c.module, obj as WebAssembly.Imports);
} catch (e) {
throw new KmodError(`instantiation failed: ${(e as Error).message}`);
} finally {
if (keep) this.#u8().set(keep, r.mem);
}
return instance;
}
/** Forget a module: its slots become null, so a stale pointer to it traps. */
#drop(l: Loaded): void {
for (let i = 0; i < l.rec.tableSize; i++) this.#set(l.rec.tableBase + i, null);
for (const i of l.slots.keys()) this.#set(i, null);
this.#loaded.delete(l.id);
}
/** The record list (struct kw_kmod_list). */
#list(addr: number): { recs: Rec[]; tableTop: number; tableKernel: number } {
const recs: Rec[] = [];
for (let a = this.#u64(addr); a; ) {
if (recs.length >= MAX_RECORDS) throw new KmodError("the module list does not end");
const r = this.#rec(a);
recs.push(r);
a = r.next;
}
return { recs, tableTop: this.#u64(addr + 8), tableKernel: this.#u64(addr + 16) };
}
/** Bring this host in line with the kernel's list (wasm_kmod_sync). */
sync(listAddr: number): void {
const { recs, tableTop } = this.#list(listAddr);
const live = new Set(recs.map((r) => r.id));
for (const l of [...this.#loaded.values()]) if (!live.has(l.id)) this.#drop(l);
this.#grow(tableTop);
for (const r of recs) {
try {
const l = this.#loaded.get(r.id);
if (l) {
l.rec = r;
this.#applySlots(l, r);
continue;
}
if (!r.image || r.image + r.imageLen > this.#u8().length) throw new KmodError("its image is not in memory");
const c = this.#compile(this.#u8().slice(r.image, r.image + r.imageLen));
const n: Loaded = { id: r.id, name: r.name, rec: r, slots: new Map(), instance: this.#instantiate(c, r, false) };
this.#loaded.set(r.id, n);
this.#applySlots(n, r);
} catch (e) {
throw new KmodError(`${r.name}: ${(e as Error).message}`);
}
}
}
imports(): Record<string, unknown> {
const h = this;
return {
wasm_kmod_form(): bigint {
return h.#o.memory64() ? FORM_WASM64 : FORM_WASM32;
},
wasm_kmod_parse(image: bigint, len: bigint, info: bigint, err: bigint, errlen: bigint): bigint {
try {
const m = h.#u8();
const a = Number(image), n = Number(len);
if (a + n > m.length) throw new KmodError("image out of memory");
const c = h.#compile(m.slice(a, a + n));
const id = h.#next++;
h.#pending.set(id, c);
const dv = h.#dv(), p = Number(info);
const put = (i: number, v: number) => dv.setBigUint64(p + 8 * i, BigInt(v), true);
put(0, c.info.memSize);
put(1, c.info.memAlign);
put(2, c.info.tableSize);
put(3, c.info.tableAlign);
put(4, c.symbols.length);
put(5, Number(h.#table().t.length));
return id;
} catch (e) {
return h.#fail(err, errlen, "parse", e);
}
},
wasm_kmod_import(handle: bigint, index: bigint, name: bigint, size: bigint, flags: bigint): bigint {
const p = h.#pending.get(handle);
const s = p?.symbols[Number(index)];
if (!s) return -EINVAL;
const b = new TextEncoder().encode(s.name);
if (b.length + 1 > Number(size)) return -ENAMETOOLONG;
const m = h.#u8();
m.set(b, Number(name));
m[Number(name) + b.length] = 0;
h.#dv().setBigUint64(Number(flags), s.weak ? BigInt(FLAG_WEAK) : 0n, true);
return BigInt(s.kind);
},
wasm_kmod_link(handle: bigint, rec: bigint, list: bigint, err: bigint, errlen: bigint): bigint {
const p = h.#pending.get(handle);
h.#pending.delete(handle);
if (!p) return -EBADF;
let r: Rec | undefined, n: Loaded | undefined;
try {
r = h.#rec(Number(rec));
h.#grow(h.#list(Number(list)).tableTop);
n = { id: r.id, name: r.name, rec: r, slots: new Map(), instance: h.#instantiate(p, r, true) };
h.#loaded.set(r.id, n);
// Only stores into its own memory; its constructors (which may
// call the kernel, and sleep) are the kernel's to run.
try {
(n.instance.exports.__wasm_apply_data_relocs as (() => void) | undefined)?.();
} catch (e) {
throw new KmodError(`its data relocations trapped: ${(e as Error).message}`);
}
h.#applySlots(n, r);
return 0n;
} catch (e) {
// Nothing of it stays in the table: the kernel hands its slots out again.
if (n) h.#drop(n);
return h.#fail(err, errlen, r?.name ?? "link", e);
}
},
wasm_kmod_export(rec: bigint, name: bigint, len: bigint, kind: bigint, value: bigint): bigint {
try {
const r = h.#rec(Number(rec));
const l = h.#loaded.get(r.id);
if (!l) return -ENOENT;
const n = new TextDecoder().decode(h.#u8().slice(Number(name), Number(name) + Number(len)));
const e = l.instance.exports[n];
const dv = h.#dv();
if (Number(kind) === KIND_DATA) {
if (!(e instanceof WebAssembly.Global)) return -ENOENT;
dv.setBigUint64(Number(value), BigInt(r.mem + Number(e.value)), true);
return 0n;
}
if (typeof e !== "function") return -ENOENT;
let slot: number | undefined;
for (let i = 0; i < r.tableSize && slot === undefined; i++) if (h.#get(r.tableBase + i) === e) slot = r.tableBase + i;
for (const [i, f] of l.slots) if (slot === undefined && f === e) slot = i;
if (slot === undefined) return 1n;
dv.setBigUint64(Number(value), BigInt(slot), true);
return 0n;
} catch (e) {
h.#o.log(`[host] kmod: export lookup: ${(e as Error).message}`);
return -EINVAL;
}
},
wasm_kmod_sync(list: bigint, err: bigint, errlen: bigint): bigint {
try {
h.sync(Number(list));
return 0n;
} catch (e) {
return h.#fail(err, errlen, "sync", e);
}
},
wasm_kmod_drop(handle: bigint): void {
h.#pending.delete(handle);
},
};
}
}