diff --git a/docs/browser.md b/docs/browser.md index 7e7ed7e..89089cf 100644 --- a/docs/browser.md +++ b/docs/browser.md @@ -35,6 +35,7 @@ and `cjFileBlob(path)` also work. has no environment otherwise. Under Node, Java sees the host's environment. - `preloadProgress(done, total)` reports the bytes of the runtime downloaded at start. `total` is 0 while the server has not sent a length; the last call has `done === total`. +- `cheerpjInit({ warmSnapshot: true })` saves a library VM once its calls have warmed it up (see below). - A file Java closes under `/files/downloads/` is downloaded by the browser. `/files/uploads/` exists for files the page adds there. - The browser console gets whole lines, so two `print` calls and a `println` log one @@ -126,3 +127,12 @@ After a VM boots, the worker keeps a snapshot of it, in memory and in IndexedDB (the 4 most recently used). Later runs with the same class path and `cheerpjInit` options start from it instead of booting, in this page and in later visits. + +With `warmSnapshot: true`, `cheerpjRunLibrary` also saves its VM after a call +returns once its calls have loaded at least 200 classes since boot (one javac +compile loads over a thousand) and no library handles are live. Later library +starts with the same class path restore that image, after checking that the +files, missing paths and directory listings those calls used are unchanged; the +first javac compile after it took 2.7 s instead of 5.3 s in Chromium on a +Raspberry Pi 5. An image is about 18 MB. IndexedDB keeps the 2 most recent warm images separately +from boot snapshots. diff --git a/docs/node.md b/docs/node.md index 3246dfd..f7ea5d8 100644 --- a/docs/node.md +++ b/docs/node.md @@ -52,6 +52,7 @@ resolves to the exit code. Its options: - `fetch`: sockets stay inside the VM, and `http:` requests go to this `fetch`, as in the browser - `snapshotDir`: where boot snapshots are kept, or `null` for none (see below) +- `warmSnapshot: true`: save a library VM once its calls have warmed it up (see below) `startLibrary(options)` starts a VM in library mode, and `libraryOf(vm)` is its `lib`, used as `cheerpjRunLibrary`'s result is in the browser. `vm.halt(0)` @@ -67,3 +68,13 @@ reads all of them. The snapshots, about 1 MB each, are kept in `$XDG_CACHE_HOME/java-web/snapshots` (`~/.cache/java-web/snapshots`), the 16 most recently used. Set `JAVA_WEB_SNAPSHOT_DIR` to keep them elsewhere, or to an empty value to turn them off. + +Set `warmSnapshot: true` in `startLibrary` options to save the VM after a call +returns once its calls have loaded at least 200 classes since boot (one javac +compile loads over a thousand) and no library handles are live. A later library +start with the same class path and working directory restores it, after +checking that the files, missing paths and directory listings those calls used +are unchanged; a javac compile from it takes about 1 s instead of 6 s on a +Raspberry Pi 5. An image is about 18 MB; warm snapshots share the snapshot +directory and keep the 2 most recent. They build on boot snapshots, so with +`snapshotDir: null` there are none. diff --git a/src/browser/api.ts b/src/browser/api.ts index b8312c5..723ea3b 100644 --- a/src/browser/api.ts +++ b/src/browser/api.ts @@ -29,6 +29,8 @@ export interface InitOptions { env?: string[]; // load the formats and names of locales other than English localeData?: boolean; + // save and restore library VMs after their first idle call + warmSnapshot?: boolean; // where java-web.js, the worker and jdk/ live; defaults to the script's directory runtime?: string; // receives output instead of the page console element @@ -178,7 +180,7 @@ export function cheerpjInit(options: InitOptions = {}): Promise { }; }); natives = options.natives ?? {}; - send({ type: "init", runtime, app: appBase, props, hostName: options.hostName, env, localeData: !!options.localeData, natives: Object.keys(natives), progress: !!options.preloadProgress }); + send({ type: "init", runtime, app: appBase, props, hostName: options.hostName, env, localeData: !!options.localeData, warmSnapshot: !!options.warmSnapshot, natives: Object.keys(natives), progress: !!options.preloadProgress }); initStarted(ready); return ready; } diff --git a/src/browser/idb.ts b/src/browser/idb.ts index 30e1c11..6f0278c 100644 --- a/src/browser/idb.ts +++ b/src/browser/idb.ts @@ -3,14 +3,15 @@ // changes are written back in batches. import type { MemoryBackend, MemoryEntry } from "../fs.ts"; -import type { SnapshotImage } from "../snapshot.ts"; +import type { SnapshotImage, WarmSnapshotImage } from "../snapshot.ts"; const DB = "java-web", STORE = "files"; // its own database, so adding it needs no version change that open pages would block const SNAPSHOT_DB = "java-web-snapshots"; // snapshot keys, most recently used first const ORDER = "#order"; -const KEEP_SNAPSHOTS = 4; +const WARM_ORDER = "#warm-order"; +const KEEP_SNAPSHOTS = 4, KEEP_WARM_SNAPSHOTS = 2; function request(r: IDBRequest): Promise { return new Promise((resolve, reject) => { @@ -108,3 +109,35 @@ export function saveSnapshot(image: SnapshotImage) { export function dropSnapshot(key: string) { useSnapshot(key, null).catch(() => {}); } + +async function useWarmSnapshot(key: string, image?: WarmSnapshotImage | null) { + const db = await openSnapshots(); + if (!db) return; + const store = db.transaction(STORE, "readwrite").objectStore(STORE); + const id = `warm:${key}`; + if (image) store.put(image, id); + const order = ((await request(store.get(WARM_ORDER))) as string[] | undefined ?? []).filter((k) => k !== id); + if (image !== null) order.unshift(id); + for (const k of [...order.slice(KEEP_WARM_SNAPSHOTS), ...(image === null ? [id] : [])]) store.delete(k); + store.put(order.slice(0, KEEP_WARM_SNAPSHOTS), WARM_ORDER); +} + +export async function loadWarmSnapshot(key: string): Promise { + try { + const db = await openSnapshots(); + if (!db) return null; + const id = `warm:${key}`; + const image = (await request(db.transaction(STORE, "readonly").objectStore(STORE).get(id))) as WarmSnapshotImage | undefined; + if (!image) return null; + useWarmSnapshot(key).catch(() => {}); + return image; + } catch { return null; } +} + +export function saveWarmSnapshot(image: WarmSnapshotImage) { + useWarmSnapshot(image.warmKey, image).catch(() => {}); +} + +export function dropWarmSnapshot(key: string) { + useWarmSnapshot(key, null).catch(() => {}); +} diff --git a/src/browser/protocol.ts b/src/browser/protocol.ts index 87d2d3a..0c24ec5 100644 --- a/src/browser/protocol.ts +++ b/src/browser/protocol.ts @@ -12,6 +12,7 @@ export interface InitMessage { hostName?: string; env: Record; localeData: boolean; + warmSnapshot: boolean; // JNI names of natives the page implements natives: string[]; // report the download of the runtime diff --git a/src/browser/worker.ts b/src/browser/worker.ts index e8876b2..90dabd5 100644 --- a/src/browser/worker.ts +++ b/src/browser/worker.ts @@ -5,8 +5,8 @@ import { MemoryBackend, VFS } from "../fs.ts"; import { JVM, SnapshotError } from "../jvm.ts"; import { HttpBackend, parsePack } from "./http.ts"; -import { dropSnapshot, loadSnapshot, persist, saveSnapshot } from "./idb.ts"; -import type { SnapshotImage } from "../snapshot.ts"; +import { dropSnapshot, dropWarmSnapshot, loadSnapshot, loadWarmSnapshot, persist, saveSnapshot, saveWarmSnapshot } from "./idb.ts"; +import type { SnapshotImage, WarmSnapshotImage } from "../snapshot.ts"; import type { LibraryError, LibraryReply } from "../library.ts"; import type { NativeReply } from "../bridge.ts"; import type { FromWorker, InitMessage, ToWorker } from "./protocol.ts"; @@ -113,6 +113,8 @@ declare const JAVA_WEB_BUILD: string; // in IndexedDB for later loads. A VM changes the image it restores, so each // gets a copy. const snapshots = new Map(); +const warmSnapshots = new Map(); +const droppedWarmSnapshots = new Set(); const keep = (image: SnapshotImage) => { snapshots.delete(image.key); snapshots.set(image.key, image); @@ -143,6 +145,29 @@ const snapshotCache = { }, }; +const warmSnapshotCache = { + load: async (key: string) => { + if (droppedWarmSnapshots.has(key)) return null; + const image = warmSnapshots.get(key) ?? await loadWarmSnapshot(key); + if (!image) return null; + warmSnapshots.delete(key); + warmSnapshots.set(key, image); + return structuredClone(image); + }, + save: (image: WarmSnapshotImage) => { + droppedWarmSnapshots.delete(image.warmKey); + warmSnapshots.delete(image.warmKey); + warmSnapshots.set(image.warmKey, structuredClone(image)); + for (const k of [...warmSnapshots.keys()].slice(0, -2)) warmSnapshots.delete(k); + saveWarmSnapshot(image); + }, + drop: (key: string) => { + warmSnapshots.delete(key); + droppedWarmSnapshots.add(key); + dropWarmSnapshot(key); + }, +}; + // A snapshot that cannot be restored is dropped, and a second VM boots. function retried(start: () => Promise): Promise { return start().catch((e) => { @@ -152,9 +177,10 @@ function retried(start: () => Promise): Promise { }); } -function newVm(classpath: string[], vmId: number): JVM { +function newVm(classpath: string[], vmId: number, library = false): JVM { return new JVM({ snapshots: snapshotCache, + ...(library && config!.warmSnapshot ? { warmSnapshot: true, warmSnapshots: warmSnapshotCache } : {}), fs: vfs!, javaHome: "/jdk", classpath, @@ -226,7 +252,7 @@ self.onmessage = (e: MessageEvent) => { } case "library": { reply(m.id, retried(() => { - const vm = newVm(m.classpath, m.lib); + const vm = newVm(m.classpath, m.lib, true); vms.set(m.lib, vm); return vm.startLibrary(); }).then(() => ({ value: undefined }))); diff --git a/src/fs.ts b/src/fs.ts index f9dbdd4..10aeb10 100644 --- a/src/fs.ts +++ b/src/fs.ts @@ -1,5 +1,7 @@ // Virtual file system the Java side sees. Paths are absolute and use "/". +import { sha256Bytes } from "./natives/crypto.ts"; + export interface Space { bsize: bigint; blocks: bigint; @@ -63,6 +65,18 @@ export interface Backend { access?(path: string, mode: number): boolean; } +export interface WarmTrace { + reads: [string, string][]; + missing: string[]; + lists: [string, string[] | null][]; +} + +const TRACE_LIMIT = 128 << 10; + +function digest(data: Uint8Array): string { + return sha256Bytes(data); +} + export function normalize(path: string): string { if (path.length > 1 && path[0] === "/" && !path.endsWith("/") && !path.endsWith("/.") && !path.endsWith("/..") && !path.includes("//") && !path.includes("/./") && !path.includes("/../")) return path; @@ -80,6 +94,114 @@ export class VFS { private setTimes = new Map(); private mounts: { prefix: string; backend: Backend }[] = []; private hidden: string[] = []; + private warmTrace: WarmTrace | null = null; + private warmTraceSize = 0; + private warmTraceTooLarge = false; + // paths the VM itself changed while tracing: saved as they are at save time + private warmChanged: Set | null = null; + + beginWarmTrace(): boolean { + if (this.warmTrace) return false; + this.warmTrace = { reads: [], missing: [], lists: [] }; + this.warmChanged = new Set(); + this.warmTraceSize = 0; + this.warmTraceTooLarge = false; + return true; + } + + endWarmTrace(): WarmTrace | null { + const trace = this.warmTraceTooLarge ? null : this.warmTrace; + this.warmTrace = null; + this.warmChanged = null; + this.warmTraceTooLarge = false; + return trace; + } + + // What the traced paths hold now. A later start checks against this, so a + // file the warm-up wrote itself (javac's output) does not count as changed. + peekWarmTrace(): WarmTrace | null { + if (!this.warmTrace || this.warmTraceTooLarge) return null; + const changed = this.warmChanged!; + const touched = (p: string) => changed.has(p) || [...changed].some((c) => c.startsWith(p === "/" ? "/" : p + "/")); + const trace: WarmTrace = { reads: [], missing: [], lists: [] }; + const tracing = this.warmTrace; + this.warmTrace = null; + try { + for (const [p, hash] of tracing.reads) { + if (!changed.has(p)) trace.reads.push([p, hash]); + else { + const now = this.read(p); + if (now) trace.reads.push([p, digest(now)]); + else trace.missing.push(p); + } + } + for (const p of tracing.missing) { + const now = changed.has(p) ? this.read(p) : null; + if (now) trace.reads.push([p, digest(now)]); + // a directory the warm-up made itself needs no check + else if (!changed.has(p) || !this.stat(p)) trace.missing.push(p); + } + for (const [p, names] of tracing.lists) trace.lists.push([p, touched(p) ? this.list(p) : names]); + } finally { + this.warmTrace = tracing; + } + return trace; + } + + recordWarmFile(path: string) { + if (!this.warmTrace || path === "/jdk" || path.startsWith("/jdk/")) return; + if (!this.read(path)) this.warmTraceTooLarge = true; + } + + private traceMissing(path: string) { + if (!this.warmTrace || this.warmTraceTooLarge) return; + path = normalize(path); + if (path === "/jdk" || path.startsWith("/jdk/")) return; + if (this.warmTrace.missing.includes(path)) return; + this.warmTraceSize += path.length; + if (this.warmTraceSize > TRACE_LIMIT) this.warmTraceTooLarge = true; + this.warmTrace.missing.push(path); + } + + private traceRead(path: string, data: Uint8Array | null) { + if (!this.warmTrace || this.warmTraceTooLarge) return; + path = normalize(path); + if (!data) return this.traceMissing(path); + if (path === "/jdk" || path.startsWith("/jdk/")) return; + const reads = this.warmTrace.reads; + const old = reads.find(([p]) => p === path); + const hash = digest(data); + // a file that changed while the warm-up ran cannot be checked later + if (old) { + if (old[1] !== hash) this.warmTraceTooLarge = true; + return; + } + this.warmTraceSize += path.length + hash.length; + if (this.warmTraceSize > TRACE_LIMIT) { this.warmTraceTooLarge = true; return; } + reads.push([path, hash]); + } + + validateWarmTrace(trace: WarmTrace): boolean { + return this.warmTraceMismatch(trace) === null; + } + + warmTraceMismatch(trace: WarmTrace): string | null { + for (const [path, hash] of trace.reads) { + if (this.warmTraceDigest(path) !== hash) return `file changed: ${path}`; + } + for (const path of trace.missing) if (this.stat(path) !== null) return `path appeared: ${path}`; + for (const [path, names] of trace.lists) { + const now = this.list(path); + if (now === null ? names !== null : names === null || now.length !== names.length || now.some((n, i) => n !== names[i])) return `directory changed: ${path}`; + } + return null; + } + + private warmTraceDigest(path: string): string | null { + const data = this.read(path); + return data ? digest(data) : null; + } + private watchers = new Set<(path: string, event: "create" | "modify" | "delete") => void>(); watchChanges(watcher: (path: string, event: "create" | "modify" | "delete") => void): () => void { @@ -90,6 +212,7 @@ export class VFS { private changed(path: string, event: "create" | "modify" | "delete") { path = normalize(path); for (const watcher of this.watchers) watcher(path, event); + this.warmChanged?.add(path); } resolvePath(path: string): string { @@ -157,6 +280,7 @@ export class VFS { if (normalize(path) === "/" || this.mountsUnder(path).length > 0 || this.isMountPoint(path)) { return { dir: true, size: 0, mtime: 0 }; } + this.traceMissing(n); return null; } @@ -168,7 +292,9 @@ export class VFS { read(path: string): Uint8Array | null { if (DEVICES.has(normalize(path))) return null; const r = this.resolve(path); - return r ? r[0].read(r[1]) : null; + const data = r ? r[0].read(r[1]) : null; + this.traceRead(path, data); + return data; } canOpenFile(path: string): boolean { @@ -198,18 +324,39 @@ export class VFS { readRange(path: string, off: number, len: number): Uint8Array | null { const r = this.resolve(path); - return r?.[0].readRange?.(r[1], off, len) ?? null; + const data = r?.[0].readRange?.(r[1], off, len) ?? null; + if (this.warmTrace && !path.startsWith("/jdk/") && !this.warmTrace.reads.some(([p]) => p === normalize(path))) this.traceRead(path, r?.[0].read(r[1]) ?? null); + return data; } list(path: string): string[] | null { const r = this.resolve(path); const own = r ? r[0].list(r[1]) : null; const extra = this.mountsUnder(path); - if (!own && extra.length === 0) return this.stat(path)?.dir ? [] : null; + if (!own && extra.length === 0) { + const absent = this.stat(path)?.dir ? [] : null; + this.traceList(path, absent); + return absent; + } const names = [...new Set([...(own ?? []), ...extra])]; - if (!this.hidden.length) return names; + if (!this.hidden.length) { + this.traceList(path, names); + return names; + } const dir = normalize(path); - return names.filter((name) => !this.isHidden(dir === "/" ? `/${name}` : `${dir}/${name}`)); + const visible = names.filter((name) => !this.isHidden(dir === "/" ? `/${name}` : `${dir}/${name}`)); + this.traceList(path, visible); + return visible; + } + + private traceList(path: string, names: string[] | null) { + if (!this.warmTrace || this.warmTraceTooLarge) return; + path = normalize(path); + if (path === "/jdk" || path.startsWith("/jdk/")) return; + if (this.warmTrace.lists.some(([p]) => p === path)) return; + this.warmTraceSize += path.length + (names?.reduce((n, x) => n + x.length, 0) ?? 0); + if (this.warmTraceSize > TRACE_LIMIT) { this.warmTraceTooLarge = true; return; } + this.warmTrace.lists.push([path, names?.slice() ?? null]); } write(path: string, data: Uint8Array): boolean { diff --git a/src/jvm.ts b/src/jvm.ts index 6f518be..589c381 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -24,7 +24,7 @@ import { invokePolymorphic, linkCallSite, resolveConstant } from "./indy.ts"; import { hostNative, jniNames } from "./hostnatives.ts"; import { Library } from "./library.ts"; import { dumpVM, restoreVM, snapshotKey } from "./snapshot.ts"; -import type { SnapshotImage } from "./snapshot.ts"; +import type { SnapshotImage, WarmSnapshotImage } from "./snapshot.ts"; import type { LibraryRequest } from "./library.ts"; import type { HostNative } from "./hostnatives.ts"; import { PROXY_HOST, PROXY_PORT } from "./http-proxy.ts"; @@ -80,6 +80,12 @@ export interface JvmOptions { // forgets a snapshot that could not be restored drop: (key: string) => void; }; + warmSnapshots?: { + load: (key: string) => WarmSnapshotImage | null | Promise; + save: (image: WarmSnapshotImage) => void; + drop: (key: string) => void; + }; + warmSnapshot?: boolean; } // what a resumed thread body yields first, before the run under it returns @@ -106,6 +112,10 @@ const YIELD = (() => { }; })(); +// Classes loaded since boot before a library VM saves a warm snapshot; one +// javac compile loads over a thousand. +const WARM_MIN_CLASSES = 200; + export class JVM { readonly opts: JvmOptions; readonly fs: VFS; @@ -1076,8 +1086,14 @@ export class JVM { // library, one call at a time on the main thread, as in CheerpJ's library mode. startLibrary(): Promise { const t = new JThread(this); + this.libraryStarting = true; return new Promise((resolve, reject) => { this.restore(t, (restored) => { + if (restored && this.warmRestored) { + this.startThread(t); + resolve(); + return; + } t.pushNative(this.libraryGen(t, restored, resolve, reject), null, "V", false); this.startThread(t); }, reject); @@ -1085,6 +1101,12 @@ export class JVM { } private lib: Library | null = null; + private libraryStarting = false; + private warmRestored = false; + private warmSaved = false; + private warmKey = ""; + private warmTraceActive = false; + private warmTraceClasses = 0; // Java objects and calls for library mode, and for natives that call back. get library(): Library { @@ -1106,10 +1128,46 @@ export class JVM { failed(e instanceof Error ? e : new Error(String(e))); return; } + if (this.opts.warmSnapshot && this.libraryStarting && this.snapshots) { + this.warmTraceActive = this.fs.beginWarmTrace(); + this.warmTraceClasses = this.classCount; + } started(); yield* this.library.loop(t); } + libraryIdle(t: JThread) { + const cache = this.opts.warmSnapshots; + if (!this.opts.warmSnapshot || !this.warmTraceActive || this.warmSaved || !cache) return; + // until calls have loaded enough classes there is little warm-up worth saving + if (this.classCount - this.warmTraceClasses < WARM_MIN_CLASSES) return; + try { + if (this.library.handleCount) throw new Error("library handles are live"); + const fds = this.state.get("fds") as { files?: Map } | undefined; + for (const file of fds?.files?.values() ?? []) if (!file.writable && file.path) this.fs.recordWarmFile(file.path); + const trace = this.fs.peekWarmTrace(); + if (!trace) { + this.fs.endWarmTrace(); + this.warmTraceActive = false; + this.debug("warm snapshot busy: access record too large"); + return; + } + const key = this.opts.snapshots ? snapshotKey(this, this.opts.snapshots.build) : ""; + const image = dumpVM(this, t, key, true) as WarmSnapshotImage; + image.warmKey = this.warmKey; + image.trace = trace; + cache.save(image); + this.fs.endWarmTrace(); + this.warmTraceActive = false; + this.warmSaved = true; + for (const c of this.created ?? []) c.bytes = undefined; + this.created = null; + this.debug("warm snapshot saved"); + } catch (e) { + this.debug("warm snapshot busy:", e instanceof Error ? e.message : e); + } + } + // System.initPhase1 to 3, as HotSpot's Threads::create_vm runs them. private *bootGen(t: JThread): NativeGen { const boot = (n: string) => this.loadBootOrFail(n); @@ -1178,6 +1236,48 @@ export class JVM { // with t as its main thread, then starts it; synchronously when load is. private restore(t: JThread, start: (restored: boolean) => void, failed: (e: SnapshotError) => void) { const snaps = this.snapshots; + if (snaps && this.libraryStarting && this.opts.warmSnapshot && this.opts.warmSnapshots) { + const build = snaps.build; + this.warmKey = JSON.stringify([snapshotKey(this, build), this.opts.classpath ?? [], this.opts.cwd ?? "/", this.props.get("sun.java.command") ?? null]); + const useWarm = (image: WarmSnapshotImage | null) => { + if (!image) return false; + let mismatch: string | null; + try { + mismatch = image.warmKey === this.warmKey && image.key === snapshotKey(this, build) ? this.fs.warmTraceMismatch(image.trace) : "key changed"; + } catch (e) { + this.opts.warmSnapshots!.drop(this.warmKey); + this.debug("warm snapshot missed validation:", e instanceof Error ? e.message : e); + return false; + } + if (mismatch !== null) { + this.opts.warmSnapshots!.drop(this.warmKey); + this.debug("warm snapshot missed validation:", mismatch); + return false; + } + try { + restoreVM(this, image, t); + this.warmRestored = true; + this.warmSaved = true; + this.debug("warm snapshot restored"); + start(true); + return true; + } catch (e) { + this.opts.warmSnapshots!.drop(this.warmKey); + this.halt(1); + failed(new SnapshotError(`warm snapshot not restored: ${e instanceof Error ? e.message : e}`, { cause: e })); + return true; + } + }; + const image = this.opts.warmSnapshots.load(this.warmKey); + if (image instanceof Promise) { + image.then((candidate) => { if (!useWarm(candidate)) this.restoreBoot(t, start, failed, snaps); }, () => this.restoreBoot(t, start, failed, snaps)); + } else if (!useWarm(image)) this.restoreBoot(t, start, failed, snaps); + return; + } + this.restoreBoot(t, start, failed, snaps); + } + + private restoreBoot(t: JThread, start: (restored: boolean) => void, failed: (e: SnapshotError) => void, snaps = this.snapshots) { if (!snaps) return start(false); const key = snapshotKey(this, snaps.build); const done = (image: SnapshotImage | null) => { @@ -1216,8 +1316,10 @@ export class JVM { } } } - for (const c of this.created ?? []) c.bytes = undefined; - this.created = null; + if (!this.opts.warmSnapshot || !this.libraryStarting) { + for (const c of this.created ?? []) c.bytes = undefined; + this.created = null; + } if (cmd !== undefined) { this.props.set("sun.java.command", cmd); const system = this.loadBootOrFail("java/lang/System"); diff --git a/src/library.ts b/src/library.ts index 0474a94..5a3d650 100644 --- a/src/library.ts +++ b/src/library.ts @@ -366,6 +366,7 @@ export class Library { const call = me.call; me.call = null; yield* this.serve(t, call); + this.vm.libraryIdle(t); } } diff --git a/src/natives/continuation.ts b/src/natives/continuation.ts index 4c8622c..c1ab24f 100644 --- a/src/natives/continuation.ts +++ b/src/natives/continuation.ts @@ -29,11 +29,14 @@ interface State { frozen: WeakMap; // enterSpecial's native frames: where each mounted continuation starts entries: WeakMap; + active: number; + frozenCount: number; + busy: boolean; } function state(vm: JVM): State { let s = vm.state.get("continuations") as State | undefined; - if (!s) vm.state.set("continuations", (s = { frozen: new WeakMap(), entries: new WeakMap() })); + if (!s) vm.state.set("continuations", (s = { frozen: new WeakMap(), entries: new WeakMap(), active: 0, frozenCount: 0, busy: false })); return s; } @@ -84,21 +87,29 @@ export const natives: Natives = { [`${C}.enterSpecial(Ljdk/internal/vm/Continuation;ZZ)V`]: function* (t, [c, isContinue, isVirtual]): NativeGen { const s = state(t.vm); s.entries.set(t.top as NativeFrame, { cont: c, virtual: isVirtual === 1, held: t.held }); - if (!isContinue) { - const enter = t.vm.loadBoot(C)!.methodMap.get("enter(Ljdk/internal/vm/Continuation;Z)V")!; - yield t.call(enter, c, 0); - return; + s.active++; + s.busy = true; + try { + if (!isContinue) { + const enter = t.vm.loadBoot(C)!.methodMap.get("enter(Ljdk/internal/vm/Continuation;Z)V")!; + yield t.call(enter, c, 0); + return; + } + const frozen = s.frozen.get(c); + if (!frozen) throw new PendingThrow("java/lang/IllegalStateException", "Continuation has no frames"); + s.frozen.delete(c); + s.frozenCount--; + setChunk(t, c, false); + t.frames.push(...frozen); + const top = t.top as Frame; + top.stack[top.sp++] = 0; + top.pc += 3; + yield { kind: "resume" }; + } finally { + s.entries.delete(t.top as NativeFrame); + s.active--; + s.busy = s.active > 0 || s.frozenCount > 0; } - const frozen = s.frozen.get(c); - if (!frozen) throw new PendingThrow("java/lang/IllegalStateException", "Continuation has no frames"); - s.frozen.delete(c); - setChunk(t, c, false); - t.frames.push(...frozen); - // yield0 is at its invokestatic of doYield, which returns 0 when it continues - const top = t.top as Frame; - top.stack[top.sp++] = 0; - top.pc += 3; - yield { kind: "resume" }; }, // Its own frame stays on top, so its result goes to enterSpecial, which then // returns to Continuation.run as if the continuation had finished. @@ -108,7 +119,10 @@ export const natives: Natives = { const why = pinned(t, e); if (why) return why; const cont = state(t.vm).entries.get(t.frames[e] as NativeFrame)!.cont; - state(t.vm).frozen.set(cont, t.frames.splice(e + 1, t.frames.length - e - 2)); + const s = state(t.vm); + s.frozen.set(cont, t.frames.splice(e + 1, t.frames.length - e - 2)); + s.frozenCount++; + s.busy = true; setChunk(t, cont, true); return 0; }, diff --git a/src/natives/crypto.ts b/src/natives/crypto.ts index d88322f..5ccdb2f 100644 --- a/src/natives/crypto.ts +++ b/src/natives/crypto.ts @@ -86,6 +86,18 @@ function sha256(s: Int32Array, b: Int8Array, ofs: number) { s[4] = (s[4] + e) | 0; s[5] = (s[5] + f) | 0; s[6] = (s[6] + g) | 0; s[7] = (s[7] + h) | 0; } +export function sha256Bytes(input: Uint8Array): string { + const size = Math.ceil((input.length + 9) / 64) * 64; + const data = new Int8Array(size); + data.set(input); + data[input.length] = -128; + let bits = BigInt(input.length) * 8n; + for (let i = 0; i < 8; i++, bits >>= 8n) data[size - 1 - i] = Number(bits & 255n); + const state = Int32Array.from([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); + for (let offset = 0; offset < size; offset += 64) sha256(state, data, offset); + return Array.from(state, (x) => (x >>> 0).toString(16).padStart(8, "0")).join(""); +} + // SHA-512 on 32-bit halves: hi and lo words in separate arrays const K512 = (() => { const k = [ diff --git a/src/natives/io.ts b/src/natives/io.ts index 4a6823f..094dc38 100644 --- a/src/natives/io.ts +++ b/src/natives/io.ts @@ -236,6 +236,12 @@ class LazyFile extends OpenFile { } } +export function reopenSnapshotFile(path: string, size: number, pos: number, vfs: VFS): OpenFile { + const file = vfs.canReadRange(path) ? new LazyFile(path, size, vfs) : new OpenFile(path, vfs.read(path) ?? new Uint8Array(), false); + file.pos = pos; + return file; +} + // Read-only files at least this big are read in parts where the backend can. const LAZY_MIN = 256 << 10; diff --git a/src/node.ts b/src/node.ts index da4109c..2cd89fc 100644 --- a/src/node.ts +++ b/src/node.ts @@ -12,7 +12,7 @@ import { VFS } from "./fs.ts"; import type { Backend, Stat } from "./fs.ts"; import { Bridge, nativeTable } from "./bridge.ts"; import { JVM, LM_CLASS, LM_JAR, SnapshotError } from "./jvm.ts"; -import type { SnapshotImage } from "./snapshot.ts"; +import type { SnapshotImage, WarmSnapshotImage } from "./snapshot.ts"; import { hostNatives } from "./hostnatives.ts"; import { ImageBackend, imageFd } from "./image.ts"; import { NodeNet } from "./net-node.ts"; @@ -258,6 +258,8 @@ export interface NodeRunOptions { // where boot snapshots are kept, or null for none; by default // JAVA_WEB_SNAPSHOT_DIR (empty for none), else java-web/snapshots in the user's cache snapshotDir?: string | null; + // save and restore the library VM after its first idle call + warmSnapshot?: boolean; } function fixedInput(data: Uint8Array) { @@ -304,7 +306,7 @@ function defaultSnapshotDir(): string | null { return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "java-web", "snapshots"); } -const KEEP_SNAPSHOTS = 16, KEEP_MARKERS = 256; +const KEEP_SNAPSHOTS = 16, KEEP_WARM_SNAPSHOTS = 2, KEEP_MARKERS = 256; // set by the build of dist/node.js: names its code and image declare const JAVA_WEB_BUILD: string; @@ -331,6 +333,7 @@ function buildId(vfs: VFS, packaged: boolean): string | null { function snapshotCache(dir: string, build: string) { const name = (key: string) => path.join(dir, createHash("sha256").update(key).digest("hex").slice(0, 32)); const file = (key: string) => name(key) + ".snap"; + const warmFile = (key: string) => name(key) + ".warm"; // keeps the most recently used of each kind const prune = (ext: string, keep: number) => { const old = fs.readdirSync(dir).filter((f) => f.endsWith(ext)).map((f) => path.join(dir, f)) @@ -361,6 +364,24 @@ function snapshotCache(dir: string, build: string) { } }, drop: (key: string) => fs.rmSync(file(key), { force: true }), + loadWarm: (key: string) => { + try { + const image = deserialize(fs.readFileSync(warmFile(key))); + const now = new Date(); + fs.utimesSync(warmFile(key), now, now); + return image as WarmSnapshotImage; + } catch { return null; } + }, + dropWarm: (key: string) => fs.rmSync(warmFile(key), { force: true }), + saveWarm: (image: WarmSnapshotImage) => { + const target = warmFile(image.warmKey), tmp = `${target}.${process.pid}.tmp`; + try { + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(tmp, serialize(image)); + fs.renameSync(tmp, target); + } finally { fs.rmSync(tmp, { force: true }); } + prune(".warm", KEEP_WARM_SNAPSHOTS); + }, save: (image: SnapshotImage) => { const tmp = `${file(image.key)}.${process.pid}.tmp`; try { @@ -394,8 +415,12 @@ function nodeVm(o: NodeRunOptions): JVM { }); const snapDir = o.snapshotDir === undefined ? defaultSnapshotDir() : o.snapshotDir; const build = snapDir ? buildId(vfs, packaged) : null; + const cache = snapDir && build ? snapshotCache(snapDir, build) : null; const vm: JVM = new JVM({ - ...(snapDir && build ? { snapshots: snapshotCache(snapDir, build) } : {}), + ...(cache ? { snapshots: cache } : {}), + ...(o.warmSnapshot && cache ? { warmSnapshot: true, warmSnapshots: { + load: cache.loadWarm, save: cache.saveWarm, drop: cache.dropWarm, + } } : {}), fs: vfs, javaHome: "/jdk", localeData: o.localeData, diff --git a/src/snapshot.ts b/src/snapshot.ts index fd78a76..d2661dd 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -8,8 +8,9 @@ import { parseClass } from "./classfile.ts"; import type { JVM } from "./jvm.ts"; import { platformProperties, vmProperties } from "./natives/misc.ts"; import { restorePending, restoreReference } from "./natives/ref.ts"; -import { streams } from "./natives/io.ts"; import { MAX_HEAP } from "./runtime.ts"; +import type { WarmTrace } from "./fs.ts"; +import { reopenSnapshotFile, OpenFile, streams } from "./natives/io.ts"; import { JArray, JClass, JField, JMethod, JObject, Monitor } from "./runtime.ts"; import { Frame, JThread, NativeFrame, STATUS_RUNNABLE } from "./thread.ts"; import type { NativeGen } from "./thread.ts"; @@ -21,6 +22,11 @@ export interface SnapshotImage { threads: ThreadRec[]; } +export interface WarmSnapshotImage extends SnapshotImage { + warmKey: string; + trace: WarmTrace; +} + interface ClassRec { kind: "prim" | "array" | "boot" | "bytes"; name: string; @@ -41,6 +47,7 @@ interface ClassRec { vmMembers: unknown; nestHost: unknown; links: [string, unknown][]; + caches: [string, unknown][]; } interface VmRec { @@ -85,7 +92,7 @@ export function snapshotKey(vm: JVM, build: string): string { const WAIT0 = "java/lang/Object.wait0(J)V"; const REF_WAIT = "java/lang/ref/Reference.waitForReferencePendingList()V"; // vm.state entries rebuilt on demand rather than saved -const TRANSIENT = new Set(["stdin", "refs", "socks"]); +const TRANSIENT = new Set(["stdin", "refs", "socks", "continuations"]); class Encoder { private twins = new Map(); @@ -244,7 +251,7 @@ class Decoder { // The image of a VM whose boot just finished on main, which keeps running // and is not saved itself. -export function dumpVM(vm: JVM, main: JThread, key: string): SnapshotImage { +export function dumpVM(vm: JVM, main: JThread, key: string, library = false): SnapshotImage { const classes = vm.created!; const others = [...vm.threads].filter((t) => t !== main); const e = new Encoder(classes, [main, ...others]); @@ -262,6 +269,7 @@ export function dumpVM(vm: JVM, main: JThread, key: string): SnapshotImage { vmMembers: e.enc(c.vmMembers, `${p}.vmMembers`), nestHost: e.enc(c.nestHost, `${p}.nestHost`), links: c.methods.filter((m) => m.link).map((m) => [m.key, e.enc(m.link, `${p}.${m.key}.link`)]), + caches: c.methods.filter((m) => m.cache).map((m) => [m.key, e.enc(m.cache, `${p}.${m.key}.cache`)]), }; if (c.initThread || c.initWaiters.length) throw new Error(`snapshot: ${c.name} is being initialized`); if (rec.kind === "prim") rec.desc = c.prim!; @@ -290,13 +298,14 @@ export function dumpVM(vm: JVM, main: JThread, key: string): SnapshotImage { classCount: vm.classCount, state: [...s].filter(([k, x]) => { if (k === "socks" && x.socks.size) throw new Error("snapshot: a socket is open"); + if (k === "continuations" && x.busy) throw new Error("snapshot: a continuation is active"); if (k === "fds" && [...x.files.values()].some(streams)) throw new Error("snapshot: a host file that streams is open"); return !TRANSIENT.has(k) && !k.startsWith("parked:"); - }).map(([k, v]) => [k, e.enc(v, `state.${k}`)]), + }).map(([k, v]) => [k, k === "fds" ? snapshotFds(v) : e.enc(v, `state.${k}`)]), pending: e.enc(refs?.pending ?? [], "refs.pending"), mem: { buf: mem.u8.slice(0, mem.top), top: mem.top, sizes: e.enc(mem.sizes, "mem"), free: e.enc(mem.free, "mem") }, }; - const threads = others.map((t): ThreadRec => { + const threadRec = (t: JThread, isMain = false): ThreadRec => { const p = `thread ${t.name}`; const frames = t.frames.map((f, i) => { if (f instanceof Frame) { @@ -304,6 +313,7 @@ export function dumpVM(vm: JVM, main: JThread, key: string): SnapshotImage { return { $: "Fr", m: e.enc(f.m, p), pc: f.pc, sp: f.sp, l: e.enc(f.locals, p), s: e.enc(f.stack, p), k: e.enc(f.lock, p), nl: f.needLock }; } if (f.input !== undefined || f.thrown) throw new Error(`snapshot: native frame with a pending value in ${p}`); + if (library && isMain && i === 0 && f.m === null) return { $: "library" }; if (i === 0 && f.m === null) return { $: "body" }; const key = f.m ? `${f.m.cls.name}.${f.m.key}` : "vm"; if (key === REF_WAIT) return { $: "native", m: e.enc(f.m, p) }; @@ -326,8 +336,21 @@ export function dumpVM(vm: JVM, main: JThread, key: string): SnapshotImage { scopedValueCache: e.enc(t.scopedValueCache, p), frames, }; - }); - return { key, classes: classRecs, vm: vmRec, threads: [{ obj: e.enc(main.obj, "main") } as ThreadRec, ...threads] }; + }; + const threads = others.map((t) => threadRec(t)); + return { key, classes: classRecs, vm: vmRec, threads: [library ? threadRec(main, true) : { obj: e.enc(main.obj, "main") } as ThreadRec, ...threads] }; +} + +function snapshotFds(value: unknown): unknown { + const table = value as { next: number; files: Map }; + const files: [number, { path: string; pos: number; size: number }][] = []; + for (const [id, file] of table.files) { + if (!(file instanceof OpenFile) || file.writable || file.dirty || file.path === "" || (file as any).host !== undefined || (file.contents as any).host !== undefined) { + throw new Error("snapshot: a file is busy"); + } + files.push([id, { path: file.path, pos: file.pos, size: file.size }]); + } + return { next: table.next, files }; } // A waiter woken as if spuriously: takes its monitor back with the count it gave up. @@ -356,6 +379,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { if (cf.name !== r.cfName) cf = { ...cf, name: r.cfName!, renamedFrom: cf.name }; const sup = r.superclass === null ? null : classes[r.superclass!]; c = vm.defineLinked(cf, d.dec(r.loader), sup, r.interfaces!.map((i) => classes[i]), r.hidden); + c.bytes = r.bytes; } if (!c || c.name !== r.name) throw new Error(`snapshot: ${r.name} came back as ${c?.name}`); classes.push(c); @@ -372,6 +396,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { c.vmMembers = d.dec(r.vmMembers); c.nestHost = d.dec(r.nestHost); for (const [k, l] of r.links) c.methodMap.get(k)!.link = d.dec(l); + for (const [k, cache] of r.caches ?? []) c.methodMap.get(k)!.cache = d.dec(cache); }); d.flush(); const v = image.vm; @@ -385,7 +410,13 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { for (const [k, s] of d.dec(v.interned) as Map) interned.set(k, s); (vm as any).hashSeed = v.hashSeed; vm.classCount = v.classCount; - for (const [k, x] of v.state) vm.state.set(k, d.dec(x)); + for (const [k, x] of v.state) { + if (k === "fds") { + const fds = x as { next: number; files: [number, { path: string; pos: number; size: number }][] }; + const files = new Map(fds.files.map(([id, f]) => [id, reopenSnapshotFile(f.path, f.size, f.pos, vm.fs)])); + vm.state.set(k, { next: fds.next, files }); + } else vm.state.set(k, d.dec(x)); + } const mem = vm.mem as any; mem.buf = new ArrayBuffer(Math.max(mem.buf.byteLength, v.mem.buf.length)); mem.u8 = new Uint8Array(mem.buf); @@ -396,8 +427,17 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { mem.free = d.dec(v.mem.free); d.flush(); - main.obj = d.dec(image.threads[0].obj); + const mainRec = image.threads[0]; + main.obj = d.dec(mainRec.obj); main.obj!.x = main; + if (mainRec.frames) { + for (const f of mainRec.frames as any[]) { + if (f.$ === "library") { + const gen = vm.library.loop(main); + main.frames.push(new NativeFrame(gen, null, "V", false)); + } else throw new Error(`snapshot: unsupported main frame ${f.$}`); + } + } image.threads.slice(1).forEach((r, i) => { const t = others[i]; t.obj = d.dec(r.obj); diff --git a/test/warm-snapshot.test.ts b/test/warm-snapshot.test.ts new file mode 100644 index 0000000..c875f1b --- /dev/null +++ b/test/warm-snapshot.test.ts @@ -0,0 +1,72 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { startLibrary } from "../src/node.ts"; +import { hotspot } from "../scripts/hotspot.ts"; + +const root = join(import.meta.dirname, ".."); +const classes = join(root, "build", "test-warm-snapshot"); +mkdirSync(classes, { recursive: true }); +execFileSync(hotspot("javac"), ["-d", classes, join(root, "test", "warm-snapshot", "WarmJavac.java")]); + +const dirs: string[] = []; +after(() => dirs.forEach((dir) => rmSync(dir, { recursive: true, force: true }))); + +function scratch() { + const dir = mkdtempSync(join(tmpdir(), "java-web-warm-")); + dirs.push(dir); + return dir; +} + +async function compile(cache: string, source: string, missing: string) { + const out = join(cache, "out"); + let log = ""; + const error = console.error; + console.error = (...args: unknown[]) => { log += `${args.join(" ")}\n`; }; + let vm: Awaited> | undefined; + try { + vm = await startLibrary({ classpath: [classes], snapshotDir: cache, warmSnapshot: true, debug: true }); + return { result: await vm.callStatic("WarmJavac", "compile", [source, missing, out]), log }; + } finally { + vm?.halt(0); + console.error = error; + } +} + +test("library warm snapshots restore and validate reads and missing paths", async () => { + const dir = scratch(); + const src = join(dir, "Result.java"); + const missing = join(dir, "not-created", "Absent.class"); + const source = (value: number) => `public class Result { public static int value() { return ${value}; } }\n`; + writeFileSync(src, source(7)); + const reference7 = join(dir, "reference7"); + mkdirSync(reference7); + execFileSync(hotspot("javac"), ["-g:none", "-d", reference7, src]); + const expected7 = readFileSync(join(reference7, "Result.class")).toString("base64"); + const first = await compile(dir, src, missing); + assert.equal(first.result, expected7); + assert.equal(readdirSync(dir).filter((f) => f.endsWith(".warm")).length, 1, first.log); + + const restored = await compile(dir, src, missing); + assert.equal(restored.result, expected7); + assert.match(restored.log, /warm snapshot restored/); + + writeFileSync(src, source(8)); + const reference8 = join(dir, "reference8"); + mkdirSync(reference8); + execFileSync(hotspot("javac"), ["-g:none", "-d", reference8, src]); + const expected8 = readFileSync(join(reference8, "Result.class")).toString("base64"); + const changed = await compile(dir, src, missing); + assert.equal(changed.result, expected8); + assert.match(changed.log, /warm snapshot missed validation/); + + mkdirSync(join(dir, "not-created")); + writeFileSync(missing, new Uint8Array()); + const created = await compile(dir, src, missing); + assert.equal(created.result, expected8); + assert.match(created.log, /warm snapshot missed validation/); + +}); diff --git a/test/warm-snapshot/WarmJavac.java b/test/warm-snapshot/WarmJavac.java new file mode 100644 index 0000000..e2232e2 --- /dev/null +++ b/test/warm-snapshot/WarmJavac.java @@ -0,0 +1,37 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.net.URI; +import java.util.Base64; +import java.util.List; +import javax.tools.JavaFileObject; +import javax.tools.FileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +public class WarmJavac { + public static String compile(String sourcePath, String missing, String outDir) throws Exception { + String source = Files.readString(Path.of(sourcePath)); + Files.exists(Path.of(missing)); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + JavaFileObject input = new SimpleJavaFileObject(URI.create("string:///Result.java"), JavaFileObject.Kind.SOURCE) { + @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return source; } + }; + var compiler = ToolProvider.getSystemJavaCompiler(); + var files = compiler.getStandardFileManager(null, null, null); + var output = new SimpleJavaFileObject(URI.create("memory:///Result.class"), JavaFileObject.Kind.CLASS) { + @Override public OutputStream openOutputStream() { return bytes; } + }; + var manager = new javax.tools.ForwardingJavaFileManager<>(files) { + @Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) { return output; } + }; + boolean ok = compiler.getTask(null, manager, null, List.of("-g:none", "-classpath", ""), null, List.of(input)).call(); + if (!ok) return "compile failed"; + // output the warm-up itself writes must not make the next start miss + Path out = Path.of(outDir); + Files.createDirectories(out); + Files.write(out.resolve("Result.class"), bytes.toByteArray()); + return Base64.getEncoder().encodeToString(bytes.toByteArray()); + } +} diff --git a/types/node.d.ts b/types/node.d.ts index 9e873af..24afbf2 100644 --- a/types/node.d.ts +++ b/types/node.d.ts @@ -33,6 +33,8 @@ export interface NodeRunOptions { // where boot snapshots are kept, or null for none; by default // JAVA_WEB_SNAPSHOT_DIR (empty for none), else java-web/snapshots in the user's cache snapshotDir?: string | null; + /** Save and restore the library VM after its first idle call. */ + warmSnapshot?: boolean; } // A running VM, as startLibrary returns it.