From 901db906db009021bc40149c280f64bf00142f00 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:48:57 -0600 Subject: [PATCH 1/3] perf(runtime): keep an object's monitor, identity hash and VM data in one slot --- src/jit.ts | 11 ++++---- src/jvm.ts | 45 +++++++++++++++++++-------------- src/natives/continuation.ts | 18 +++++++------- src/natives/invoke.ts | 22 ++++++++-------- src/natives/java2d-shape.ts | 12 +++++---- src/natives/java2d-surface.ts | 3 ++- src/natives/java2d.ts | 4 +-- src/natives/lang.ts | 16 ++++++------ src/natives/loader.ts | 4 +-- src/natives/management.ts | 18 +++++++------- src/natives/misc.ts | 18 ++++++++------ src/natives/ref.ts | 32 +++++++++++++----------- src/natives/stackwalk.ts | 5 ++-- src/runtime.ts | 47 ++++++++++++++++++++++++++++++++--- src/snapshot.ts | 30 +++++++++++++--------- 15 files changed, 174 insertions(+), 111 deletions(-) diff --git a/src/jit.ts b/src/jit.ts index e259c6e..b6ecfda 100644 --- a/src/jit.ts +++ b/src/jit.ts @@ -15,9 +15,7 @@ // interpreted call. import { cpB, cpTag, cpValue, Tag, utf8 } from "./classfile.ts"; -import { - ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, -} from "./runtime.ts"; +import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, dataOf } from "./runtime.ts"; import { memberTarget } from "./natives/invoke.ts"; import { concatStrings } from "./natives/strings.ts"; import { Frame, JavaThrow, NativeFrame, PendingThrow, fromNative } from "./thread.ts"; @@ -76,7 +74,7 @@ export function restoreJit(vm: JVM, m: JMethod, code: SavedJit) { // A constant of compiled code that holds a class another loader can drop. function namesUnloadable(v: unknown, caller: JClass): boolean { - const c = v instanceof JClass ? v : v instanceof JMethod || v instanceof JField ? v.cls : v instanceof JObject ? (v.x instanceof JClass ? v.x : v.cls) : null; + const c = v instanceof JClass ? v : v instanceof JMethod || v instanceof JField ? v.cls : v instanceof JObject ? (dataOf(v) instanceof JClass ? dataOf(v) : v.cls) : null; return c !== null && c !== caller && c.unloadable && (c.hidden || c.loader !== caller.loader); } @@ -1088,11 +1086,12 @@ function insnCode(g: Gen, b: Body, pc: number) { } case 0xc2: if (region) throw new NoInline(); - emit(`if(${top()}===null)np(${pc});if(!vm.monitorEnter(t,${top()}))${g.exit(pc, d, EXIT_SUSPEND)}`); + // an idle or own monitor is taken inline, so the object's shape is seen by this site alone + emit(`if(${top()}===null)np(${pc});{const mo=${top()}.s;if(mo!==null&&typeof mo==="object"&&mo.owner===null&&t.mounted===null&&!t.blockedOnMonitor){mo.owner=t;mo.count=1}else if(mo!==null&&typeof mo==="object"&&mo.owner===t)mo.count++;else if(!vm.monitorEnter(t,${top()}))${g.exit(pc, d, EXIT_SUSPEND)}}`); break; case 0xc3: if (region) throw new NoInline(); - emit(`if(${top()}===null)np(${pc});vm.monitorExit(t,${top()});`); + emit(`if(${top()}===null)np(${pc});{const mo=${top()}.s;if(mo!==null&&typeof mo==="object"&&mo.owner===t){if(mo.count>1)mo.count--;else if(mo.entry===null&&t.mounted===null){mo.owner=null;mo.count=0}else vm.monitorExit(t,${top()})}else vm.monitorExit(t,${top()})}`); break; case 0xc4: { const wop = c[pc + 1], i = u16(c, pc + 2); diff --git a/src/jvm.ts b/src/jvm.ts index d322d30..9186db9 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -11,7 +11,8 @@ import { JImage } from "./jimage.ts"; import { ACC_ABSTRACT, ACC_FINAL, ACC_INTERFACE, ACC_NATIVE, ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC, ACC_STATIC, ACC_SUPER, ACC_VARARGS, ERRONEOUS, INITIALIZED, INITIALIZING, JArray, JClass, JField, - JMethod, JObject, LINKED, Monitor, defaultValue, dropsWithLoader, newArrayData, noteYield, sched, + JMethod, JObject, LINKED, Monitor, dataOf, defaultValue, dropsWithLoader, hashOf, monitorFor, monitorOf, newArrayData, noteYield, + sched, setData, setHash, } from "./runtime.ts"; import type { CallSite, NativeFn } from "./runtime.ts"; import { @@ -262,7 +263,9 @@ export class JVM { } loaderData(loader: JObject): LoaderData { - return (loader.x ??= { classes: new Map(), modules: new Map() }); + let d = dataOf(loader); + if (d === undefined) setData(loader, (d = { classes: new Map(), modules: new Map() })); + return d; } // A hidden class defined STRONG lives as long as its loader; the others, as long as they are reachable. @@ -442,7 +445,7 @@ export class JVM { throw e; } if (!mirror) throw new PendingThrow("java/lang/NoClassDefFoundError", name); - const c = mirror.x as JClass; + const c = dataOf(mirror) as JClass; this.loaderClasses(loader).set(name, c); return c; } @@ -724,13 +727,14 @@ export class JVM { } identityHash(o: JObject): number { - if (o.hash === 0) { + let h = hashOf(o); + if (h === 0) { let x = this.hashSeed; x ^= x << 13; x ^= x >>> 17; x ^= x << 5; this.hashSeed = x; - o.hash = (x & 0x7fffffff) || 1; + setHash(o, h = (x & 0x7fffffff) || 1); } - return o.hash; + return h; } isInstance(o: JObject, name: string): boolean { @@ -741,7 +745,7 @@ export class JVM { mirror(c: JClass): JObject { if (c.mirror) return c.mirror; const o = this.newObject(this.loadBootOrFail("java/lang/Class")); - o.x = c; + setData(o, c); c.mirror = o; this.setField(o, "java/lang/Class", "classLoader", c.loader); if (c.component) this.setField(o, "java/lang/Class", "componentType", this.mirror(c.component)); @@ -752,7 +756,7 @@ export class JVM { } classOf(mirror: JObject): JClass { - return mirror.x as JClass; + return dataOf(mirror) as JClass; } // Class.getModifiers: inner class flags win over the class access flags. @@ -782,16 +786,21 @@ export class JVM { return this.getField(c.loader, "java/lang/ClassLoader", "unnamedModule"); } + private baseVersion(): string | undefined { + const base = this.bootModules.get("java.base"); + return base ? dataOf(base)?.version : undefined; + } + // ModuleEntry::should_show_version: the JDK's own modules show no version. shownVersion(mod: JObject): string | null { - const version = mod.x?.version as string | null | undefined; + const version = dataOf(mod)?.version as string | null | undefined; if (!version || !this.getField(mod, "java/lang/Module", "name")) return null; - const jrt = (mod.x.location as string | null) ?? ""; + const jrt = (dataOf(mod).location as string | null) ?? ""; const loader = this.getField(mod, "java/lang/Module", "loader") as JObject | null; const platform = loader?.cls.name === "jdk/internal/loader/ClassLoaders$PlatformClassLoader"; const builtin = !loader || platform || loader.cls.name === "jdk/internal/loader/ClassLoaders$AppClassLoader"; if ((!loader || platform) && jrt.startsWith("jrt:/java.")) return null; - if (builtin && jrt.startsWith("jrt:/jdk.") && version === this.bootModules.get("java.base")?.x?.version) return null; + if (builtin && jrt.startsWith("jrt:/jdk.") && version === this.baseVersion()) return null; return version; } @@ -1009,7 +1018,7 @@ export class JVM { this.setThreadStatus(t, STATUS_BLOCKED); } t.state = WAITING; - o.mon!.enqueue(() => this.wake(t, true)); + monitorOf(o)!.enqueue(() => this.wake(t, true)); return false; } @@ -1021,7 +1030,7 @@ export class JVM { // Takes o's monitor if that needs no waiting. tryMonitorEnter(t: JThread, o: JObject): boolean { - const mon = (o.mon ??= new Monitor()); + const mon = monitorFor(o); if (mon.owner === null) { mon.owner = t; mon.count = 1; @@ -1036,7 +1045,7 @@ export class JVM { } monitorExit(t: JThread, o: JObject) { - const mon = o.mon; + const mon = monitorOf(o); if (!mon || mon.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException"); if (--mon.count === 0) { if (t.mounted !== null) dropOwned(t, o); @@ -1178,7 +1187,7 @@ export class JVM { javaThread(obj: JObject): JThread { const t = new JThread(this); t.obj = obj; - obj.x = t; + setData(obj, t); const vm = this; const holder = this.getField(obj, "java/lang/Thread", "holder") as JObject; t.daemon = this.getField(holder, "java/lang/Thread$FieldHolder", "daemon") === 1; @@ -1213,7 +1222,7 @@ export class JVM { // Thread.join waits on the thread object, checking isAlive() under its // monitor. Take the monitor first, as HotSpot's ensure_join does, so a // joiner between isAlive() and wait() cannot miss the wakeup. - while (!this.tryMonitorEnter(t, obj)) yield t.block(new Signal((r) => obj.mon!.enqueue(r))); + while (!this.tryMonitorEnter(t, obj)) yield t.block(new Signal((r) => monitorOf(obj)!.enqueue(r))); const holder = this.getField(obj, "java/lang/Thread", "holder") as JObject; this.setField(holder, "java/lang/Thread$FieldHolder", "threadStatus", STATUS_TERMINATED); this.setField(obj, "java/lang/Thread", "eetop", 0n); @@ -1222,7 +1231,7 @@ export class JVM { } notifyAll(o: JObject) { - const mon = o.mon; + const mon = monitorOf(o); if (!mon) return; const w = mon.waiters; if (w === null) return; @@ -1364,7 +1373,7 @@ export class JVM { const thread = boot("java/lang/Thread"); const obj = this.newObject(thread); t.obj = obj; - obj.x = t; + setData(obj, t); this.setField(obj, "java/lang/Thread", "eetop", 1n); yield t.call(thread.methodMap.get("(Ljava/lang/ThreadGroup;Ljava/lang/String;)V")!, obj, mainGroup, this.str("main")); const holder = this.getField(obj, "java/lang/Thread", "holder") as JObject; diff --git a/src/natives/continuation.ts b/src/natives/continuation.ts index 9d39aa8..25e16bc 100644 --- a/src/natives/continuation.ts +++ b/src/natives/continuation.ts @@ -6,7 +6,7 @@ // virtual thread while it is not (JEP 491): a yield, a contended enter and // Object.wait all unmount it, and the monitors move to a stand-in owner. -import { JMethod } from "../runtime.ts"; +import { JMethod, dataOf, monitorOf, setData } from "../runtime.ts"; import type { JObject, Monitor } from "../runtime.ts"; import { Frame, JThread, NativeFrame, PendingThrow, RUNNABLE, Signal, WAITING } from "../thread.ts"; import type { AnyFrame, NativeGen } from "../thread.ts"; @@ -108,7 +108,7 @@ function state(vm: JVM): State { // The continuation a native frame is the entry of, if it is one. // The frames of a yielded continuation, bottom first. export function frozenFrames(c: JObject): AnyFrame[] | undefined { - const info = c.x as Frozen | undefined; + const info = dataOf(c) as Frozen | undefined; if (!info) return undefined; if (!(info.flags & PACKED)) return info.frames as AnyFrame[]; const out: AnyFrame[] = []; @@ -156,13 +156,13 @@ function freeze(t: JThread, e: number, count: number, retry: boolean) { const entry = (t.frames[e] as NativeFrame).entry!; const info: Frozen = { frames: [], flags: retry ? RETRY : 0, monitors: NO_MONITORS, owner: null }; if (entry.virtual) { - const monitors = [...new Set(t.owned)].filter((o) => o.mon?.owner === t); + const monitors = [...new Set(t.owned)].filter((o) => monitorOf(o)?.owner === t); t.owned = []; if (monitors.length > 0) { const owner = new JThread(t.vm); owner.obj = t.mounted; owner.state = WAITING; - for (const o of monitors) o.mon!.owner = owner; + for (const o of monitors) monitorOf(o)!.owner = owner; info.monitors = monitors; info.owner = owner; } @@ -172,7 +172,7 @@ function freeze(t: JThread, e: number, count: number, retry: boolean) { info.frames = pack(frames); info.flags |= PACKED; } else info.frames = frames; - entry.cont.x = info; + setData(entry.cont, info); s.frozenCount++; s.busy = true; setChunk(t, entry.cont, true); @@ -203,7 +203,7 @@ export function unmountBlocked(t: JThread) { const e = innermost(t); freeze(t, e, t.frames.length - e - 1, true); t.vm.setField(t.mounted!, VT, "state", BLOCKING); - unblockOnRelease(t.vm, t.mounted!, o.mon!); + unblockOnRelease(t.vm, t.mounted!, monitorOf(o)!); t.state = RUNNABLE; } @@ -243,15 +243,15 @@ export const natives: Natives = { yield t.call(enter, c, 0); return; } - const info = c.x as Frozen | undefined; + const info = dataOf(c) as Frozen | undefined; if (!info) throw new PendingThrow("java/lang/IllegalStateException", "Continuation has no frames"); - c.x = undefined; + setData(c, undefined); s.frozenCount--; setChunk(t, c, false); if (info.flags & PACKED) unpackInto(t.frames, info.frames); else for (const f of info.frames as AnyFrame[]) t.frames.push(f); if (info.owner) { - for (const o of info.monitors) o.mon!.owner = t; + for (const o of info.monitors) monitorOf(o)!.owner = t; t.owned = info.monitors; } const top = t.top; diff --git a/src/natives/invoke.ts b/src/natives/invoke.ts index 51459ba..6aa95f7 100644 --- a/src/natives/invoke.ts +++ b/src/natives/invoke.ts @@ -3,7 +3,7 @@ // ({ m } or { f }); methods also get a ResolvedMethodName holding the JMethod, // so clones of the MemberName share it as they do in HotSpot. -import { ACC_FINAL, ACC_STATIC, INITIALIZED, JClass, JField, JMethod, JObject, STATIC_OFFSET_BASE } from "../runtime.ts"; +import { ACC_FINAL, ACC_STATIC, INITIALIZED, JClass, JField, JMethod, JObject, STATIC_OFFSET_BASE, dataOf, setData } from "../runtime.ts"; import { JThread, PendingThrow } from "../thread.ts"; import type { NativeGen } from "../thread.ts"; import { fieldOf } from "./misc.ts"; @@ -21,13 +21,14 @@ const REF_invokeVirtual = 5, REF_invokeStatic = 6, REF_invokeSpecial = 7, REF_ne const METHOD_MODIFIERS = 0x1dff, FIELD_MODIFIERS = 0x50df; export function memberTarget(t: JThread, mn: JObject): JMethod { - const m = mn.x?.m ?? (t.vm.getField(mn, MN, "method") as JObject | null)?.x; + const rn = t.vm.getField(mn, MN, "method") as JObject | null; + const m = dataOf(mn)?.m ?? (rn ? dataOf(rn) : undefined); if (!m) throw new PendingThrow("java/lang/InternalError", "unresolved MemberName"); return m; } export function memberField(mn: JObject): JField { - const f = mn.x?.f; + const f = dataOf(mn)?.f; if (!f) throw new PendingThrow("java/lang/InternalError", "unresolved field MemberName"); return f; } @@ -75,7 +76,7 @@ export function resolvedMethodName(t: JThread, m: JMethod): JObject { const vm = t.vm; const o = vm.newObject(vm.loadBoot("java/lang/invoke/ResolvedMethodName")!); vm.setField(o, "java/lang/invoke/ResolvedMethodName", "vmholder", vm.mirror(m.cls)); - o.x = m; + setData(o, m); return o; } @@ -99,7 +100,7 @@ export function initMethodMember(t: JThread, mn: JObject, m: JMethod, refKind: n vm.setField(mn, MN, "flags", flags | (kind << KIND_SHIFT)); vm.setField(mn, MN, "clazz", vm.mirror(m.cls)); vm.setField(mn, MN, "method", resolvedMethodName(t, m)); - mn.x = { m }; + setData(mn, { m }); } export function initFieldMember(t: JThread, mn: JObject, f: JField, setter: boolean) { @@ -110,7 +111,7 @@ export function initFieldMember(t: JThread, mn: JObject, f: JField, setter: bool const kind = (f.isStatic ? REF_getStatic : REF_getField) + (setter ? REF_putField - REF_getField : 0); vm.setField(mn, MN, "flags", flags | (kind << KIND_SHIFT)); vm.setField(mn, MN, "clazz", vm.mirror(f.cls)); - mn.x = { f }; + setData(mn, { f }); } function findMethodIn(c: JClass, key: string, refKind: number): JMethod | null { @@ -160,7 +161,7 @@ export const natives: Natives = { }, "java/lang/invoke/MethodHandleNatives.expand(Ljava/lang/invoke/MemberName;)V": (t, [mn]) => { const vm = t.vm; - const x = mn.x; + const x = dataOf(mn); if (!x) throw new PendingThrow("java/lang/IllegalArgumentException", "MemberName not resolved"); const member = x.m ?? x.f; if (!vm.getField(mn, MN, "clazz")) vm.setField(mn, MN, "clazz", vm.mirror(member.cls)); @@ -178,12 +179,13 @@ export const natives: Natives = { const vm = t.vm; const long = vm.loadBoot("java/lang/Long")!; if (long.state !== INITIALIZED) yield* vm.initGen(t, long); - const isField = !!mn.x?.f; + const field = dataOf(mn)?.f as JField | undefined; + const isField = !!field; // a method reference that dispatches has a vtable index; others none const kind = (vm.getField(mn, MN, "flags") >> KIND_SHIFT) & 0xf; - const index = isField ? BigInt(mn.x.f.slot) : kind === REF_invokeVirtual || kind === REF_invokeInterface ? 0n : -2n; + const index = isField ? BigInt(field!.slot) : kind === REF_invokeVirtual || kind === REF_invokeInterface ? 0n : -2n; const boxed = yield t.call(long.methodMap.get("valueOf(J)Ljava/lang/Long;")!, index); - return vm.newObjectArray("java/lang/Object", [boxed, isField ? vm.mirror(mn.x.f.cls) : mn]); + return vm.newObjectArray("java/lang/Object", [boxed, isField ? vm.mirror(field!.cls) : mn]); }, "java/lang/invoke/MethodHandleNatives.setCallSiteTargetNormal(Ljava/lang/invoke/CallSite;Ljava/lang/invoke/MethodHandle;)V": (t, [site, target]) => t.vm.setField(site, "java/lang/invoke/CallSite", "target", target), diff --git a/src/natives/java2d-shape.ts b/src/natives/java2d-shape.ts index ce84c77..bb5ef4c 100644 --- a/src/natives/java2d-shape.ts +++ b/src/natives/java2d-shape.ts @@ -5,6 +5,7 @@ import type { JArray, JObject } from "../runtime.ts"; import { PendingThrow } from "../thread.ts"; import type { JThread } from "../thread.ts"; import type { Natives } from "./util.ts"; +import { dataOf, setData } from "../runtime.ts"; const SSI = "sun/java2d/pipe/ShapeSpanIterator"; const SCR = "sun/java2d/pipe/SpanClipRenderer"; @@ -503,7 +504,8 @@ function minmax4(v1: number, v2: number, v3: number, v4: number): [number, numbe } export function spanIterOf(o: JObject): SpanIter | null { - return o.x instanceof Path ? o.x : null; + const p = dataOf(o); + return p instanceof Path ? p : null; } function internal(msg: string): never { @@ -515,7 +517,7 @@ function npe(msg: string): never { } function data(o: JObject, min: number, max: number): Path { - const p = o.x; + const p = dataOf(o); if (!(p instanceof Path)) return npe("private data"); if (p.state < min || p.state > max) return internal("bad path delivery sequence"); return p; @@ -634,8 +636,8 @@ function fillTile(t: JThread, ri: JObject | null, alphaTile: JArray | null, offs export const natives: Natives = { [`${SSI}.setNormalize(Z)V`]: (_t, [self, adjust]) => { - if (self.x instanceof Path) internal("private data already initialized"); - self.x = new Path(!!adjust); + if (dataOf(self) instanceof Path) internal("private data already initialized"); + setData(self, new Path(!!adjust)); }, [`${SSI}.setOutputAreaXYXY(IIII)V`]: (_t, [self, lox, loy, hix, hiy]) => { const p = data(self, STATE_INIT, STATE_INIT); @@ -682,7 +684,7 @@ export const natives: Natives = { }, [`${SSI}.getNativeIterator()J`]: () => 1n, [`${SSI}.dispose()V`]: (_t, [self]) => { - self.x = null; + setData(self, null); }, [`${SSI}.appendPoly([I[IIII)V`]: (_t, [self, xArray, yArray, nPoints, xoff, yoff]) => { const p = data(self, STATE_HAVE_CLIP, STATE_HAVE_CLIP); diff --git a/src/natives/java2d-surface.ts b/src/natives/java2d-surface.ts index a8e4fcc..ce800a3 100644 --- a/src/natives/java2d-surface.ts +++ b/src/natives/java2d-surface.ts @@ -6,6 +6,7 @@ import { PendingThrow } from "../thread.ts"; import type { JThread } from "../thread.ts"; import type { JVM } from "../jvm.ts"; import { Surf, extraAlpha8 } from "./java2d-loops.ts"; +import { dataOf } from "../runtime.ts"; export const LOOPS = "sun/java2d/loops/"; export const GP = LOOPS + "GraphicsPrimitive"; @@ -33,7 +34,7 @@ export function add(cls: string, src: string, comp: string, dst: string, fn: any export function surfOf(t: JThread, sd: JObject | null): Surf | null { if (sd === null) throw new PendingThrow("java/lang/NullPointerException", "surfaceData"); - const s = sd.x as Surf | undefined; + const s = dataOf(sd) as Surf | undefined; if (s) return s; if (sd.cls.name === "sun/java2d/NullSurfaceData") return null; if (!t.vm.getField(sd, "sun/java2d/SurfaceData", "valid")) throw new PendingThrow("sun/java2d/InvalidPipeException", "invalid data"); diff --git a/src/natives/java2d.ts b/src/natives/java2d.ts index 81a17fb..517aa72 100644 --- a/src/natives/java2d.ts +++ b/src/natives/java2d.ts @@ -3,7 +3,7 @@ // .registerNativeLoops). Surface types without loops here use the JDK's // pure Java general loops, as HotSpot does for types it has no loops for. -import { INITIALIZED } from "../runtime.ts"; +import { INITIALIZED, setData } from "../runtime.ts"; import type { JArray, JMethod, JObject } from "../runtime.ts"; import type { JVM } from "../jvm.ts"; import { PendingThrow } from "../thread.ts"; @@ -397,7 +397,7 @@ const surfaceNatives: Natives = { s.lut = lut; s.lutSize = lutSize; s.icm = icm; - self.x = s; + setData(self, s); }, "sun/java2d/SurfaceData.isOpaqueGray"(t, [icm]) { return icm === null ? 0 : t.vm.getField(icm, "java/awt/image/IndexColorModel", "allgrayopaque"); diff --git a/src/natives/lang.ts b/src/natives/lang.ts index b65710b..14f0519 100644 --- a/src/natives/lang.ts +++ b/src/natives/lang.ts @@ -4,7 +4,7 @@ import { isHidden } from "./stackwalk.ts"; import { gcStats, javaHeap } from "./management.ts"; import { assertionsEnabled } from "../assertions.ts"; import { normalize } from "../fs.ts"; -import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, newArrayData, releasePins } from "../runtime.ts"; +import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, newArrayData, releasePins, dataOf, monitorOf, setData } from "../runtime.ts"; import type { Monitor } from "../runtime.ts"; import { canUnmount, dropOwned, unblockOnRelease } from "./continuation.ts"; import { collect, registerFinalizer, releaseFinalizerCycles, releaseSoftReferences } from "./ref.ts"; @@ -60,7 +60,7 @@ const MAX_DELAY = 0x7fffffff; function* waitImpl(t: JThread, self: JObject, ms: bigint): NativeGen { const vm = t.vm; - const mon = self.mon; + const mon = monitorOf(self); if (!mon || mon.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException", "current thread is not owner"); checkInterrupt(t); if (t.mounted !== null && canUnmount(t)) return yield* waitUnmounted(t, self, mon, ms); @@ -201,7 +201,7 @@ export function cloneObject(t: JThread, o: JObject): JObject { throw new PendingThrow("java/lang/CloneNotSupportedException", o.cls.javaName); } const copy = new JObject(o.cls, o.f.slice()); - copy.x = o.x; + setData(copy, dataOf(o)); if (copy.cls.finalizable) registerFinalizer(t.vm, copy); return copy; } @@ -216,12 +216,12 @@ export const natives: Natives = { "java/lang/Object.hashCode()I": (t, [o]) => t.vm.identityHash(o), "java/lang/Object.clone()Ljava/lang/Object;": (t, [o]) => cloneObject(t, o), "java/lang/Object.notify()V": (t, [o]) => { - const mon = o.mon; + const mon = monitorOf(o); if (!mon || mon.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException", "current thread is not owner"); mon.waiters?.shift()?.wake(); }, "java/lang/Object.notifyAll()V": (t, [o]) => { - if (!o.mon || o.mon.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException", "current thread is not owner"); + if (monitorOf(o)?.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException", "current thread is not owner"); t.vm.notifyAll(o); }, "java/lang/Object.wait0(J)V": (t, [o, ms]) => waitImpl(t, o, ms), @@ -311,12 +311,12 @@ export const natives: Natives = { t.vm.setField(holder, "java/lang/Thread$FieldHolder", "threadStatus", STATUS_RUNNABLE); t.vm.startThread(nt); }, - "java/lang/Thread.holdsLock(Ljava/lang/Object;)Z": (t, [o]) => nonNull(o).mon?.owner === t, + "java/lang/Thread.holdsLock(Ljava/lang/Object;)Z": (t, [o]) => monitorOf(nonNull(o))?.owner === t, "java/lang/Thread.getThreads()[Ljava/lang/Thread;": (t) => t.vm.newObjectArray("java/lang/Thread", [...t.vm.threads].filter((x) => x.state !== TERMINATED && x.obj).map((x) => x.obj!)), "java/lang/Thread.setPriority0(I)V": () => undefined, "java/lang/Thread.interrupt0()V": (t, [obj]) => { - const target = obj.x as JThread | undefined; + const target = dataOf(obj) as JThread | undefined; target?.wake?.(); }, "java/lang/Thread.clearInterruptEvent()V": () => undefined, @@ -412,7 +412,7 @@ export function fillElement(t: JThread, e: JObject, c: JClass, method: string, p vm.setField(e, S, "moduleName", name); // every version, as java_lang_StackTraceElement::fill_in sets it; // toString leaves out the JDK's own - const version = mod.x?.version as string | null | undefined; + const version = dataOf(mod)?.version as string | null | undefined; if (version) vm.setField(e, S, "moduleVersion", vm.intern(version)); } } diff --git a/src/natives/loader.ts b/src/natives/loader.ts index d645098..4715975 100644 --- a/src/natives/loader.ts +++ b/src/natives/loader.ts @@ -1,6 +1,6 @@ // java.lang.ClassLoader and java.lang.Module natives. -import { INITIALIZED, JArray, JObject } from "../runtime.ts"; +import { INITIALIZED, JArray, JObject, setData } from "../runtime.ts"; import type { JThread, NativeGen } from "../thread.ts"; import { nestHostOf } from "./reflect.ts"; import { jstr, u8 } from "./util.ts"; @@ -21,7 +21,7 @@ function* define(t: JThread, loader: JObject | null, name: JObject | null, bytes function defineModule(t: JThread, m: JObject, version: JObject | null, location: JObject | null, pns: JArray) { const vm = t.vm; const name = jstr(t, vm.getField(m, "java/lang/Module", "name")); - m.x = { version: jstr(t, version), location: jstr(t, location) }; + setData(m, { version: jstr(t, version), location: jstr(t, location) }); const loader = vm.getField(m, "java/lang/Module", "loader") as JObject | null; const pkgs = (pns.a as JObject[]).map((p) => vm.jsString(p).replace(/\./g, "/")); if (loader === null) { diff --git a/src/natives/management.ts b/src/natives/management.ts index e555bcd..880aaf4 100644 --- a/src/natives/management.ts +++ b/src/natives/management.ts @@ -4,7 +4,7 @@ // collector. Heap usage is the JS heap's; collections are the explicit // System.gc() calls, which HotSpot counts as full collections. -import { INITIALIZED, JArray, JClass, JObject, MAX_HEAP } from "../runtime.ts"; +import { INITIALIZED, JArray, JClass, JObject, MAX_HEAP, dataOf, monitorOf } from "../runtime.ts"; import type { JMethod } from "../runtime.ts"; import { Frame, JThread, NativeFrame, PendingThrow, STATUS_BLOCKED, STATUS_NEW, STATUS_PARKED, STATUS_PARKED_TIMED, STATUS_RUNNABLE, @@ -206,7 +206,7 @@ function synchronizerOwner(vm: JVM, o: JObject): JObject | null { } function platformThread(o: JObject | null): JThread | null { - const x = o?.x; + const x = o ? dataOf(o) : undefined; return x instanceof JThread && x.state !== TERMINATED ? x : null; } @@ -282,17 +282,17 @@ function lockedMonitors(t: JThread, frames: Shown[]): { o: JObject; depth: numbe if (!(f instanceof Frame)) return; const held: JObject[] = []; const locals: any[] = f.locals ?? []; - for (const v of locals) if (v instanceof JObject && v.mon?.owner === t) owned.add(v); + for (const v of locals) if (v instanceof JObject && monitorOf(v)?.owner === t) owned.add(v); if (locals.length) { const active = syncBlocks(f.m).filter((b) => b.start <= f.pc && f.pc < b.end); // a handler's own range is listed too, so one lock can appear twice const slots = [...new Set(active.sort((x, y) => y.start - x.start).map((b) => b.slot))]; for (const slot of slots) { const v = locals[slot]; - if (v instanceof JObject && v.mon?.owner === t) held.push(v); + if (v instanceof JObject && monitorOf(v)?.owner === t) held.push(v); } } - if (f.lock && !f.needLock && f.lock.mon?.owner === t) held.push(f.lock); + if (f.lock && !f.needLock && monitorOf(f.lock)?.owner === t) held.push(f.lock); for (const o of held) accounted.set(o, (accounted.get(o) ?? 0) + 1); byFrame.set(at, held); }); @@ -301,7 +301,7 @@ function lockedMonitors(t: JThread, frames: Shown[]): { o: JObject; depth: numbe for (const o of byFrame.get(fr.at) ?? []) out.push({ o, depth }); }); for (const o of owned) { - for (let n = o.mon!.count - (accounted.get(o) ?? 0); n > 0; n--) out.push({ o, depth: -1 }); + for (let n = monitorOf(o)!.count - (accounted.get(o) ?? 0); n > 0; n--) out.push({ o, depth: -1 }); } return out; } @@ -326,7 +326,7 @@ function snapshot(vm: JVM, t: JThread, maxDepth: number): Snapshot { const o = t.waitingOn ?? t.pendingOn; if (o === null) status = STATUS_RUNNABLE; else { - const holder = o.mon?.owner ?? null; + const holder = monitorOf(o)?.owner ?? null; if (holder === null && status === STATUS_BLOCKED) status = STATUS_RUNNABLE; else { blocker = o; @@ -429,7 +429,7 @@ function ownedSynchronizers(vm: JVM): Map { if (Array.isArray(o.a)) for (const v of o.a) visit(v); } else for (const v of o.f) visit(v); // a class loader keeps the classes it defined - const x = o.x; + const x = dataOf(o); if (x instanceof JClass) visitClass(x); else if (x?.classes instanceof Map) for (const c of x.classes.values()) visitClass(c); } @@ -486,7 +486,7 @@ function findDeadlocks(vm: JVM, synchronizers: boolean): JObject | null { while (cur && (mon || park)) { path.push(cur); if (mon) { - const owner = mon.mon?.owner ?? null; + const owner = monitorOf(mon)?.owner ?? null; if (owner !== null) cur = owner.state === TERMINATED ? null : owner; } else if (isSynchronizer(vm, park)) { cur = platformThread(synchronizerOwner(vm, park!)); diff --git a/src/natives/misc.ts b/src/natives/misc.ts index c7b280f..71c1f7d 100644 --- a/src/natives/misc.ts +++ b/src/natives/misc.ts @@ -1,9 +1,7 @@ // jdk.internal.misc (Unsafe, VM, CDS, Signal), system properties and other // low-level natives. -import { - ARRAY_BASE_OFFSET, INITIALIZED, JArray, JClass, JMethod, JObject, STATIC_OFFSET_BASE, -} from "../runtime.ts"; +import { ARRAY_BASE_OFFSET, INITIALIZED, JArray, JClass, JMethod, JObject, STATIC_OFFSET_BASE, dataOf, setData } from "../runtime.ts"; import { JThread, JavaThrow, PendingThrow, STATUS_PARKED, STATUS_PARKED_TIMED, STATUS_RUNNABLE } from "../thread.ts"; import type { NativeGen } from "../thread.ts"; import type { JVM } from "../jvm.ts"; @@ -24,10 +22,12 @@ export function indexScale(c: JClass): number { // A primitive array's DataView, kept in x (unused otherwise for arrays, and // not copied by clone). function view(a: JArray): DataView { - const v = a.x as DataView | undefined; + const v = dataOf(a) as DataView | undefined; if (v !== undefined) return v; const d = a.a as Int8Array; - return (a.x = new DataView(d.buffer, d.byteOffset, d.byteLength)); + const dv = new DataView(d.buffer, d.byteOffset, d.byteLength); + setData(a, dv); + return dv; } // A byte[] access of another width, composed from bytes: a DataView per @@ -122,7 +122,8 @@ export function unsafeGet(t: JThread, o: JObject | null, offset: bigint, k: stri if (sameKind(elem, k)) return o.a[(off - ARRAY_BASE_OFFSET) / WIDTH[elem]]; return arrayRead(o, off - ARRAY_BASE_OFFSET, k); } - if (off >= STATIC_OFFSET_BASE && o.x instanceof JClass) return o.x.statics[off - STATIC_OFFSET_BASE]; + const c = dataOf(o); + if (off >= STATIC_OFFSET_BASE && c instanceof JClass) return c.statics[off - STATIC_OFFSET_BASE]; return o.f[off]; } @@ -139,7 +140,8 @@ export function unsafePut(t: JThread, o: JObject | null, offset: bigint, k: stri else arrayWrite(o, off - ARRAY_BASE_OFFSET, k, v); return; } - if (off >= STATIC_OFFSET_BASE && o.x instanceof JClass) o.x.statics[off - STATIC_OFFSET_BASE] = v; + const c = dataOf(o); + if (off >= STATIC_OFFSET_BASE && c instanceof JClass) c.statics[off - STATIC_OFFSET_BASE] = v; else o.f[off] = v; } @@ -282,7 +284,7 @@ function setStatus(t: JThread, s: number) { Object.assign(unsafe, { [`${U}park(ZJ)V`]: (t: JThread, [, abs, time]: any[]) => park(t, abs === 1, time), [`${U}unpark(Ljava/lang/Object;)V`]: (t: JThread, [, obj]: any[]) => { - const jt = obj?.x as JThread | undefined; + const jt = obj ? (dataOf(obj) as JThread | undefined) : undefined; if (!(jt instanceof JThread)) return; jt.parkPermit = true; if (t.vm.state.get(`parked:${jt.id}`)) jt.wake?.(); diff --git a/src/natives/ref.ts b/src/natives/ref.ts index 1988c65..bb07c84 100644 --- a/src/natives/ref.ts +++ b/src/natives/ref.ts @@ -6,7 +6,7 @@ // finalizer is watched too: its wrapper is collected, and the Finalizer gets a // new wrapper over the same storage. -import { INITIALIZED, MAX_HEAP, freeHeap, hasMaxHeap, releasePins, setReclaim, wrapperOver } from "../runtime.ts"; +import { INITIALIZED, MAX_HEAP, dataOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, setReclaim, wrapperOver } from "../runtime.ts"; import { JObject } from "../runtime.ts"; import type { JClass } from "../runtime.ts"; import { Signal } from "../thread.ts"; @@ -61,8 +61,8 @@ function refs(vm: JVM): RefState { if (typeof held === "function") return held(); if ("cls" in held) return resurrect(vm, s!, held); const ref = held.deref(); - if (!ref || !(ref.x instanceof WeakRef)) return; - ref.x = null; + if (!ref || !(dataOf(ref) instanceof WeakRef)) return; + setData(ref, null); addPending(s!, ref); }), weak: vm.loadBoot("java/lang/ref/WeakReference")!, @@ -88,24 +88,25 @@ function addPending(s: RefState, ref: JObject) { } function referent(t: JThread, r: JObject): JObject | null { - if (r.x instanceof WeakRef) return r.x.deref() ?? null; + const x = dataOf(r); + if (x instanceof WeakRef) return x.deref() ?? null; return t.vm.getField(r, R, "referent"); } function clear(t: JThread, r: JObject) { - if (r.x instanceof WeakRef) { + if (dataOf(r) instanceof WeakRef) { const s = refs(t.vm); s.registry.unregister(r); s.softs.delete(r); } - r.x = null; + setData(r, null); t.vm.setField(r, R, "referent", null); } // A weak, soft or phantom reference to obj; a reference with a queue is // enqueued when obj is collected. function watch(s: RefState, self: JObject, obj: JObject, queued: boolean) { - self.x = new WeakRef(obj); + setData(self, new WeakRef(obj)); if (self.cls.isSubclassOf(s.soft)) { s.softs.set(self, obj); s.softCount++; @@ -157,16 +158,16 @@ function probe(s: RefState, done: () => void) { // storage, and the Reference Handler passes it on to finalize(). function resurrect(vm: JVM, s: RefState, h: Fin) { const fin = h.fin; - if (!(fin.x instanceof WeakRef)) return; + if (!(dataOf(fin) instanceof WeakRef)) return; if (h.f === null) { // nothing to finalize: the Finalizer thread unlinks it, and its finalize(null) fails quietly - fin.x = null; + setData(fin, null); return addPending(s, fin); } const o = wrapperOver(h.cls, h.f); - o.hash = h.hash; - o.x = h.x; - fin.x = null; + setHash(o, h.hash); + setData(o, h.x); + setData(fin, null); vm.setField(fin, R, "referent", o); addPending(s, fin); } @@ -226,7 +227,8 @@ function forgetCycles(s: RefState, scan: number): boolean { let i = 0; for (; i < list.length && budget.left > 0; i++) { const h = list[i]; - const w = h.f !== null && h.fin.x instanceof WeakRef ? h.fin.x.deref() : undefined; + const fx = h.f !== null ? dataOf(h.fin) : undefined; + const w = fx instanceof WeakRef ? fx.deref() : undefined; if (w === undefined) continue; if (leadsBack(w, h.f!, budget)) h.f = null; else kept.push(h); @@ -241,8 +243,8 @@ export function releaseFinalizerCycles(vm: JVM) { } function watchFinalizer(vm: JVM, s: RefState, fin: JObject, obj: JObject) { - fin.x = new WeakRef(obj); - const h: Fin = { fin, cls: obj.cls, f: obj.f, hash: vm.identityHash(obj), x: obj.x }; + setData(fin, new WeakRef(obj)); + const h: Fin = { fin, cls: obj.cls, f: obj.f, hash: vm.identityHash(obj), x: dataOf(obj) }; s.fins.push(h); s.registry.register(obj, h, fin); } diff --git a/src/natives/stackwalk.ts b/src/natives/stackwalk.ts index 8d2be6f..2454467 100644 --- a/src/natives/stackwalk.ts +++ b/src/natives/stackwalk.ts @@ -7,6 +7,7 @@ import { fillElement } from "./lang.ts"; import { annotationTypes, isCallerSensitive, resolvedMethodName } from "./invoke.ts"; import { javaFrames } from "./util.ts"; import type { Natives } from "./util.ts"; +import { dataOf } from "../runtime.ts"; const CLASS_INFO_ONLY = 0x2, SHOW_HIDDEN_FRAMES = 0x20; const IS_METHOD = 0x10000, IS_CONSTRUCTOR = 0x20000, CALLER_SENSITIVE = 0x100000, HIDDEN_MEMBER = 0x400000; @@ -68,7 +69,7 @@ function fill(t: JThread, mode: number, w: Walk, frames: JArray, start: number, } function methodOfInfo(t: JThread, sfi: JObject): JMethod { - return (t.vm.getField(sfi, CFI, "classOrMemberName") as JObject).x as JMethod; + return dataOf(t.vm.getField(sfi, CFI, "classOrMemberName") as JObject) as JMethod; } export const natives: Natives = { @@ -118,7 +119,7 @@ export const natives: Natives = { function stackOf(t: JThread, thread: JObject): JObject | null { // a mounted virtual thread's frames are on its carrier - const own = thread.x as JThread | undefined; + const own = dataOf(thread) as JThread | undefined; const target = own ?? [...t.vm.threads].find((c) => c.mounted === thread); if (!target) return null; const ste = t.vm.loadBoot("java/lang/StackTraceElement")!; diff --git a/src/runtime.ts b/src/runtime.ts index aa66694..972613e 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -174,10 +174,9 @@ export class JMethod { export class JObject { cls: JClass; f: any[]; - mon: Monitor | null = null; - hash = 0; - // VM-side data: the JClass of a Class mirror, the JThread of a Thread, ... - x: any = undefined; + // what most objects never need: null, the identity hash once taken, or a + // Monitor (which also holds the hash and the VM-side data) + s: number | Monitor | null = null; constructor(cls: JClass, f: any[]) { this.cls = cls; this.f = f; @@ -185,6 +184,43 @@ export class JObject { } } +export function monitorOf(o: JObject): Monitor | null { + const s = o.s; + return typeof s === "object" ? s : null; +} + +export function monitorFor(o: JObject): Monitor { + const s = o.s; + if (typeof s === "object" && s !== null) return s; + const m = new Monitor(); + if (s !== null) m.hash = s; + o.s = m; + return m; +} + +export function hashOf(o: JObject): number { + const s = o.s; + return s === null ? 0 : typeof s === "number" ? s : s.hash; +} + +export function setHash(o: JObject, h: number) { + const s = o.s; + if (typeof s === "object" && s !== null) s.hash = h; + else o.s = h === 0 ? null : h; +} + +// VM-side data: the JClass of a Class mirror, the JThread of a Thread, ... +export function dataOf(o: JObject): any { + const s = o.s; + return typeof s === "object" && s !== null ? s.x : undefined; +} + +export function setData(o: JObject, x: any) { + const s = o.s; + if (typeof s === "object" && s !== null) s.x = x; + else if (x !== undefined) monitorFor(o).x = x; +} + export type ArrayData = | Int8Array | Uint16Array | Int16Array | Int32Array | Float32Array | Float64Array | BigInt64Array | (JObject | null)[]; @@ -233,6 +269,9 @@ export class Monitor { entry: (() => void)[] | null = null; // threads in wait(), woken by notify, with the entry count they gave up waiters: Waiter[] | null = null; + // the object's identity hash and VM-side data, kept here to cost the other objects nothing + hash = 0; + x: any = undefined; enqueue(wake: () => void) { (this.entry ??= []).push(wake); diff --git a/src/snapshot.ts b/src/snapshot.ts index aebce49..6a485f4 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -11,7 +11,7 @@ import { restorePending, restoreReference } from "./natives/ref.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 { JArray, JClass, JField, JMethod, JObject, Monitor, dataOf, hashOf, monitorOf, setData, setHash } from "./runtime.ts"; import { restoreJit } from "./jit.ts"; import { Frame, JThread, NativeFrame, STATUS_RUNNABLE, Signal } from "./thread.ts"; import type { NativeGen } from "./thread.ts"; @@ -216,7 +216,7 @@ class Encoder { } private isLeaf(v: JObject): boolean { - if (v.mon || v.x !== undefined) return false; + if (monitorOf(v) !== null) return false; const list = v instanceof JArray ? v.a : v.f; if (!Array.isArray(list)) return true; for (const e of list) if (e !== null && (typeof e === "function" || (typeof e === "object" && !ArrayBuffer.isView(e) && !(e instanceof ArrayBuffer)))) return false; @@ -229,7 +229,7 @@ class Encoder { let t: any; if (v instanceof JObject) { const array = v instanceof JArray; - t = { $: array ? "A" : "O", c: this.cls(v.cls, path), h: v.hash }; + t = { $: array ? "A" : "O", c: this.cls(v.cls, path), h: hashOf(v) }; this.work.push(() => { if (array && !Array.isArray(v.a)) t.a = v.a; else { @@ -237,8 +237,10 @@ class Encoder { t[array ? "a" : "f"] = list; if (r) t.r = r; } - if (v.mon) t.n = this.child(v.mon, path, next); - if (v.x !== undefined) t.x = v.x instanceof WeakRef ? { $: "W", v: this.child(v.x.deref() ?? null, path, next) } : this.child(v.x, path, next); + const mon = monitorOf(v); + if (mon && (mon.owner !== null || mon.count > 0 || mon.waiters?.length)) t.n = this.child(mon, path, next); + const x = dataOf(v); + if (x !== undefined) t.x = x instanceof WeakRef ? { $: "W", v: this.child(x.deref() ?? null, path, next) } : this.child(x, path, next); }); } else if (v instanceof JClass) t = { $: "C", i: this.cls(v, path) }; else if (v instanceof JMethod) t = { $: "M", c: this.cls(v.cls, path), k: v.key }; @@ -312,7 +314,7 @@ class Decoder { const cls = this.classes[v.c]; if (!cls) throw new Error(`snapshot: object of class #${v.c} before its class`); o = v.$ === "A" ? new JArray(cls, v.a) : new JObject(cls, v.f); - o.hash = v.h; + if (v.h) setHash(o, v.h); break; } case "C": return this.classes[v.i]; @@ -355,10 +357,14 @@ class Decoder { } switch (v.$) { case "O": case "A": - if (v.n) o.mon = this.dec(v.n); + if (v.n) { + const m: Monitor = this.dec(v.n); + m.hash = hashOf(o); + o.s = m; + } if (v.x !== undefined) { if (v.x?.$ === "W") this.references.push([o, v.x.v]); - else o.x = this.dec(v.x); + else setData(o, this.dec(v.x)); } break; case "m": @@ -464,7 +470,7 @@ export function dumpVM(vm: JVM, main: JThread, key: string, library = false): Sn if (key === REF_WAIT) return { $: "native", m: e.enc(f.m, p) }; if (key === WAIT0) { const o = (t.frames[i - 1] as Frame).locals[0] as JObject; - const w = o.mon?.waiters?.find((x) => x.t === t); + const w = monitorOf(o)?.waiters?.find((x) => x.t === t); if (!w) throw new Error(`snapshot: ${p} in wait0 is not a waiter`); return { $: "rewait", m: e.enc(f.m, p), o: e.enc(o, p), n: w.count }; } @@ -499,7 +505,7 @@ function snapshotFds(value: unknown): unknown { // A waiter woken as if spuriously: takes its monitor back with the count it gave up. function* rewait(t: JThread, o: JObject, count: number): NativeGen { - const mon = o.mon!; + const mon = monitorOf(o)!; t.waitingOn = o; while (mon.owner !== null) yield t.block(new Signal((r) => mon.enqueue(r))); mon.owner = t; @@ -574,7 +580,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { const mainRec = image.threads[0]; main.obj = d.dec(mainRec.obj); - main.obj!.x = main; + setData(main.obj!, main); if (mainRec.frames) { for (const f of mainRec.frames as any[]) { if (f.$ === "library") { @@ -620,7 +626,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { for (const [o, referent] of d.references) { const r = d.dec(referent); if (r) restoreReference(vm, o, r); - else o.x = null; + else setData(o, null); } d.flush(); for (const t of others) vm.startThread(t); From a502f6bb1e05a0507dd969b277869a68e663015e Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:56:25 -0600 Subject: [PATCH 2/3] perf(runtime): store instance fields in the object itself instead of a separate array --- AGENTS.md | 6 ++ src/interp.ts | 28 ++++- src/jit.ts | 22 ++-- src/jvm.ts | 32 +++--- src/library.ts | 4 +- src/natives/crypto.ts | 14 +-- src/natives/lang.ts | 5 +- src/natives/management.ts | 8 +- src/natives/misc.ts | 27 +++-- src/natives/ref.ts | 23 +++-- src/natives/strings.ts | 60 +++++------ src/runtime.ts | 200 +++++++++++++++++++++++++++++++----- src/snapshot.ts | 11 +- test/java/ObjectLayout.java | 151 +++++++++++++++++++++++++++ 14 files changed, 469 insertions(+), 122 deletions(-) create mode 100644 test/java/ObjectLayout.java diff --git a/AGENTS.md b/AGENTS.md index e8e6e18..261dda0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,6 +107,12 @@ Node, which is how the tests run. - **PendingThrow**: thrown by JS code to raise a new Java exception; the interpreter builds it with its real constructor. - **mirror**: the `java.lang.Class` object of a runtime class. +- **object layout**: a Java object is a JS object with `cls`, `s` (identity + hash, monitor and VM data, once it has any) and its instance fields as + properties `f0`, `f1`, ... (`JField.key`). Classes whose fields have the same + kinds share one generated constructor, so one JS shape. An object whose class + has a finalizer keeps its fields in a second object, `st`, that the Finalizer + also holds. - **handle**: how the VM names a Java object it gave to JS; the page's proxy holds it until the proxy is dropped. - **wire value**: a value as it crosses between the VM and JS (library.ts). diff --git a/src/interp.ts b/src/interp.ts index 3f07d0e..d384d51 100644 --- a/src/interp.ts +++ b/src/interp.ts @@ -332,7 +332,19 @@ export function interpret(t: JThread, f: Frame, budget: number): number { if (fld === undefined) { f.pc = ipc; f.sp = sp; return budget; } o = stack[sp - 1]; if (o === null) npe(); - stack[sp - 1] = o.f[fld.slot]; + // a named load per slot: the engine caches each by shape, which a computed key cannot + switch (fld.slot) { + case 0: v = o.f0; break; + case 1: v = o.f1; break; + case 2: v = o.f2; break; + case 3: v = o.f3; break; + case 4: v = o.f4; break; + case 5: v = o.f5; break; + case 6: v = o.f6; break; + case 7: v = o.f7; break; + default: v = o[fld.key]; + } + stack[sp - 1] = v; if (fld.wide) stack[sp++] = undefined; pc += 3; break; @@ -345,7 +357,17 @@ export function interpret(t: JThread, f: Frame, budget: number): number { v = stack[--sp]; o = stack[--sp]; if (o === null) npe(); - o.f[fld.slot] = v; + switch (fld.slot) { + case 0: o.f0 = v; break; + case 1: o.f1 = v; break; + case 2: o.f2 = v; break; + case 3: o.f3 = v; break; + case 4: o.f4 = v; break; + case 5: o.f5 = v; break; + case 6: o.f6 = v; break; + case 7: o.f7 = v; break; + default: o[fld.key] = v; + } pc += 3; break; } @@ -412,7 +434,7 @@ export function interpret(t: JThread, f: Frame, budget: number): number { if (c === undefined) { f.pc = ipc; f.sp = sp; return budget; } if (c.state !== INITIALIZED && !vm.initialize(t, c)) { f.pc = ipc; f.sp = sp; return budget; } if (c.access & 0x0600) throw new PendingThrow("java/lang/InstantiationError", c.javaName); - const o = new JObject(c, c.template.slice()); + const o = new c.ctor(c); if (c.finalizable) registerFinalizer(vm, o); stack[sp++] = o; pc += 3; diff --git a/src/jit.ts b/src/jit.ts index b6ecfda..fc13e51 100644 --- a/src/jit.ts +++ b/src/jit.ts @@ -1019,11 +1019,11 @@ function insnCode(g: Gen, b: Body, pc: number) { case 0xb4: case 0xb5: { const fld = cls.rcp[idx2] as JField | undefined; if (!fld) { emit(slow(pc, d)); break; } - if (op === 0xb4) emit(`${b.nn.has(d - 1) ? "" : `if(${top()}===null)np(${pc});`}${top()}=${top()}.f[${fld.slot}];`); + if (op === 0xb4) emit(`${b.nn.has(d - 1) ? "" : `if(${top()}===null)np(${pc});`}${top()}=${top()}.${fld.key};`); else { const k = fld.wide ? 2 : 1; const obj = top(k); - emit(`${b.nn.has(d - 1 - k) ? "" : `if(${obj}===null)np(${pc});`}${obj}.f[${fld.slot}]=${fld.wide ? top(1) : top()};`); + emit(`${b.nn.has(d - 1 - k) ? "" : `if(${obj}===null)np(${pc});`}${obj}.${fld.key}=${fld.wide ? top(1) : top()};`); } break; } @@ -1053,7 +1053,7 @@ function insnCode(g: Gen, b: Body, pc: number) { } const k = cls.rcp[idx2] as JClass | undefined; if (!k || k.state !== INITIALIZED || k.access & 0x0600 || k.finalizable) { emit(slow(pc, d)); break; } - emit(`${S(d)}=new rt.JObject(${K(k)},${K(k)}.template.slice());`); + emit(`${S(d)}=new ${K(k)}.ctor(${K(k)});`); break; } case 0xbc: { @@ -1189,7 +1189,7 @@ function numLit(v: number): string { // Bodies that can be inlined at a call site: they neither call nor throw. type Trivial = - | { kind: "empty" } | { kind: "get"; slot: number } | { kind: "set"; slot: number } | { kind: "const"; value: string } + | { kind: "empty" } | { kind: "get"; key: string } | { kind: "set"; key: string } | { kind: "const"; value: string } | { kind: "expr"; build: (args: string[]) => string }; // Pure arithmetic on parameters, as one JS expression, or null. Only @@ -1218,7 +1218,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null { const c = code.code; if (c.length > 32 || code.handlers.length > 0) return null; // the expression is built from tokens: ["arg", slot] refers to a parameter - type Tok = string | ["arg", number] | ["field", number, number]; + type Tok = string | ["arg", number] | ["field", number, string]; const stack: Tok[][] = []; // negative literals in parentheses, so "a - -5" cannot become "a--5" const lit = (s: string): Tok[] => [s.startsWith("-") ? `(${s})` : s]; @@ -1248,7 +1248,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null { const a = stack.pop(); const fld = m.cls.rcp[(c[pc + 1] << 8) | c[pc + 2]] as JField | undefined; if (!a || !fld || a.length !== 1 || !Array.isArray(a[0]) || a[0][0] !== "arg" || a[0][1] !== 0) return null; - push = [["field", 0, fld.slot]]; + push = [["field", 0, fld.key]]; len = 3; } else if (op >= 0xac && op <= 0xb0) { if (pc + 1 !== c.length || stack.length !== 1) return null; @@ -1263,7 +1263,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null { function render(toks: Tok[], args: string[]): string { return toks.map((x: any) => { if (typeof x === "string") return x; - if (Array.isArray(x)) return x[0] === "arg" ? args[x[1]] : `${args[x[1]]}.f[${x[2]}]`; + if (Array.isArray(x)) return x[0] === "arg" ? args[x[1]] : `${args[x[1]]}.${x[2]}`; if (x.op) return x.op(render(x.a, args), render(x.b, args)); return x.op1(render(x.a, args)); }).join(""); @@ -1285,12 +1285,12 @@ function trivialBody(m: JMethod): Trivial | null { // aload_0 getfield xreturn if (c.length === 5 && c[1] === 0xb4 && c[4] >= 0xac && c[4] <= 0xb0) { const f = field(); - return f ? { kind: "get", slot: f.slot } : null; + return f ? { kind: "get", key: f.key } : null; } // aload_0 xload_1 putfield return if (c.length === 6 && [0x1b, 0x1f, 0x23, 0x27, 0x2b].includes(c[1]) && c[2] === 0xb5 && c[5] === 0xb1) { const f = m.cls.rcp[(c[3] << 8) | c[4]] as JField | undefined; - return f ? { kind: "set", slot: f.slot } : null; + return f ? { kind: "set", key: f.key } : null; } const build = leafExpr(m); return build ? { kind: "expr", build } : null; @@ -1301,8 +1301,8 @@ function genInline(body: Trivial, res: string, args: string[], pc: number, check switch (body.kind) { case "empty": return nullCheck; case "const": return `${nullCheck}${res}=${body.value};`; - case "get": return `${nullCheck}${res}=${args[0]}.f[${body.slot}];`; - case "set": return `${nullCheck}${args[0]}.f[${body.slot}]=${args[1]};`; + case "get": return `${nullCheck}${res}=${args[0]}.${body.key};`; + case "set": return `${nullCheck}${args[0]}.${body.key}=${args[1]};`; case "expr": return `${nullCheck}${res}=${body.build(args)};`; } } diff --git a/src/jvm.ts b/src/jvm.ts index 9186db9..231430d 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -12,9 +12,9 @@ import { ACC_ABSTRACT, ACC_FINAL, ACC_INTERFACE, ACC_NATIVE, ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC, ACC_STATIC, ACC_SUPER, ACC_VARARGS, ERRONEOUS, INITIALIZED, INITIALIZING, JArray, JClass, JField, JMethod, JObject, LINKED, Monitor, dataOf, defaultValue, dropsWithLoader, hashOf, monitorFor, monitorOf, newArrayData, noteYield, - sched, setData, setHash, + fieldKey, sched, setData, setHash, } from "./runtime.ts"; -import type { CallSite, NativeFn } from "./runtime.ts"; +import type { CallSite, FieldKey, NativeFn } from "./runtime.ts"; import { Frame, JThread, JavaThrow, NativeFrame, PendingThrow, RUNNABLE, Signal, STATUS_BLOCKED, STATUS_RUNNABLE, STATUS_TERMINATED, TERMINATED, WAITING, @@ -162,7 +162,7 @@ export class JVM { private interned = new Map(); readonly prims = new Map(); // owner -> field name -> slot; two lookups of literal strings beat building a key - private slots = new Map>(); + private keys = new Map>(); readonly threads = new Set(); private runQueue: JThread[] = []; // threads another thread woke in its turn: they run before the rotation, so a hand-off does not wait behind spinners @@ -379,7 +379,6 @@ export class JVM { c.superclass = superclass; c.interfaces = interfaces; let slot = superclass ? superclass.instanceSlots : 0; - const template = superclass ? superclass.template.slice() : []; for (const [i, fm] of cf.fields.entries()) { const f = new JField(c, fm); f.index = i; @@ -388,12 +387,11 @@ export class JVM { c.statics.push(defaultValue(f.desc)); } else { f.slot = slot++; - template.push(defaultValue(f.desc)); + f.key = fieldKey(f.slot); } c.fields.push(f); } 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()) { @@ -703,7 +701,7 @@ export class JVM { // ---- objects ------------------------------------------------------------- newObject(c: JClass): JObject { - const o = new JObject(c, c.template.slice()); + const o = new c.ctor(c); if (c.finalizable) registerFinalizer(this, o); return o; } @@ -823,25 +821,25 @@ export class JVM { // ---- fields by name ------------------------------------------------------ - slotOf(owner: string, name: string): number { - let byName = this.slots.get(owner); - if (!byName) this.slots.set(owner, (byName = new Map())); + keyOf(owner: string, name: string): FieldKey { + let byName = this.keys.get(owner); + if (!byName) this.keys.set(owner, (byName = new Map())); let s = byName.get(name); if (s === undefined) { const f = this.loadBootOrFail(owner).findField(name); if (!f) throw new Error(`no field ${owner}.${name}`); - s = f.slot; + s = f.key; byName.set(name, s); } return s; } getField(o: JObject, owner: string, name: string): any { - return o.f[this.slotOf(owner, name)]; + return o[this.keyOf(owner, name)]; } setField(o: JObject, owner: string, name: string, v: any) { - o.f[this.slotOf(owner, name)] = v; + o[this.keyOf(owner, name)] = v; } getStatic(c: JClass, name: string): any { @@ -872,14 +870,14 @@ export class JVM { const u16 = new Uint16Array(bytes.buffer); for (let i = 0; i < s.length; i++) u16[i] = s.charCodeAt(i); } - o.f[this.slotOf("java/lang/String", "value")] = new JArray(this.primArrayClass("B"), bytes); - o.f[this.slotOf("java/lang/String", "coder")] = latin1 ? 0 : 1; + o[this.keyOf("java/lang/String", "value")] = new JArray(this.primArrayClass("B"), bytes); + o[this.keyOf("java/lang/String", "coder")] = latin1 ? 0 : 1; return o; } jsString(o: JObject): string { - const bytes = (o.f[this.slotOf("java/lang/String", "value")] as JArray).a as Int8Array; - const coder = o.f[this.slotOf("java/lang/String", "coder")]; + const bytes = (o[this.keyOf("java/lang/String", "value")] as JArray).a as Int8Array; + const coder = o[this.keyOf("java/lang/String", "coder")]; let units: ArrayLike; if (coder === 0) units = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length); else if (bytes.byteOffset % 2 === 0) units = new Uint16Array(bytes.buffer, bytes.byteOffset, bytes.length >> 1); diff --git a/src/library.ts b/src/library.ts index a619d65..7c627db 100644 --- a/src/library.ts +++ b/src/library.ts @@ -464,7 +464,7 @@ export class Library { case "setStatic": case "set": { const { f, obj } = yield* this.field(t, req.op === "set" ? req.obj : req.cls, req.field); const value = yield* this.toJava(t, f.desc, yield* this.resolve(t, req.value), f.cls.loader); - if (obj) obj.f[f.slot] = value; + if (obj) obj[f.key] = value; else f.cls.statics[f.slot] = value; return { value: undefined }; } @@ -491,7 +491,7 @@ export class Library { // A field's Java value and descriptor. private *readField(t: JThread, target: number | string | FieldRef, name: string): Generator { const { f, obj } = yield* this.field(t, target, name); - return [obj ? obj.f[f.slot] : f.cls.statics[f.slot], f.desc]; + return [obj ? obj[f.key] : f.cls.statics[f.slot], f.desc]; } private methodsOf(cls: JClass, name: string, isStatic: boolean): JMethod[] { diff --git a/src/natives/crypto.ts b/src/natives/crypto.ts index b0d0635..b1471f1 100644 --- a/src/natives/crypto.ts +++ b/src/natives/crypto.ts @@ -3,7 +3,7 @@ // longs, which are JS BigInts here, so a 64-bit step allocates; these do the // same work on numbers, or in far fewer BigInt steps. -import type { JArray, JObject } from "../runtime.ts"; +import type { FieldKey, JArray, JObject } from "../runtime.ts"; import type { JThread } from "../thread.ts"; import type { JVM } from "../jvm.ts"; import type { Natives } from "./util.ts"; @@ -17,13 +17,13 @@ const AES = "com/sun/crypto/provider/AESCrypt"; const P256 = "sun/security/util/math/intpoly/MontgomeryIntegerPolynomialP256"; // the `state` field's slot in each digest class -const stateSlots = new WeakMap>(); +const stateSlots = new WeakMap>(); function state(t: JThread, self: JObject, cls: string): JArray { let m = stateSlots.get(t.vm); if (!m) stateSlots.set(t.vm, (m = new Map())); let slot = m.get(cls); - if (slot === undefined) m.set(cls, (slot = t.vm.slotOf(cls, "state"))); - return self.f[slot] as JArray; + if (slot === undefined) m.set(cls, (slot = t.vm.keyOf(cls, "state"))); + return self[slot] as JArray; } // big-endian 32-bit word of a byte array @@ -263,7 +263,7 @@ function montgomery(a: bigint, b: bigint, nArr: Int32Array, len: number, inv: bi } // AESCrypt's round tables and the slots of its key schedule fields -interface Aes { T1: Int32Array; T2: Int32Array; T3: Int32Array; T4: Int32Array; S: Int8Array; K: number; limit: number } +interface Aes { T1: Int32Array; T2: Int32Array; T3: Int32Array; T4: Int32Array; S: Int8Array; K: FieldKey; limit: FieldKey } const aesTables = new WeakMap(); function aes(t: JThread, self: JObject): Aes { let a = aesTables.get(t.vm); @@ -272,7 +272,7 @@ function aes(t: JThread, self: JObject): Aes { const table = (name: string) => (vm.getStatic(c, name) as JArray).a as any; a = { T1: table("T1"), T2: table("T2"), T3: table("T3"), T4: table("T4"), S: table("S"), - K: vm.slotOf(AES, "K"), limit: vm.slotOf(AES, "limit"), + K: vm.keyOf(AES, "K"), limit: vm.keyOf(AES, "limit"), }; aesTables.set(vm, a); } @@ -291,7 +291,7 @@ function aesLast(out: Int8Array, o: number, S: Int8Array, a: number, b: number, // its callers (FeedbackCipher.encrypt and the modes) make them. function aesEncrypt(t: JThread, self: JObject, inp: Int8Array, i: number, out: Int8Array, o: number) { const { T1, T2, T3, T4, S, K: kSlot, limit: limitSlot } = aes(t, self); - const K = (self.f[kSlot] as JArray).a as Int32Array, limit = self.f[limitSlot] as number; + const K = (self[kSlot] as JArray).a as Int32Array, limit = self[limitSlot] as number; let t0 = word(inp, i) ^ K[0], t1 = word(inp, i + 4) ^ K[1], t2 = word(inp, i + 8) ^ K[2], t3 = word(inp, i + 12) ^ K[3]; let k = 4; while (k < limit) { diff --git a/src/natives/lang.ts b/src/natives/lang.ts index 14f0519..70531b3 100644 --- a/src/natives/lang.ts +++ b/src/natives/lang.ts @@ -4,7 +4,7 @@ import { isHidden } from "./stackwalk.ts"; import { gcStats, javaHeap } from "./management.ts"; import { assertionsEnabled } from "../assertions.ts"; import { normalize } from "../fs.ts"; -import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, newArrayData, releasePins, dataOf, monitorOf, setData } from "../runtime.ts"; +import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, dataOf, fieldsOf, monitorOf, newArrayData, releasePins, setData, setFields } from "../runtime.ts"; import type { Monitor } from "../runtime.ts"; import { canUnmount, dropOwned, unblockOnRelease } from "./continuation.ts"; import { collect, registerFinalizer, releaseFinalizerCycles, releaseSoftReferences } from "./ref.ts"; @@ -200,7 +200,8 @@ export function cloneObject(t: JThread, o: JObject): JObject { if (!o.cls.allSupers().has(t.vm.loadBoot("java/lang/Cloneable")!)) { throw new PendingThrow("java/lang/CloneNotSupportedException", o.cls.javaName); } - const copy = new JObject(o.cls, o.f.slice()); + const copy = new o.cls.ctor(o.cls); + setFields(copy, fieldsOf(o)); setData(copy, dataOf(o)); if (copy.cls.finalizable) registerFinalizer(t.vm, copy); return copy; diff --git a/src/natives/management.ts b/src/natives/management.ts index 880aaf4..7b146e2 100644 --- a/src/natives/management.ts +++ b/src/natives/management.ts @@ -4,7 +4,7 @@ // collector. Heap usage is the JS heap's; collections are the explicit // System.gc() calls, which HotSpot counts as full collections. -import { INITIALIZED, JArray, JClass, JObject, MAX_HEAP, dataOf, monitorOf } from "../runtime.ts"; +import { INITIALIZED, JArray, JClass, JObject, MAX_HEAP, dataOf, fieldsOf, monitorOf } from "../runtime.ts"; import type { JMethod } from "../runtime.ts"; import { Frame, JThread, NativeFrame, PendingThrow, STATUS_BLOCKED, STATUS_NEW, STATUS_PARKED, STATUS_PARKED_TIMED, STATUS_RUNNABLE, @@ -382,7 +382,7 @@ function* threadInfo(t: JThread, s: Snapshot, withStack: boolean, locks: Locks | // which keeps the lock and unlock paths as they are. function ownedSynchronizers(vm: JVM): Map { const aos = vm.loadBoot(AOS)!; - const slot = aos.findField("exclusiveOwnerThread")!.slot; + const ownerKey = aos.findField("exclusiveOwnerThread")!.key; const isSync = new Map(); const seen = new Set(); const classes = new Set(); @@ -417,7 +417,7 @@ function ownedSynchronizers(vm: JVM): Map { let sync = isSync.get(o.cls); if (sync === undefined) isSync.set(o.cls, (sync = o.cls.isAssignableTo(aos))); if (sync) { - const owner = o.f[slot]; + const owner = o[ownerKey]; if (owner) { const list = out.get(owner); if (list) list.push(o); @@ -427,7 +427,7 @@ function ownedSynchronizers(vm: JVM): Map { visitClass(o.cls); if (o instanceof JArray) { if (Array.isArray(o.a)) for (const v of o.a) visit(v); - } else for (const v of o.f) visit(v); + } else for (const v of fieldsOf(o)) visit(v); // a class loader keeps the classes it defined const x = dataOf(o); if (x instanceof JClass) visitClass(x); diff --git a/src/natives/misc.ts b/src/natives/misc.ts index 71c1f7d..3942b5d 100644 --- a/src/natives/misc.ts +++ b/src/natives/misc.ts @@ -1,7 +1,7 @@ // jdk.internal.misc (Unsafe, VM, CDS, Signal), system properties and other // low-level natives. -import { ARRAY_BASE_OFFSET, INITIALIZED, JArray, JClass, JMethod, JObject, STATIC_OFFSET_BASE, dataOf, setData } from "../runtime.ts"; +import { ARRAY_BASE_OFFSET, INITIALIZED, JArray, JClass, JMethod, JObject, STATIC_OFFSET_BASE, addField, casField, dataOf, readField, setData, swapField, writeField } from "../runtime.ts"; import { JThread, JavaThrow, PendingThrow, STATUS_PARKED, STATUS_PARKED_TIMED, STATUS_RUNNABLE } from "../thread.ts"; import type { NativeGen } from "../thread.ts"; import type { JVM } from "../jvm.ts"; @@ -122,9 +122,11 @@ export function unsafeGet(t: JThread, o: JObject | null, offset: bigint, k: stri if (sameKind(elem, k)) return o.a[(off - ARRAY_BASE_OFFSET) / WIDTH[elem]]; return arrayRead(o, off - ARRAY_BASE_OFFSET, k); } - const c = dataOf(o); - if (off >= STATIC_OFFSET_BASE && c instanceof JClass) return c.statics[off - STATIC_OFFSET_BASE]; - return o.f[off]; + if (off >= STATIC_OFFSET_BASE) { + const c = dataOf(o); + if (c instanceof JClass) return c.statics[off - STATIC_OFFSET_BASE]; + } + return readField(o, off); } export function unsafePut(t: JThread, o: JObject | null, offset: bigint, k: string, v: any) { @@ -140,12 +142,19 @@ export function unsafePut(t: JThread, o: JObject | null, offset: bigint, k: stri else arrayWrite(o, off - ARRAY_BASE_OFFSET, k, v); return; } - const c = dataOf(o); - if (off >= STATIC_OFFSET_BASE && c instanceof JClass) c.statics[off - STATIC_OFFSET_BASE] = v; - else o.f[off] = v; + const c = off >= STATIC_OFFSET_BASE ? dataOf(o) : undefined; + if (c instanceof JClass) c.statics[off - STATIC_OFFSET_BASE] = v; + else writeField(o, off, v); +} + +// an instance field of an object, as against an array element, a static or memory +function isInstanceField(o: JObject | null, off: number): o is JObject { + return o !== null && off < STATIC_OFFSET_BASE && !(o instanceof JArray); } function cas(t: JThread, o: JObject | null, off: bigint, k: string, expect: any, v: any): any { + const n = Number(off); + if (isInstanceField(o, n)) return casField(o, n, expect, v); const cur = unsafeGet(t, o, off, k); if (cur === expect) unsafePut(t, o, off, k, v); return cur; @@ -211,12 +220,16 @@ for (const [name, k, desc] of [["Int", "I", "I"], ["Long", "J", "J"], ["Referenc } for (const suffix of ["", "Acquire", "Release"]) { intrinsics[`${U}getAndSet${name}${suffix}(Ljava/lang/Object;J${desc})${desc}`] = (t, [, o, off, x]) => { + const n = Number(off); + if (isInstanceField(o, n)) return swapField(o, n, x); const old = unsafeGet(t, o, off, k); unsafePut(t, o, off, k, x); return old; }; if (k === "L") continue; intrinsics[`${U}getAndAdd${name}${suffix}(Ljava/lang/Object;J${desc})${desc}`] = (t, [, o, off, d]) => { + const n = Number(off); + if (isInstanceField(o, n)) return addField(o, n, d, k === "J"); const old = unsafeGet(t, o, off, k); unsafePut(t, o, off, k, k === "I" ? (old + d) | 0 : BigInt.asIntN(64, old + d)); return old; diff --git a/src/natives/ref.ts b/src/natives/ref.ts index bb07c84..363935c 100644 --- a/src/natives/ref.ts +++ b/src/natives/ref.ts @@ -6,7 +6,7 @@ // finalizer is watched too: its wrapper is collected, and the Finalizer gets a // new wrapper over the same storage. -import { INITIALIZED, MAX_HEAP, dataOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, setReclaim, wrapperOver } from "../runtime.ts"; +import { INITIALIZED, MAX_HEAP, dataOf, fieldsOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, setReclaim, wrapperOver } from "../runtime.ts"; import { JObject } from "../runtime.ts"; import type { JClass } from "../runtime.ts"; import { Signal } from "../thread.ts"; @@ -18,11 +18,12 @@ import type { Natives } from "./util.ts"; const R = "java/lang/ref/Reference"; // What a finalizable object's new wrapper needs. It must not lead back to the -// object: f is null once its fields are found to lead back to it (see forgetCycles). +// object: st, the object that holds its fields, is null once they are found to +// lead back to it (see forgetCycles). interface Fin { fin: JObject; cls: JClass; - f: any[] | null; + st: JObject | null; hash: number; x: any; } @@ -159,12 +160,12 @@ function probe(s: RefState, done: () => void) { function resurrect(vm: JVM, s: RefState, h: Fin) { const fin = h.fin; if (!(dataOf(fin) instanceof WeakRef)) return; - if (h.f === null) { + if (h.st === null) { // nothing to finalize: the Finalizer thread unlinks it, and its finalize(null) fails quietly setData(fin, null); return addPending(s, fin); } - const o = wrapperOver(h.cls, h.f); + const o = wrapperOver(h.cls, h.st); setHash(o, h.hash); setData(o, h.x); setData(fin, null); @@ -196,9 +197,9 @@ export function registerFinalizer(vm: JVM, obj: JObject) { // it had no finalizer: the fields of an object found on a cycle are dropped. const CHECK_EVERY = 2048, SCAN_PER_OBJECT = 2000, SCAN_WHILE_RUNNING = 20000, SCAN_AT_GC = 200000; -function leadsBack(w: JObject, f: any[], budget: { left: number }): boolean { +function leadsBack(w: JObject, st: JObject, budget: { left: number }): boolean { const seen = new Set(); - const todo: any[][] = [f]; + const todo: any[][] = [fieldsOf(st)]; let scanned = 0; while (todo.length) { for (const v of todo.pop()!) { @@ -210,7 +211,7 @@ function leadsBack(w: JObject, f: any[], budget: { left: number }): boolean { budget.left -= scanned; return false; } - todo.push(v.f); + todo.push(fieldsOf(v)); const a = (v as { a?: unknown }).a; if (Array.isArray(a)) todo.push(a); } @@ -227,10 +228,10 @@ function forgetCycles(s: RefState, scan: number): boolean { let i = 0; for (; i < list.length && budget.left > 0; i++) { const h = list[i]; - const fx = h.f !== null ? dataOf(h.fin) : undefined; + const fx = h.st !== null ? dataOf(h.fin) : undefined; const w = fx instanceof WeakRef ? fx.deref() : undefined; if (w === undefined) continue; - if (leadsBack(w, h.f!, budget)) h.f = null; + if (leadsBack(w, h.st!, budget)) h.st = null; else kept.push(h); } const released = i - kept.length; @@ -244,7 +245,7 @@ export function releaseFinalizerCycles(vm: JVM) { function watchFinalizer(vm: JVM, s: RefState, fin: JObject, obj: JObject) { setData(fin, new WeakRef(obj)); - const h: Fin = { fin, cls: obj.cls, f: obj.f, hash: vm.identityHash(obj), x: dataOf(obj) }; + const h: Fin = { fin, cls: obj.cls, st: (obj as unknown as { st: JObject }).st, hash: vm.identityHash(obj), x: dataOf(obj) }; s.fins.push(h); s.registry.register(obj, h, fin); } diff --git a/src/natives/strings.ts b/src/natives/strings.ts index 7d2db1c..bcddcc5 100644 --- a/src/natives/strings.ts +++ b/src/natives/strings.ts @@ -6,7 +6,7 @@ // The jimage string reader is here too. import { JArray, MAX_HEAP, newArrayData } from "../runtime.ts"; -import type { JClass, JObject } from "../runtime.ts"; +import type { FieldKey, JClass, JObject } from "../runtime.ts"; import { PendingThrow } from "../thread.ts"; import type { JThread } from "../thread.ts"; import type { JVM } from "../jvm.ts"; @@ -17,16 +17,16 @@ const SOFT_MAX = 0x7fffffff - 8; let slotVm: JVM | null = null; let strClass: JClass; -let sbValue = 0, sbCoder = 0, sbCount = 0, sbMaybeLatin1 = 0, strValue = 0, strCoder = 0; +let sbValue: FieldKey = "f0", sbCoder: FieldKey = "f0", sbCount: FieldKey = "f0", sbMaybeLatin1: FieldKey = "f0", strValue: FieldKey = "f0", strCoder: FieldKey = "f0"; function slots(vm: JVM) { if (slotVm === vm) return; - sbValue = vm.slotOf(ASB, "value"); - sbCoder = vm.slotOf(ASB, "coder"); - sbCount = vm.slotOf(ASB, "count"); - sbMaybeLatin1 = vm.slotOf(ASB, "maybeLatin1"); - strValue = vm.slotOf(STR, "value"); - strCoder = vm.slotOf(STR, "coder"); + sbValue = vm.keyOf(ASB, "value"); + sbCoder = vm.keyOf(ASB, "coder"); + sbCount = vm.keyOf(ASB, "count"); + sbMaybeLatin1 = vm.keyOf(ASB, "maybeLatin1"); + strValue = vm.keyOf(STR, "value"); + strCoder = vm.keyOf(STR, "coder"); strClass = vm.loadBootOrFail(STR); slotVm = vm; } @@ -61,12 +61,12 @@ function appendString(t: JThread, args: any[]): JObject { const vm = t.vm; slots(vm); const s = str ?? vm.intern("null"); - const sBytes = (s.f[strValue] as JArray).a as Int8Array; - const sCoder = s.f[strCoder] as number; + const sBytes = (s[strValue] as JArray).a as Int8Array; + const sCoder = s[strCoder] as number; const len = sBytes.length >> sCoder; - const coder = self.f[sbCoder] as number; - const count = self.f[sbCount] as number; - let value = (self.f[sbValue] as JArray).a as Int8Array; + const coder = self[sbCoder] as number; + const count = self[sbCount] as number; + let value = (self[sbValue] as JArray).a as Int8Array; const newCoder = coder | sCoder; const min = (count + len) | 0; const old = value.length >> coder; @@ -83,12 +83,12 @@ function appendString(t: JThread, args: any[]): JObject { inflate(value, count, buf, 0); value = buf; } - self.f[sbValue] = new JArray((self.f[sbValue] as JArray).cls, value); - self.f[sbCoder] = newCoder; + self[sbValue] = new JArray((self[sbValue] as JArray).cls, value); + self[sbCoder] = newCoder; } if (sCoder === newCoder) value.set(sBytes, count << newCoder); else inflate(sBytes, len, value, count); - self.f[sbCount] = min; + self[sbCount] = min; return self; } @@ -96,11 +96,11 @@ function appendString(t: JThread, args: any[]): JObject { function stringFromBuilder(t: JThread, args: any[]) { const self: JObject = args[0], sb: JObject = args[1]; slots(t.vm); - const src = (sb.f[sbValue] as JArray).a as Int8Array; - const count = sb.f[sbCount] as number; - let coder = sb.f[sbCoder] as number; + const src = (sb[sbValue] as JArray).a as Int8Array; + const count = sb[sbCount] as number; + let coder = sb[sbCoder] as number; let value: Int8Array; - if (coder === 1 && sb.f[sbMaybeLatin1]) { + if (coder === 1 && sb[sbMaybeLatin1]) { let i = 0; while (i < count && src[i * 2 + 1] === 0) i++; if (i === count) { @@ -113,8 +113,8 @@ function stringFromBuilder(t: JThread, args: any[]) { } function fill(vm: JVM, s: JObject, value: Int8Array, coder: number) { - s.f[strValue] = new JArray(vm.primArrayClass("B"), value); - s.f[strCoder] = coder; + s[strValue] = new JArray(vm.primArrayClass("B"), value); + s[strCoder] = coder; } function copy(src: Int8Array, n: number): Int8Array { @@ -133,9 +133,9 @@ export function concatStrings(t: JThread, pc: number, parts: (JObject | null)[]) let chars = 0, coder = 0; for (let i = 0; i < parts.length; i++) { const s = parts[i] ?? nul!; - const c = s.f[strCoder] as number; + const c = s[strCoder] as number; coder |= c; - chars += (s.f[strValue] as JArray).a.length >> c; + chars += (s[strValue] as JArray).a.length >> c; } let value: Int8Array; try { @@ -147,8 +147,8 @@ export function concatStrings(t: JThread, pc: number, parts: (JObject | null)[]) let at = 0; for (let i = 0; i < parts.length; i++) { const s = parts[i] ?? nul!; - const bytes = (s.f[strValue] as JArray).a as Int8Array; - const c = s.f[strCoder] as number; + const bytes = (s[strValue] as JArray).a as Int8Array; + const c = s[strCoder] as number; const len = bytes.length >> c; if (c === coder) value.set(bytes, at << coder); else inflate(bytes, len, value, at); @@ -166,15 +166,15 @@ 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; + const limit = buf[vm.keyOf("java/nio/Buffer", "limit")] as number; + const hb = buf[vm.keyOf("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; + base = buf[vm.keyOf("java/nio/ByteBuffer", "offset")] as number; } else { bytes = vm.mem.u8; - base = Number(buf.f[vm.slotOf("java/nio/Buffer", "address")] as bigint); + base = Number(buf[vm.keyOf("java/nio/Buffer", "address")] as bigint); } if (offset < 0) { throw new PendingThrow("java/lang/IndexOutOfBoundsException", `Index ${offset} out of bounds for length ${limit}`); diff --git a/src/runtime.ts b/src/runtime.ts index 972613e..1f85468 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -80,6 +80,8 @@ export class JField { private attrsRaw: Map | number; readonly wide: boolean; slot = -1; + // the property of an instance field's object + key: FieldKey = "f0"; index = 0; constructor(cls: JClass, m: Member) { this.cls = cls; @@ -171,17 +173,169 @@ export class JMethod { } } +// Instance fields are properties f0, f1, ... of the object. Classes whose fields +// have the same kinds share one constructor, and so one engine shape. +export type FieldKey = `f${number}`; +const KEYS: FieldKey[] = []; +export function fieldKey(slot: number): FieldKey { + return KEYS[slot] ?? (KEYS[slot] = `f${slot}`); +} + export class JObject { cls: JClass; - f: any[]; // what most objects never need: null, the identity hash once taken, or a // Monitor (which also holds the hash and the VM-side data) s: number | Monitor | null = null; - constructor(cls: JClass, f: any[]) { + [field: FieldKey]: any; + constructor(cls: JClass) { this.cls = cls; - this.f = f; - if (allocationCheck?.enabled) allocated(32); - } + if (alloc.check?.enabled) allocated(32); + } +} + +// A field by slot number, for offsets that arrive as numbers (Unsafe). Each +// slot has its own functions, so the engine caches the property per slot, not +// per call site, and a read-modify-write touches the object once. +const MAX_FAST_SLOT = 4096; +type SlotFns = { read: (o: JObject) => any; write: (o: JObject, v: any) => void; cas: (o: JObject, e: any, v: any) => any; swap: (o: JObject, v: any) => any; add: (o: JObject, d: any) => any; addLong: (o: JObject, d: bigint) => bigint }; +const slotFns: SlotFns[] = []; +function fnsFor(slot: number): SlotFns | null { + if (!(slot >= 0 && slot < MAX_FAST_SLOT && Number.isInteger(slot))) return null; + return (slotFns[slot] ??= { + read: new Function("o", `return o.f${slot}`) as SlotFns["read"], + write: new Function("o", "v", `o.f${slot}=v`) as SlotFns["write"], + cas: new Function("o", "e", "v", `const c=o.f${slot};if(c===e)o.f${slot}=v;return c`) as SlotFns["cas"], + swap: new Function("o", "v", `const c=o.f${slot};o.f${slot}=v;return c`) as SlotFns["swap"], + add: new Function("o", "d", `const c=o.f${slot};o.f${slot}=(c+d)|0;return c`) as SlotFns["add"], + addLong: new Function("o", "d", `const c=o.f${slot};o.f${slot}=BigInt.asIntN(64,c+d);return c`) as SlotFns["addLong"], + }); +} +export function readField(o: JObject, slot: number): any { + const f = fnsFor(slot); + return f ? f.read(o) : o[fieldKey(slot)]; +} +export function writeField(o: JObject, slot: number, v: any) { + const f = fnsFor(slot); + if (f) f.write(o, v); + else o[fieldKey(slot)] = v; +} +// the old value; the field is set to v when it was e +export function casField(o: JObject, slot: number, e: any, v: any): any { + const f = fnsFor(slot); + if (f) return f.cas(o, e, v); + const c = o[fieldKey(slot)]; + if (c === e) o[fieldKey(slot)] = v; + return c; +} +// the old value; the field is set to v +export function swapField(o: JObject, slot: number, v: any): any { + const f = fnsFor(slot); + if (f) return f.swap(o, v); + const c = o[fieldKey(slot)]; + o[fieldKey(slot)] = v; + return c; +} +// the old value; an int field gets old + d, a long field the 64-bit sum +export function addField(o: JObject, slot: number, d: any, long: boolean): any { + const f = fnsFor(slot); + if (f) return long ? f.addLong(o, d) : f.add(o, d); + const c = o[fieldKey(slot)]; + o[fieldKey(slot)] = long ? BigInt.asIntN(64, c + d) : (c + d) | 0; + return c; +} + +// dump and load read and write all instance fields at once, by slot. +export interface ObjCtor { + new (cls: JClass): JObject; + dump(o: JObject): any[]; + load(o: JObject, f: ArrayLike): void; +} +const ctors = new Map(); + +// One character per instance field slot: J long, L reference, D float or +// double, I the rest. +function kindOf(desc: string): string { + const c = desc[0]; + return c === "[" ? "L" : c === "F" ? "D" : c === "B" || c === "C" || c === "S" || c === "Z" ? "I" : c; +} + +function kindsOf(c: JClass): string { + const chain: JClass[] = []; + for (let k: JClass | null = c; k; k = k.superclass) chain.push(k); + let kinds = ""; + for (let i = chain.length - 1; i >= 0; i--) for (const f of chain[i].fields) if (!f.isStatic) kinds += kindOf(f.desc); + return kinds; +} + +function withAccess(C: unknown, kinds: string): ObjCtor { + const T = C as ObjCtor; + // generated on first use: boot does not need them + T.dump = (o) => { + let body = "return["; + for (let i = 0; i < kinds.length; i++) body += `o.f${i},`; + return (T.dump = new Function("o", `${body}]`) as ObjCtor["dump"])(o); + }; + T.load = (o, f) => { + let body = ""; + for (let i = 0; i < kinds.length; i++) body += `o.f${i}=f[${i}];`; + (T.load = new Function("o", "f", body) as ObjCtor["load"])(o, f); + }; + return T; +} + +function ctorFor(kinds: string): ObjCtor { + let C = ctors.get(kinds); + if (C) return C; + if (kinds === "") C = withAccess(JObject, kinds); + else { + let body = "this.cls=cls;this.s=null;"; + for (let i = 0; i < kinds.length; i++) body += `this.f${i}=${kinds[i] === "J" ? "0n" : kinds[i] === "L" ? "null" : "0"};`; + const Obj = new Function("A", "T", `return function Obj(cls){${body}if(A.check!==null&&A.check.enabled)T(32);}`)(alloc, allocated); + Obj.prototype = JObject.prototype; + C = withAccess(Obj, kinds); + } + ctors.set(kinds, C); + return C; +} + +// An object whose class has a finalizer keeps its fields in a second object, +// st, which the Finalizer holds too: the engine collects the object, and the +// fields live on for finalize(). The fields are accessors over st. +const finalizableCtors = new Map(); +function finalizableCtorFor(kinds: string): ObjCtor { + let C = finalizableCtors.get(kinds); + if (C) return C; + const Storage = ctorFor(kinds); + let accessors = ""; + for (let i = 0; i < kinds.length; i++) accessors += `get f${i}(){return this.st.f${i}},set f${i}(v){this.st.f${i}=v},`; + const Obj = new Function("P", "S", "A", "T", ` + const proto = Object.create(P, Object.getOwnPropertyDescriptors({${accessors}})); + function Obj(cls){this.cls=cls;this.s=null;this.st=new S(cls);if(A.check!==null&&A.check.enabled)T(32);} + Obj.prototype = proto; + return Obj;`)(JObject.prototype, Storage, alloc, allocated); + C = withAccess(Obj, kinds); + finalizableCtors.set(kinds, C); + return C; +} + +// A class's constructor is made the first time one of its objects is. +const lazyCtor = function (cls: JClass): JObject { + return new (ensureCtor(cls))(cls); +} as unknown as ObjCtor; + +export function ensureCtor(c: JClass): ObjCtor { + if (c.ctor !== lazyCtor) return c.ctor; + const kinds = kindsOf(c); + return (c.ctor = c.finalizable ? finalizableCtorFor(kinds) : ctorFor(kinds)); +} + +// The values of an object's instance fields, by slot. +export function fieldsOf(o: JObject): any[] { + return ensureCtor(o.cls).dump(o); +} + +export function setFields(o: JObject, f: ArrayLike) { + ensureCtor(o.cls).load(o, f); } export function monitorOf(o: JObject): Monitor | null { @@ -247,9 +401,9 @@ export function trackArrays(): () => number { export class JArray extends JObject { a: ArrayData; constructor(cls: JClass, a: ArrayData) { - super(cls, EMPTY); + super(cls); this.a = a; - if (allocationCheck?.enabled) { + if (alloc.check?.enabled) { const bytes = ArrayBuffer.isView(a) ? a.byteLength : a.length * 8; allocated(bytes); if (trackingArrays && bytes >= TRACK_MIN) { @@ -260,8 +414,6 @@ export class JArray extends JObject { } } -const EMPTY: any[] = []; - export class Monitor { owner: JThread | null = null; count = 0; @@ -340,7 +492,7 @@ export class JClass { methods: JMethod[] = []; methodMap = new Map(); instanceSlots = 0; - template: any[] = []; + ctor: ObjCtor = lazyCtor; statics: any[] = []; state = LOADED; initThread: JThread | null = null; @@ -527,11 +679,11 @@ interface AllocationCheck { // no gc(): the engine frees garbage between tasks, see lazyOver lazy: boolean; } -let allocationCheck: AllocationCheck | null = null; +const alloc: { check: AllocationCheck | null } = { check: null }; export function setAllocationCheck(cap: number, usage: () => number, o: { gc?: () => void; lazy?: boolean } = {}) { - allocationCheck = { cap, step: Math.min(cap, Math.max(4 << 20, cap / 16)), allocated: 0, baseline: 0, enabled: false, over: false, usage, gc: o.gc, lazy: !!o.lazy }; + alloc.check = { cap, step: Math.min(cap, Math.max(4 << 20, cap / 16)), allocated: 0, baseline: 0, enabled: false, over: false, usage, gc: o.gc, lazy: !!o.lazy }; } -export function clearAllocationCheck() { allocationCheck = null; } +export function clearAllocationCheck() { alloc.check = null; } // Lets go of what the VM holds for the program's sake (soft referents, caches // of unloadable classes) before an OutOfMemoryError; returns whether there was any. let reclaim: (() => boolean) | null = null; @@ -539,30 +691,32 @@ export function setReclaim(f: () => boolean) { reclaim = f; } // An allocation that cannot succeed still collects first, as HotSpot does, so // the program sees soft references cleared and unloaded classes gone. function collectBeforeGivingUp() { - if (reclaim?.()) (allocationCheck?.gc ?? (globalThis as { gc?: () => void }).gc)?.(); + if (reclaim?.()) (alloc.check?.gc ?? (globalThis as { gc?: () => void }).gc)?.(); } // A JObject made while a collection hands a finalizable object to its Finalizer: // it is not an allocation that can fail. -export function wrapperOver(cls: JClass, f: any[]): JObject { - const check = allocationCheck; +export function wrapperOver(cls: JClass, st: JObject): JObject { + const check = alloc.check; const was = check?.enabled; if (check) check.enabled = false; try { - return new JObject(cls, f); + const o = new (ensureCtor(cls))(cls); + (o as unknown as { st: JObject }).st = st; + return o; } finally { if (check) check.enabled = was!; } } // Java heap bytes still free under the cap, measured as the cap is. export function freeHeap(): number { - const check = allocationCheck; + const check = alloc.check; return check?.enabled ? MAX_HEAP - (check.usage() - check.baseline) : MAX_HEAP; } export function resetAllocationCheck() { - if (!allocationCheck) return; - allocationCheck.baseline = allocationCheck.usage(); - allocationCheck.allocated = 0; - allocationCheck.enabled = true; + if (!alloc.check) return; + alloc.check.baseline = alloc.check.usage(); + alloc.check.allocated = 0; + alloc.check.enabled = true; } // Browsers have no gc(). Arrays the program dropped keep counting until the @@ -614,7 +768,7 @@ function lazyOver(check: AllocationCheck) { } function allocated(bytes: number) { - const check = allocationCheck; + const check = alloc.check; if (!check?.enabled || bytes <= 0) return; check.allocated += bytes; if (check.allocated < (check.gc || check.lazy ? check.step : check.cap)) return; diff --git a/src/snapshot.ts b/src/snapshot.ts index 6a485f4..5a8de4e 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -11,13 +11,13 @@ import { restorePending, restoreReference } from "./natives/ref.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, dataOf, hashOf, monitorOf, setData, setHash } from "./runtime.ts"; +import { JArray, JClass, JField, JMethod, JObject, Monitor, dataOf, fieldsOf, hashOf, monitorOf, setData, setFields, setHash } from "./runtime.ts"; import { restoreJit } from "./jit.ts"; import { Frame, JThread, NativeFrame, STATUS_RUNNABLE, Signal } from "./thread.ts"; import type { NativeGen } from "./thread.ts"; // Bump when the layout of an image changes; images of another format are ignored. -export const SNAPSHOT_FORMAT = 3; +export const SNAPSHOT_FORMAT = 4; export interface SnapshotImage { format: number; @@ -217,7 +217,7 @@ class Encoder { private isLeaf(v: JObject): boolean { if (monitorOf(v) !== null) return false; - const list = v instanceof JArray ? v.a : v.f; + const list = v instanceof JArray ? v.a : fieldsOf(v); if (!Array.isArray(list)) return true; for (const e of list) if (e !== null && (typeof e === "function" || (typeof e === "object" && !ArrayBuffer.isView(e) && !(e instanceof ArrayBuffer)))) return false; return true; @@ -233,7 +233,7 @@ class Encoder { this.work.push(() => { if (array && !Array.isArray(v.a)) t.a = v.a; else { - const { v: list, r } = this.values(array ? (v.a as unknown[]) : v.f, path, next); + const { v: list, r } = this.values(array ? (v.a as unknown[]) : fieldsOf(v), path, next); t[array ? "a" : "f"] = list; if (r) t.r = r; } @@ -313,7 +313,7 @@ class Decoder { case "O": case "A": { const cls = this.classes[v.c]; if (!cls) throw new Error(`snapshot: object of class #${v.c} before its class`); - o = v.$ === "A" ? new JArray(cls, v.a) : new JObject(cls, v.f); + o = v.$ === "A" ? new JArray(cls, v.a) : new cls.ctor(cls); if (v.h) setHash(o, v.h); break; } @@ -357,6 +357,7 @@ class Decoder { } switch (v.$) { case "O": case "A": + if (v.$ === "O") setFields(o, list!); if (v.n) { const m: Monitor = this.dec(v.n); m.hash = hashOf(o); diff --git a/test/java/ObjectLayout.java b/test/java/ObjectLayout.java new file mode 100644 index 0000000..e786b7e --- /dev/null +++ b/test/java/ObjectLayout.java @@ -0,0 +1,151 @@ +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.lang.ref.WeakReference; +import java.lang.reflect.Field; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + +// Instance fields of every kind in classes of different shapes: reads, writes, +// inheritance, clone, reflection, field updaters, VarHandles, and an identity +// hash and a monitor taken on the same object in either order. +public class ObjectLayout { + static class Empty { } + + static class Mixed implements Cloneable { + boolean z; byte b; char c; short s; int i; long j; float f; double d; Object o; String str; int[] arr; + volatile int vi; volatile long vj; volatile Object vo; + + @Override + public Mixed clone() { + try { + return (Mixed) super.clone(); + } catch (CloneNotSupportedException e) { + throw new AssertionError(e); + } + } + + @Override + public String toString() { + return z + " " + (int) b + " " + (int) c + " " + s + " " + i + " " + j + " " + f + " " + d + " " + o + " " + str + + " " + (arr == null ? null : arr.length) + " " + vi + " " + vj + " " + vo; + } + } + + static class Base { int a = 1; long b = 2; Object c = "base"; } + static class Middle extends Base { double d = 3.5; int e = 4; } + static class Leaf extends Middle { Object f = "leaf"; long g = 5; float h = 6.25f; } + static class OtherLeaf extends Middle { long f = 7; Object g = "other"; } + + static class Wide { + int f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19; + long g0 = 1, g1 = 2, g2 = 3; + double h0 = 0.5, h1 = 1.5; + Object o0 = "o0", o1; + } + + static class Counter { + volatile int count; + volatile long total; + volatile Object last; + } + + static final AtomicIntegerFieldUpdater COUNT = AtomicIntegerFieldUpdater.newUpdater(Counter.class, "count"); + static final AtomicLongFieldUpdater TOTAL = AtomicLongFieldUpdater.newUpdater(Counter.class, "total"); + static final AtomicReferenceFieldUpdater LAST = AtomicReferenceFieldUpdater.newUpdater(Counter.class, Object.class, "last"); + + static class Holder { + volatile int x; + long y; + Object z; + } + + public static void main(String[] args) throws Exception { + Object empty = new Empty(); + System.out.println(empty.getClass().getName() + " " + (empty.hashCode() == empty.hashCode())); + + Mixed m = new Mixed(); + System.out.println(m); + m.z = true; m.b = -5; m.c = 'x'; m.s = -300; m.i = Integer.MIN_VALUE; m.j = Long.MIN_VALUE; m.f = 1.5f; m.d = Math.PI; + m.o = "obj"; m.str = "text"; m.arr = new int[3]; m.vi = 9; m.vj = 1L << 40; m.vo = m; + Mixed copy = m.clone(); + m.i = 0; + m.j = 0; + System.out.println(copy + " " + (copy.vo == m) + " " + (copy.arr == m.arr)); + m.f = 0.1f; + m.d = -0.0; + System.out.println(m.f + " " + m.d + " " + (1 / m.d)); + m.d = 1e300 * 1e10; + m.f = Float.NaN; + System.out.println(m.d + " " + m.f); + + Base[] bases = { new Base(), new Middle(), new Leaf(), new OtherLeaf() }; + for (Base b : bases) { + StringBuilder sb = new StringBuilder(b.getClass().getSimpleName()).append(' ').append(b.a).append(' ').append(b.b).append(' ').append(b.c); + if (b instanceof Middle mid) sb.append(' ').append(mid.d).append(' ').append(mid.e); + if (b instanceof Leaf l) sb.append(' ').append(l.f).append(' ').append(l.g).append(' ').append(l.h); + if (b instanceof OtherLeaf l) sb.append(' ').append(l.f).append(' ').append(l.g); + System.out.println(sb); + } + + Wide w = new Wide(); + w.f19 = 19; w.g2 = Long.MAX_VALUE; w.h1 = 2.25; w.o1 = w; + System.out.println(w.f0 + " " + w.f19 + " " + w.g0 + " " + w.g2 + " " + w.h0 + " " + w.h1 + " " + w.o0 + " " + (w.o1 == w)); + + Counter c = new Counter(); + COUNT.incrementAndGet(c); + COUNT.compareAndSet(c, 1, 5); + TOTAL.addAndGet(c, 1L << 33); + LAST.compareAndSet(c, null, "first"); + LAST.compareAndSet(c, "other", "second"); + System.out.println(c.count + " " + c.total + " " + c.last); + + Holder h = new Holder(); + VarHandle X = MethodHandles.lookup().findVarHandle(Holder.class, "x", int.class); + VarHandle Y = MethodHandles.lookup().findVarHandle(Holder.class, "y", long.class); + VarHandle Z = MethodHandles.lookup().findVarHandle(Holder.class, "z", Object.class); + X.set(h, 3); + System.out.println((int) X.getAndAdd(h, 4) + " " + h.x + " " + (int) X.getVolatile(h)); + Y.set(h, -1L); + System.out.println((long) Y.compareAndExchange(h, -1L, 8L) + " " + h.y); + System.out.println(Z.compareAndSet(h, null, "set") + " " + h.z); + + for (Field f : Mixed.class.getDeclaredFields()) { + f.setAccessible(true); + if (f.getName().equals("i")) f.setInt(copy, 77); + if (f.getName().equals("str")) f.set(copy, "reflected"); + if (f.getName().equals("d")) f.setDouble(copy, 0.25); + } + Field jf = Mixed.class.getDeclaredField("j"); + jf.setAccessible(true); + System.out.println(copy.i + " " + copy.str + " " + copy.d + " " + jf.getLong(copy) + " " + jf.get(copy).getClass().getSimpleName()); + + Object o = new Object(); + int hash = o.hashCode(); + synchronized (o) { + System.out.println(hash == o.hashCode()); + o.wait(1); + } + System.out.println(hash == System.identityHashCode(o)); + Object p = new Object(); + synchronized (p) { + p.notifyAll(); + } + int phash = p.hashCode(); + synchronized (p) { + System.out.println(phash == p.hashCode()); + } + System.out.println(Thread.holdsLock(p)); + + WeakReference ref = new WeakReference<>(new Leaf()); + System.out.println(ref.get() != null || ref.get() == null); + Thread t = new Thread(() -> { }); + t.start(); + t.join(); + System.out.println(t.getState()); + Class k = Mixed.class; + synchronized (k) { + System.out.println(k.hashCode() == k.hashCode()); + } + } +} From edf898ae457da9b76d92fc1423804e3644e29ac7 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:29:07 -0600 Subject: [PATCH 3/3] test: print the class of Mixed.vo in ObjectLayout so toString does not recurse into itself --- test/java/ObjectLayout.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/java/ObjectLayout.java b/test/java/ObjectLayout.java index e786b7e..b7d0255 100644 --- a/test/java/ObjectLayout.java +++ b/test/java/ObjectLayout.java @@ -28,7 +28,7 @@ public Mixed clone() { @Override public String toString() { return z + " " + (int) b + " " + (int) c + " " + s + " " + i + " " + j + " " + f + " " + d + " " + o + " " + str - + " " + (arr == null ? null : arr.length) + " " + vi + " " + vj + " " + vo; + + " " + (arr == null ? null : arr.length) + " " + vi + " " + vj + " " + (vo == null ? null : vo.getClass().getSimpleName()); } }