From 99fda3eff1811b4c370d8df1a8ac76c2d09af367 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:44:13 -0600 Subject: [PATCH 1/8] Decode constant pool strings, line tables and method attributes on first use instead of when a class loads --- src/classfile.ts | 111 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 76 insertions(+), 35 deletions(-) diff --git a/src/classfile.ts b/src/classfile.ts index 2bd2656..4f45173 100644 --- a/src/classfile.ts +++ b/src/classfile.ts @@ -16,13 +16,15 @@ export interface CpEntry { b: number; } -// Utf8 and numeric values live in values. Other entries keep a and b as two -// u16 in one word of ab. +// Numeric values live in values. Other entries keep a and b as two u16 in one +// word of ab. A Utf8 entry keeps the offset of its bytes in ab, and its string +// in values once something asks for it. export interface ConstantPool { length: number; values: (string | number | bigint | undefined)[]; tags: Uint8Array; ab: Uint32Array; + bytes: Uint8Array; } export interface ExceptionEntry { @@ -32,15 +34,45 @@ export interface ExceptionEntry { catchType: number; } -export interface Code { - maxStack: number; - maxLocals: number; - code: Uint8Array; - handlers: ExceptionEntry[]; - // pairs of (start pc, line), sorted by pc - lines: number[] | null; +export class Code { + readonly maxStack: number; + readonly maxLocals: number; + readonly code: Uint8Array; + readonly handlers: ExceptionEntry[]; // raw LocalVariableTable attribute body, parsed on demand - localVars: Uint8Array | null; + readonly localVars: Uint8Array | null; + private rawLines: Uint8Array[] | null; + private parsedLines: number[] | null | undefined; + constructor(maxStack: number, maxLocals: number, code: Uint8Array, handlers: ExceptionEntry[], rawLines: Uint8Array[] | null, localVars: Uint8Array | null) { + this.maxStack = maxStack; + this.maxLocals = maxLocals; + this.code = code; + this.handlers = handlers; + this.rawLines = rawLines; + this.localVars = localVars; + } + // pairs of (start pc, line), sorted by pc + get lines(): number[] | null { + if (this.parsedLines !== undefined) return this.parsedLines; + let lines: number[] | null = null; + for (const body of this.rawLines ?? []) { + const lr = new Reader(body); + lines ??= []; + for (let n = lr.u2(); n > 0; n--) lines.push(lr.u2(), lr.u2()); + } + this.rawLines = null; + if (lines && lines.length > 2) { + let sorted = true; + for (let i = 2; i < lines.length; i += 2) if (lines[i] < lines[i - 2]) { sorted = false; break; } + if (!sorted) { + const pairs: [number, number][] = []; + for (let i = 0; i < lines.length; i += 2) pairs.push([lines[i], lines[i + 1]]); + pairs.sort((a, b) => a[0] - b[0]); + lines = pairs.flat(); + } + } + return this.parsedLines = lines; + } } export interface Member { @@ -145,13 +177,27 @@ export function encodeMutf8(s: string): Uint8Array { return Uint8Array.from(out); } +const NO_ATTRS = new Map(); + function readMember(r: Reader, cp: ClassFile["cp"]): Member { const access = r.u2(); const name = utf8(cp, r.u2()); const desc = utf8(cp, r.u2()); - const attrs = readAttrs(r, cp); - const raw = attrs.get("Code"); - return { access, name, desc, attrs, code: raw ? readCode(raw, cp) : null }; + let attrs = NO_ATTRS; + let code: Code | null = null; + for (let n = r.u2(); n > 0; n--) { + const attr = utf8(cp, r.u2()); + const length = r.u4(); + if (attr === "Code") { + const end = r.pos + length; + code = readCode(r, cp); + r.pos = end; + } else { + if (attrs === NO_ATTRS) attrs = new Map(); + attrs.set(attr, r.slice(length)); + } + } + return { access, name, desc, attrs, code }; } function readAttrs(r: Reader, cp: ClassFile["cp"]) { @@ -163,8 +209,7 @@ function readAttrs(r: Reader, cp: ClassFile["cp"]) { return attrs; } -function readCode(raw: Uint8Array, cp: ClassFile["cp"]): Code { - const r = new Reader(raw); +function readCode(r: Reader, cp: ClassFile["cp"]): Code { const maxStack = r.u2(); const maxLocals = r.u2(); const code = r.slice(r.u4()); @@ -172,29 +217,22 @@ function readCode(raw: Uint8Array, cp: ClassFile["cp"]): Code { for (let n = r.u2(); n > 0; n--) { handlers.push({ start: r.u2(), end: r.u2(), handler: r.u2(), catchType: r.u2() }); } - let lines: number[] | null = null; + let lines: Uint8Array[] | null = null; let localVars: Uint8Array | null = null; - for (const [name, body] of readAttrs(r, cp)) { + for (let n = r.u2(); n > 0; n--) { + const name = utf8(cp, r.u2()); + const body = r.slice(r.u4()); if (name === "LocalVariableTable") localVars = body; - if (name !== "LineNumberTable") continue; - const lr = new Reader(body); - lines ??= []; - for (let n = lr.u2(); n > 0; n--) lines.push(lr.u2(), lr.u2()); - } - if (lines && lines.length > 2) { - const pairs: [number, number][] = []; - for (let i = 0; i < lines.length; i += 2) pairs.push([lines[i], lines[i + 1]]); - pairs.sort((a, b) => a[0] - b[0]); - lines = pairs.flat(); + else if (name === "LineNumberTable") (lines ??= []).push(body); } - return { maxStack, maxLocals, code, handlers, lines, localVars }; + return new Code(maxStack, maxLocals, code, handlers, lines, localVars); } export function cpEntry(cp: ClassFile["cp"], i: number): CpEntry | undefined { const tag = cp.tags[i]; if (!tag) return undefined; - const value = cp.values[i]; - return { tag, value, a: cp.ab[i] >>> 16, b: cp.ab[i] & 0xffff }; + if (tag === Tag.Utf8) return { tag, value: utf8(cp, i), a: 0, b: 0 }; + return { tag, value: cp.values[i], a: cp.ab[i] >>> 16, b: cp.ab[i] & 0xffff }; } export function cpTag(cp: ClassFile["cp"], i: number): number { return cp.tags[i]; } @@ -204,8 +242,10 @@ export function cpValue(cp: ClassFile["cp"], i: number): number | bigint | undef export function utf8(cp: ClassFile["cp"], i: number): string { const s = cp.values[i]; - if (typeof s !== "string") throw new ClassFormatError(`bad utf8 index ${i}`); - return s; + if (typeof s === "string") return s; + if (cp.tags[i] !== Tag.Utf8) throw new ClassFormatError(`bad utf8 index ${i}`); + const at = cp.ab[i], b = cp.bytes; + return cp.values[i] = decodeMutf8(b.subarray(at + 2, at + 2 + ((b[at] << 8) | b[at + 1]))); } export function className(cp: ClassFile["cp"], i: number): string { @@ -240,12 +280,13 @@ function parseBody(r: Reader, preview: boolean): ClassFile { values: new Array(count), tags: new Uint8Array(count), ab: new Uint32Array(count), + bytes: r.bytes, }; for (let i = 1; i < count; i++) { const tag = r.u1(); - let value: CpEntry["value"], a = 0, b = 0; + let value: CpEntry["value"], a = 0, b = 0, start = 0; switch (tag) { - case Tag.Utf8: value = decodeMutf8(r.slice(r.u2())); break; + case Tag.Utf8: start = r.pos; r.pos += 2 + r.view.getUint16(r.pos); break; case Tag.Integer: value = r.i4(); break; case Tag.Float: value = r.view.getFloat32(r.pos); r.pos += 4; break; case Tag.Long: value = r.view.getBigInt64(r.pos); r.pos += 8; break; @@ -260,7 +301,7 @@ function parseBody(r: Reader, preview: boolean): ClassFile { } cp.tags[i] = tag; if (value !== undefined) cp.values[i] = value; - cp.ab[i] = a << 16 | b; + cp.ab[i] = tag === Tag.Utf8 ? start : a << 16 | b; if (tag === Tag.Long || tag === Tag.Double) i++; } const access = r.u2(); From 972a6005028348a0f6fe33a8718e5734391936d8 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:59:58 -0600 Subject: [PATCH 2/8] Share parsed method descriptors between methods and look up intrinsics only in classes that have them --- src/jvm.ts | 5 ++++- src/runtime.ts | 23 +++++++++++++++++------ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/jvm.ts b/src/jvm.ts index e3721b2..8b99130 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -99,6 +99,8 @@ const RESUMED = Object.freeze({ kind: "resume" }) as unknown as Request; // LauncherHelper launch modes export const LM_CLASS = 1, LM_JAR = 2; +const intrinsicClasses = new Set(Object.keys(intrinsics).map((k) => k.slice(0, k.indexOf(".")))); + // Rejects run and startLibrary when a snapshot could not be restored. The // snapshot is dropped, so a new VM with the same options boots. export class SnapshotError extends Error {} @@ -333,9 +335,10 @@ export class JVM { } c.instanceSlots = slot; c.template = template; + const withIntrinsics = loader === null && intrinsicClasses.has(cf.name); const poly = cf.name === "java/lang/invoke/MethodHandle" || cf.name === "java/lang/invoke/VarHandle"; for (const [i, mm] of cf.methods.entries()) { - const intrinsic = loader === null ? intrinsics[`${cf.name}.${mm.name}${mm.desc}`] : undefined; + const intrinsic = withIntrinsics ? intrinsics[`${cf.name}.${mm.name}${mm.desc}`] : undefined; const m = new JMethod(c, intrinsic ? { ...mm, code: null, access: mm.access | ACC_NATIVE } : mm); if (intrinsic) { m.native = intrinsic; diff --git a/src/runtime.ts b/src/runtime.ts index 8bbdad1..cfdb205 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -46,6 +46,19 @@ export function parseMethodDesc(desc: string): { params: string[]; ret: string } return { params, ret: desc.slice(i + 1) }; } +// parsed descriptors, shared by the methods that have them; slots exclude the receiver +const shapes = new Map(); +function methodShape(desc: string) { + let s = shapes.get(desc); + if (s === undefined) { + const { params, ret } = parseMethodDesc(desc); + let slots = 0; + for (const p of params) slots += isWide(p) ? 2 : 1; + shapes.set(desc, s = { params, ret, slots }); + } + return s; +} + export function isWide(desc: string) { return desc === "J" || desc === "D"; } @@ -128,12 +141,10 @@ export class JMethod { this.isAbstract = (m.access & ACC_ABSTRACT) !== 0; this.isPrivate = (m.access & ACC_PRIVATE) !== 0; this.isSynchronized = (m.access & ACC_SYNCHRONIZED) !== 0; - const { params, ret } = parseMethodDesc(m.desc); - this.params = params; - this.ret = ret; - let slots = this.isStatic ? 0 : 1; - for (const p of params) slots += isWide(p) ? 2 : 1; - this.argSlots = slots; + const shape = methodShape(m.desc); + this.params = shape.params; + this.ret = shape.ret; + this.argSlots = shape.slots + (this.isStatic ? 0 : 1); } // flags as fields: these are read on every call readonly isStatic: boolean; From ddcae2abb3d62652e3985b6f5e3dffbf6e63cbb9 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:08:53 -0600 Subject: [PATCH 3/8] Read jimage strings in JS: javac's first compile from a boot snapshot is about 6% faster --- src/natives/strings.ts | 52 +++++++++++++++++++++++++++++++++++++ test/java/ImageStrings.java | 19 ++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 test/java/ImageStrings.java diff --git a/src/natives/strings.ts b/src/natives/strings.ts index 3e5a58c..7d2db1c 100644 --- a/src/natives/strings.ts +++ b/src/natives/strings.ts @@ -3,6 +3,7 @@ // collapses them. They follow AbstractStringBuilder.append, // ensureCapacityNewCoder, newCapacity and String.(AbstractStringBuilder, // Void) of the pinned JDK, so buffer growth and string coders match. +// The jimage string reader is here too. import { JArray, MAX_HEAP, newArrayData } from "../runtime.ts"; import type { JClass, JObject } from "../runtime.ts"; @@ -158,7 +159,58 @@ export function concatStrings(t: JThread, pc: number, parts: (JObject | null)[]) return str; } +// ImageStringsReader.stringFromByteBuffer(buffer, offset): the modified UTF-8 +// string at offset, read from the jimage's buffer. javac lists thousands of +// image locations, and the Java version gets each byte through a ByteBuffer. +function imageString(t: JThread, args: any[]): JObject { + const vm = t.vm; + const buf: JObject | null = args[0], offset: number = args[1]; + if (buf === null) throw new PendingThrow("java/lang/NullPointerException"); + const limit = buf.f[vm.slotOf("java/nio/Buffer", "limit")] as number; + const hb = buf.f[vm.slotOf("java/nio/ByteBuffer", "hb")] as JArray | null; + let bytes: ArrayLike, base: number; + if (hb) { + bytes = hb.a as Int8Array; + base = buf.f[vm.slotOf("java/nio/ByteBuffer", "offset")] as number; + } else { + bytes = vm.mem.u8; + base = Number(buf.f[vm.slotOf("java/nio/Buffer", "address")] as bigint); + } + if (offset < 0) { + throw new PendingThrow("java/lang/IndexOutOfBoundsException", `Index ${offset} out of bounds for length ${limit}`); + } + let end = offset, ascii = true; + for (; end < limit && bytes[base + end] !== 0; end++) if (bytes[base + end] & 0x80) ascii = false; + if (end === limit) throw new PendingThrow("java/lang/InternalError", "No terminating zero byte for modified UTF-8 byte sequence"); + slots(vm); + if (ascii) { + const value = newBytes(end - offset); + for (let i = offset; i < end; i++) value[i - offset] = bytes[base + i]; + const s = vm.newObject(strClass); + fill(vm, s, value, 0); + return s; + } + let text = ""; + for (let i = offset; i < end; i++) { + let ch = bytes[base + i] & 0xff; + if (ch & 0x80) { + let uch = ch & 0x7f, mask = 0x40; + while (uch & mask) { + ch = bytes[base + ++i] & 0xff; + if ((ch & 0xc0) !== 0x80) throw new PendingThrow("java/lang/InternalError", `Bad continuation in modified UTF-8 byte sequence: ${(ch << 24) >> 24}`); + uch = ((uch & ~mask) << 6) | (ch & 0x3f); + mask <<= 5; + } + if ((uch & 0xffff) !== uch) throw new PendingThrow("java/lang/InternalError", `UTF-32 char in modified UTF-8 byte sequence: ${uch}`); + ch = uch; + } + text += String.fromCharCode(ch); + } + return vm.str(text); +} + export const intrinsics: Natives = { + "jdk/internal/jimage/ImageStringsReader.stringFromByteBuffer(Ljava/nio/ByteBuffer;I)Ljava/lang/String;": imageString, [`${ASB}.append(Ljava/lang/String;)L${ASB};`]: appendString, "java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;": appendString, "java/lang/String.(Ljava/lang/AbstractStringBuilder;Ljava/lang/Void;)V": stringFromBuilder, diff --git a/test/java/ImageStrings.java b/test/java/ImageStrings.java new file mode 100644 index 0000000..45ac92e --- /dev/null +++ b/test/java/ImageStrings.java @@ -0,0 +1,19 @@ +import java.net.URI; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Stream; + +public class ImageStrings { + public static void main(String[] args) throws Exception { + FileSystem jrt = FileSystems.getFileSystem(URI.create("jrt:/")); + try (Stream s = Files.list(jrt.getPath("/modules/java.base/java/lang/invoke"))) { + s.map(Path::toString).sorted().forEach(System.out::println); + } + try (Stream s = Files.walk(jrt.getPath("/modules/java.compiler"))) { + System.out.println(s.count()); + } + System.out.println(Files.readAllBytes(jrt.getPath("/modules/java.base/java/lang/Object.class")).length); + } +} From bb9087c2e18489c299164985d4f89836def5ee11 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:16:29 -0600 Subject: [PATCH 4/8] Parenthesize generated functions so V8 parses them once: javac's first compile is about 5% faster --- src/jit.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jit.ts b/src/jit.ts index d3e0d55..252a86d 100644 --- a/src/jit.ts +++ b/src/jit.ts @@ -599,7 +599,7 @@ function generate(t: JThread, m: JMethod): { src: string; consts: any[] } { const fname = `${m.cls.name}_${m.name}`.replace(/[^A-Za-z0-9_$]/g, "_"); const out: string[] = []; // direct calls pass arguments as parameters and a frame without arrays - out.push(`return function ${fname}(t,f${params.map((p) => "," + p).join("")}){let L=f.locals,S=f.stack;const vm=t.vm,H=rt.hooks;`); + out.push(`return (function ${fname}(t,f${params.map((p) => "," + p).join("")}){let L=f.locals,S=f.stack;const vm=t.vm,H=rt.hooks;`); out.push(`let pc=f.pc,tm,cf,r,a,v,ic,ifs=0,dpc=0,dsp=0,x=0,xs=0,xe=null,${[...g.vars].join(",")};`); out.push(`if(L===null){${params.map((p, i) => `${L(i)}=${p};`).join("")}}else{${Array.from({ length: nl }, (_, i) => `${L(i)}=L[${i}];`).join("")}${Array.from({ length: ns }, (_, i) => `${S(i)}=S[${i}];`).join("")}}`); out.push(`X:{for(;;){try{switch(pc){`); @@ -616,7 +616,7 @@ function generate(t: JThread, m: JMethod): { src: string; consts: any[] } { out.push(`f.pc=x>>>13;xs=x>>>3&1023;${spillLocals()}switch(xs){${stack}}f.sp=xs;`); out.push(`switch(x&7){case ${EXIT_FALLBACK}:return rt.fallback(t,f);case ${EXIT_INTERPRET}:return rt.viaInterpreter(t,f);` + `case ${EXIT_RETHROW}:t.pushNative(rt.rethrow(xe.obj),null,"V",false);return 1;` + - `case ${EXIT_ERROR}:H.handleError(t,xe);return 1;}return 1;}`); + `case ${EXIT_ERROR}:H.handleError(t,xe);return 1;}return 1;})`); return { src: out.join("\n"), consts }; } From fc13ba1ca8ad249a835b079b619d06435c3283e5 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:36:35 -0600 Subject: [PATCH 5/8] Move the exception and exit tails of generated code into helpers: 12% less JS, about 3 MB less heap after a javac run --- src/jit.ts | 46 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/src/jit.ts b/src/jit.ts index 252a86d..b361277 100644 --- a/src/jit.ts +++ b/src/jit.ts @@ -127,6 +127,40 @@ function fallback(t: JThread, f: Frame) { return SUSPEND; } +// An exception in compiled code: the pc of the handler (>= 0); an exit code +// to take, as -x - 2; or -1 when the frame is gone and the code returns. +function caught(t: JThread, f: Frame, pc: number, e: unknown): number { + const error = (at: number) => { + f.direct = false; + return -(at * exitCode(1, 0, 0) + EXIT_ERROR) - 2; + }; + if (e instanceof JavaThrow) { + const h = hooks.findHandler(t, f, pc, e.obj); + if (h >= 0) return h; + if (h < -1) return error(pc); + hooks.popFrame(t, f); + if (f.direct) throw e; + hooks.raise(t, e.obj); + return -1; + } + return error(e instanceof PendingThrow && e.pc !== undefined ? e.pc : pc); +} + +// Leaves compiled code through an exit once its frame is spilled. +function leave(t: JThread, f: Frame, x: number, xe: any): number { + switch (x & 7) { + case EXIT_FALLBACK: return fallback(t, f); + case EXIT_INTERPRET: return viaInterpreter(t, f); + case EXIT_RETHROW: + t.pushNative(runtime.rethrow(xe.obj), null, "V", false); + return 1; + case EXIT_ERROR: + hooks.handleError(t, xe); + return 1; + } + return 1; +} + // A call compiled code cannot make directly; not a reason to recompile. function viaInterpreter(t: JThread, f: Frame) { hooks.interpret(t, f, 1); @@ -164,6 +198,8 @@ const runtime = { concat: concatStrings, fallback, viaInterpreter, + caught, + leave, basicTarget(t: JThread, mh: JObject | null, pc: number): JMethod { if (mh === null) npeAt(pc); const form = t.vm.getField(mh, "java/lang/invoke/MethodHandle", "form") as JObject; @@ -607,16 +643,10 @@ function generate(t: JThread, m: JMethod): { src: string; consts: any[] } { // a frame the interpreter left elsewhere steps to the next entry out.push(`default:return rt.viaInterpreter(t,f);}}catch(e){`); if (g.regions.length) out.push(deoptCatch(g)); - out.push(`if(e instanceof rt.JavaThrow){const h=H.findHandler(t,f,pc,e.obj);if(h>=0){${S(0)}=e.obj;pc=h;continue;}`); - out.push(`if(h< -1){x=pc*${exitCode(1, 0, 0)}+${EXIT_ERROR};xe=e;if(f.direct)f.direct=false;break X;}`); - out.push(`H.popFrame(t,f);if(f.direct)throw e;H.raise(t,e.obj);return 1;}`); - out.push(`x=(e instanceof rt.PendingThrow&&e.pc!==undefined?e.pc:pc)*${exitCode(1, 0, 0)}+${EXIT_ERROR};xe=e;if(f.direct)f.direct=false;break X;}}}`); + out.push(`xs=rt.caught(t,f,pc,e);if(xs>=0){${S(0)}=e.obj;pc=xs;continue;}if(xs<-1){x=-xs-2;xe=e;break X;}return 1;}}}`); // the shared exit: spill into the frame's arrays, then leave as x says const stack = Array.from({ length: ns }, (_, i) => `case ${ns - i}:S[${ns - i - 1}]=${S(ns - i - 1)};`).join(""); - out.push(`f.pc=x>>>13;xs=x>>>3&1023;${spillLocals()}switch(xs){${stack}}f.sp=xs;`); - out.push(`switch(x&7){case ${EXIT_FALLBACK}:return rt.fallback(t,f);case ${EXIT_INTERPRET}:return rt.viaInterpreter(t,f);` + - `case ${EXIT_RETHROW}:t.pushNative(rt.rethrow(xe.obj),null,"V",false);return 1;` + - `case ${EXIT_ERROR}:H.handleError(t,xe);return 1;}return 1;})`); + out.push(`f.pc=x>>>13;xs=x>>>3&1023;${spillLocals()}switch(xs){${stack}}f.sp=xs;return rt.leave(t,f,x,xe);})`); return { src: out.join("\n"), consts }; } From c7aed021cc14dbb028fadca7593d38f8dc99b98b Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:40:04 -0600 Subject: [PATCH 6/8] Keep line tables as offsets into the class bytes and share empty handler lists: about 3 MB less heap per VM, hello world from a boot snapshot 4% faster --- src/classfile.ts | 48 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/src/classfile.ts b/src/classfile.ts index 4f45173..8d0f9ce 100644 --- a/src/classfile.ts +++ b/src/classfile.ts @@ -41,26 +41,33 @@ export class Code { readonly handlers: ExceptionEntry[]; // raw LocalVariableTable attribute body, parsed on demand readonly localVars: Uint8Array | null; - private rawLines: Uint8Array[] | null; + // the class's bytes, and where its LineNumberTable bodies start (-1 for none) + private bytes: Uint8Array; + private linesAt: number; + private moreLines: number[] | null; private parsedLines: number[] | null | undefined; - constructor(maxStack: number, maxLocals: number, code: Uint8Array, handlers: ExceptionEntry[], rawLines: Uint8Array[] | null, localVars: Uint8Array | null) { + constructor(maxStack: number, maxLocals: number, code: Uint8Array, handlers: ExceptionEntry[], bytes: Uint8Array, linesAt: number, moreLines: number[] | null, localVars: Uint8Array | null) { this.maxStack = maxStack; this.maxLocals = maxLocals; this.code = code; this.handlers = handlers; - this.rawLines = rawLines; + this.bytes = bytes; + this.linesAt = linesAt; + this.moreLines = moreLines; this.localVars = localVars; } // pairs of (start pc, line), sorted by pc get lines(): number[] | null { if (this.parsedLines !== undefined) return this.parsedLines; let lines: number[] | null = null; - for (const body of this.rawLines ?? []) { - const lr = new Reader(body); - lines ??= []; - for (let n = lr.u2(); n > 0; n--) lines.push(lr.u2(), lr.u2()); + if (this.linesAt >= 0) { + const r = new Reader(this.bytes); + for (const at of [this.linesAt, ...(this.moreLines ?? [])]) { + r.pos = at; + lines ??= []; + for (let n = r.u2(); n > 0; n--) lines.push(r.u2(), r.u2()); + } } - this.rawLines = null; if (lines && lines.length > 2) { let sorted = true; for (let i = 2; i < lines.length; i += 2) if (lines[i] < lines[i - 2]) { sorted = false; break; } @@ -178,6 +185,7 @@ export function encodeMutf8(s: string): Uint8Array { } const NO_ATTRS = new Map(); +const NO_HANDLERS: ExceptionEntry[] = []; function readMember(r: Reader, cp: ClassFile["cp"]): Member { const access = r.u2(); @@ -213,19 +221,27 @@ function readCode(r: Reader, cp: ClassFile["cp"]): Code { const maxStack = r.u2(); const maxLocals = r.u2(); const code = r.slice(r.u4()); - const handlers: ExceptionEntry[] = []; - for (let n = r.u2(); n > 0; n--) { + let n = r.u2(); + const handlers: ExceptionEntry[] = n === 0 ? NO_HANDLERS : []; + for (; n > 0; n--) { handlers.push({ start: r.u2(), end: r.u2(), handler: r.u2(), catchType: r.u2() }); } - let lines: Uint8Array[] | null = null; + let linesAt = -1; + let moreLines: number[] | null = null; let localVars: Uint8Array | null = null; - for (let n = r.u2(); n > 0; n--) { + for (n = r.u2(); n > 0; n--) { const name = utf8(cp, r.u2()); - const body = r.slice(r.u4()); - if (name === "LocalVariableTable") localVars = body; - else if (name === "LineNumberTable") (lines ??= []).push(body); + const length = r.u4(); + if (name === "LineNumberTable") { + if (linesAt < 0) linesAt = r.pos; + else (moreLines ??= []).push(r.pos); + r.pos += length; + } else { + const body = r.slice(length); + if (name === "LocalVariableTable") localVars = body; + } } - return new Code(maxStack, maxLocals, code, handlers, lines, localVars); + return new Code(maxStack, maxLocals, code, handlers, r.bytes, linesAt, moreLines, localVars); } export function cpEntry(cp: ClassFile["cp"], i: number): CpEntry | undefined { From 5a6bafdbe6981ff6467c087d07c8741966880fa4 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:43:18 -0600 Subject: [PATCH 7/8] Name snapshot files without node:crypto, which takes about 15 ms to load at every start --- src/node.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/node.ts b/src/node.ts index 8e10bc9..3b3fad7 100644 --- a/src/node.ts +++ b/src/node.ts @@ -6,7 +6,6 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import { deserialize, serialize, setFlagsFromString } from "node:v8"; -import { createHash } from "node:crypto"; import { runInNewContext } from "node:vm"; import { fileURLToPath, pathToFileURL } from "node:url"; import { VFS } from "./fs.ts"; @@ -432,6 +431,8 @@ function buildId(vfs: VFS, packaged: boolean): string | null { if (packaged) return typeof JAVA_WEB_BUILD === "string" ? JAVA_WEB_BUILD : null; const image = vfs.read("/jdk/lib/image.sha256"); if (!image) return null; + // loaded here, as it takes about 15 ms and a packaged start needs no digest + const { createHash } = process.getBuiltinModule("node:crypto"); const h = createHash("sha256").update(image); if (typeof JAVA_WEB_BUILD === "string") return h.update(JAVA_WEB_BUILD).digest("hex"); // unbundled, this file runs as src/node.ts, next to the rest of the VM's sources @@ -442,10 +443,21 @@ function buildId(vfs: VFS, packaged: boolean): string | null { return h.digest("hex"); } +// A file name for a key: four FNV-1a lanes, 128 bits. An image holds its full +// key, so a collision only costs a boot. +function fingerprint(key: string): string { + const lanes = [0x811c9dc5, 0x9747b28c, 0x2545f491, 0xc2b2ae35], primes = [0x01000193, 0x01000197, 0x0100019b, 0x010001a3]; + for (let i = 0; i < key.length; i++) { + const c = key.charCodeAt(i); + for (let k = 0; k < 4; k++) lanes[k] = Math.imul(lanes[k] ^ c, primes[k]); + } + return lanes.map((h) => (h >>> 0).toString(16).padStart(8, "0")).join(""); +} + // Boot snapshots kept in dir, one file per key. A key's snapshot is taken the // second time it boots, so one-off setups leave only an empty marker. function snapshotCache(dir: string, build: string) { - const name = (key: string) => path.join(dir, createHash("sha256").update(key).digest("hex").slice(0, 32)); + const name = (key: string) => path.join(dir, fingerprint(key)); const file = (key: string) => name(key) + ".snap"; const warmFile = (key: string) => name(key) + ".warm"; // keeps the most recently used of each kind From 96847b1285ec8fc2b4271fcd854d72ded62199ad Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:58:40 -0600 Subject: [PATCH 8/8] Say the warm image is about 20 MB --- docs/browser.md | 2 +- docs/node.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/browser.md b/docs/browser.md index 57030b7..95eb165 100644 --- a/docs/browser.md +++ b/docs/browser.md @@ -162,7 +162,7 @@ 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. In Chromium, the first javac compile after it takes about half the time of one -after a boot snapshot. An image is about 21 MB; it holds the JS the JIT +after a boot snapshot. An image is about 20 MB; it holds the JS the JIT generated for the methods compiled so far, and a restored method compiles that code on its first call. IndexedDB keeps the 2 most recent warm images separately from boot snapshots. With `debug: true`, the console says whether a VM was diff --git a/docs/node.md b/docs/node.md index 7941908..182b075 100644 --- a/docs/node.md +++ b/docs/node.md @@ -77,7 +77,7 @@ 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 first javac compile from it takes about a sixth of the time -of one after a boot snapshot. An image is about 21 MB, as it also holds the JS +of one after a boot snapshot. An image is about 20 MB, as it also holds the JS the JIT generated for the methods compiled so far; a restored method compiles that code on its first call instead of generating it again. Warm snapshots share the snapshot directory and keep the 2 most recent. They build on boot snapshots, so with