diff --git a/docs/support.md b/docs/support.md index 710c3f5..1d9a7fc 100644 --- a/docs/support.md +++ b/docs/support.md @@ -51,7 +51,8 @@ java-web targets headless Java: console apps, libraries and javac. `--finalization=disabled`) and Cleaners run, and a class loader that nothing refers to is unloaded with its classes and hidden classes. Soft references are cleared before an `OutOfMemoryError`, and by `System.gc()` when more than - half the heap limit is in use. + half the heap limit is in use. `System.gc()` collects only when a host collector + is available, so not under `--freeze-flags-after-init` without `--expose-gc`. An object with a finalizer is finalized only if no cycle leads from its own fields back to it (JS cannot finalize such an object): the VM drops the finalizer of an object it finds on such a cycle, so the object is freed diff --git a/src/jit.ts b/src/jit.ts index fc13e51..e798543 100644 --- a/src/jit.ts +++ b/src/jit.ts @@ -15,7 +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, dataOf } from "./runtime.ts"; +import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, dataOf, evalBlocked } from "./runtime.ts"; import { memberTarget } from "./natives/invoke.ts"; import { concatStrings } from "./natives/strings.ts"; import { Frame, JavaThrow, NativeFrame, PendingThrow, fromNative } from "./thread.ts"; @@ -95,7 +95,7 @@ function compile(t: JThread, m: JMethod) { if (stats) stats.set(`compiled ${m}`, src.length); m.fallbacks = 0; } catch (e) { - if (e instanceof EvalError || (e instanceof Error && /unsafe-eval|Content Security/i.test(e.message))) disabled = true; + if (evalBlocked(e)) disabled = true; if (!(e instanceof Unsupported)) t.vm.debug("jit failed for", m.toString(), e); if (stats) stats.set(`nojit ${m}: ${e instanceof Error ? e.message : e}`, 1e9); m.noJit = true; diff --git a/src/jvm.ts b/src/jvm.ts index 231430d..36f49f3 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -12,7 +12,7 @@ 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, - fieldKey, sched, setData, setHash, + fieldKey, removeReclaim, sched, setData, setHash, } from "./runtime.ts"; import type { CallSite, FieldKey, NativeFn } from "./runtime.ts"; import { @@ -191,6 +191,8 @@ export class JVM { readonly props: Map; // per-VM state natives keep (open files, etc.) readonly state = new Map(); + // registered with runtime.ts while the VM runs + reclaim: (() => boolean) | null = null; readonly net: NetBackend; // pending sleeps and timed waits, cancelled on halt readonly timers = new Set>(); @@ -407,7 +409,9 @@ export class JVM { c.methodMap.set(m.key, m); } const fin = c.methodMap.get("finalize()V"); - c.finalizable = superclass?.finalizable === true || (fin !== undefined && !fin.isStatic && (fin.code?.code.length ?? 0) > 1); + // as HotSpot: only a body of one return (0xb1) is empty; a native finalize() counts + const emptyFin = fin?.code?.code.length === 1 && fin.code.code[0] === 0xb1; + c.finalizable = superclass?.finalizable === true || (fin !== undefined && !fin.isStatic && !emptyFin); // Runtime members own the metadata now; discard the parsed member records. cf.fields = []; cf.methods = []; @@ -1170,6 +1174,7 @@ export class JVM { halt(code: number) { if (this.exitCode !== null) return; this.exitCode = code; + if (this.reclaim) removeReclaim(this.reclaim); this.lib?.close(); for (const timer of this.timers) clearTimeout(timer); this.timers.clear(); diff --git a/src/natives/lang.ts b/src/natives/lang.ts index 70531b3..ed5dc6b 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, dataOf, fieldsOf, monitorOf, newArrayData, releasePins, setData, setFields } from "../runtime.ts"; +import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, collector, 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"; @@ -379,7 +379,7 @@ export const natives: Natives = { "java/lang/Runtime.gc()V": function* (t): NativeGen { const stats = gcStats(t.vm); stats.count++; - const gc = (globalThis as { gc?: () => void }).gc; + const gc = collector(); if (!gc) return; yield t.block(new Promise((r) => setTimeout(r, 0))); // values popped off an operand stack are not roots in HotSpot diff --git a/src/natives/ref.ts b/src/natives/ref.ts index 363935c..f389348 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, fieldsOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, setReclaim, wrapperOver } from "../runtime.ts"; +import { INITIALIZED, MAX_HEAP, dataOf, fieldsOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, addReclaim, wrapperOver } from "../runtime.ts"; import { JObject } from "../runtime.ts"; import type { JClass } from "../runtime.ts"; import { Signal } from "../thread.ts"; @@ -73,11 +73,12 @@ function refs(vm: JVM): RefState { softs: new WeakMap(), softCount: 0, }; - setReclaim(() => { + vm.reclaim = () => { const cycles = forgetCycles(s!, SCAN_AT_GC); const soft = clearSoftReferences(vm); return releasePins() || soft || cycles; - }); + }; + addReclaim(vm.reclaim); vm.state.set("refs", s); } return s; diff --git a/src/node.ts b/src/node.ts index 7dca092..f930801 100644 --- a/src/node.ts +++ b/src/node.ts @@ -22,7 +22,7 @@ import { NodeNet } from "./net-node.ts"; import { ENV_CHANNEL, javaChild, processNatives } from "./process-node.ts"; import { PendingThrow } from "./thread.ts"; import { heapSize } from "./heapsize.ts"; -import { clearAllocationCheck, hasMaxHeap, MAX_HEAP, resetAllocationCheck, setAllocationCheck, setMaxHeap } from "./runtime.ts"; +import { clearAllocationCheck, collector, hasMaxHeap, MAX_HEAP, resetAllocationCheck, setAllocationCheck, setGc, setMaxHeap } from "./runtime.ts"; import type { NetBackend } from "./sockets.ts"; // A host directory exposed read-only (or writable) inside the VFS. @@ -386,13 +386,14 @@ function fixedInput(data: Uint8Array) { const bridges = new WeakMap(); // The host file system is the VFS root, with the JDK image mounted at /jdk. -// System.gc() calls globalThis.gc, which node defines only under --expose-gc. +// System.gc() needs a collector: globalThis.gc, which node defines only under +// --expose-gc, is used as the host left it. // The engine keeps a WeakRef's target alive until the job that made or read it // ends, so a collection from inside running Java code would miss what Java // just dropped; a microtask checkpoint of another context ends the job. let jobEnd: Context | null = null; function exposeGc() { - const g = globalThis as { gc?: unknown }; + const g = globalThis as { gc?: () => void }; if (typeof g.gc !== "function") { // V8 aborts on a flag change once flags are frozen if (/(^|\s)--freeze-flags-after-init\b/.test([...process.execArgv, process.env.NODE_OPTIONS ?? ""].join(" "))) return; @@ -402,13 +403,11 @@ function exposeGc() { if (!gc) return; g.gc = gc; } - const gc = g.gc as (() => void) & { endsJob?: true }; - if (gc.endsJob) return; - const endingJob = Object.assign(() => { + const gc = g.gc!; + setGc(() => { runInContext("0", (jobEnd ??= createContext({}, { microtaskMode: "afterEvaluate" }))); gc(); - }, { endsJob: true as const }); - g.gc = endingJob; + }); } // Once the reader goes away (a closed pipe), writes fail with an IOException as @@ -600,11 +599,10 @@ export function nodeVm(o: LauncherOptions): JVM { const classpath = o.jar ? [toVfs(o.jar)] : o.classpath.map(toVfs); const natives = o.natives ?? {}; if (hasMaxHeap()) { - const gc = (globalThis as { gc?: () => void }).gc; setAllocationCheck(MAX_HEAP, () => { const m = process.memoryUsage(); return m.heapUsed + m.arrayBuffers; - }, { gc }); + }, { gc: collector() }); } else clearAllocationCheck(); const bridge = new Bridge({ call: (_, req) => vm.library.request(req), @@ -847,7 +845,7 @@ export function main(argv: string[]) { // Collecting first: node's exit teardown can deadlock while it frees very // large array buffers (seen on x64 CI runners with a few hundred MB left). Promise.resolve().then(() => runNode(o)).then(async (code) => { - globalThis.gc?.(); + collector()?.(); // output a pipe has not taken yet goes out before the process does const flushed = [process.stdout, process.stderr].map((s) => new Promise((done) => { s.write("", () => done()); })); await Promise.race([Promise.all(flushed), new Promise((done) => setTimeout(done, 10000).unref())]); diff --git a/src/runtime.ts b/src/runtime.ts index 1f85468..d734568 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -197,18 +197,36 @@ export class JObject { // 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; + +// Pages that forbid eval throw on the first new Function. Detect it once, then +// build accessors and constructors from closures. +let noEval = false; +export function evalBlocked(e: unknown): boolean { + return e instanceof EvalError || (e instanceof Error && /unsafe-eval|Content Security/i.test(e.message)); +} +function generate(make: () => T, fallback: () => T): T { + if (!noEval) { + try { + return make(); + } catch (e) { + if (!evalBlocked(e)) throw e; + noEval = true; + } + } + return fallback(); +} 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] ??= { + return slotFns[slot] ?? generate(() => (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"], - }); + }), () => null); } export function readField(o: JObject, slot: number): any { const f = fnsFor(slot); @@ -271,14 +289,22 @@ 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.dump = generate(() => { + let body = "return["; + for (let i = 0; i < kinds.length; i++) body += `o.f${i},`; + return new Function("o", `${body}]`) as ObjCtor["dump"]; + }, () => (o) => Array.from(kinds, (_, i) => o[fieldKey(i)])); + return T.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); + T.load = generate(() => { + let body = ""; + for (let i = 0; i < kinds.length; i++) body += `o.f${i}=f[${i}];`; + return new Function("o", "f", body) as ObjCtor["load"]; + }, () => (o, f) => { + for (let i = 0; i < kinds.length; i++) o[fieldKey(i)] = f[i]; + }); + T.load(o, f); }; return T; } @@ -288,9 +314,19 @@ function ctorFor(kinds: string): ObjCtor { 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); + const Obj = generate(() => { + 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"};`; + return new Function("A", "T", `return function Obj(cls){${body}if(A.check!==null&&A.check.enabled)T(32);}`)(alloc, allocated); + }, () => { + const zeros = Array.from(kinds, (k) => (k === "J" ? 0n : k === "L" ? null : 0)); + return function Obj(this: any, cls: JClass) { + this.cls = cls; + this.s = null; + for (let i = 0; i < zeros.length; i++) this[fieldKey(i)] = zeros[i]; + if (alloc.check !== null && alloc.check.enabled) allocated(32); + }; + }); Obj.prototype = JObject.prototype; C = withAccess(Obj, kinds); } @@ -306,13 +342,34 @@ 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 Obj = generate(() => { + 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},`; + return 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); + }, () => { + const proto = Object.create(JObject.prototype); + for (let i = 0; i < kinds.length; i++) { + const k = fieldKey(i); + Object.defineProperty(proto, k, { + get(this: any) { return this.st[k]; }, + set(this: any, v: any) { this.st[k] = v; }, + enumerable: true, + configurable: true, + }); + } + function Obj(this: any, cls: JClass) { + this.cls = cls; + this.s = null; + this.st = new Storage(cls); + if (alloc.check !== null && alloc.check.enabled) allocated(32); + } + Obj.prototype = proto; + return Obj; + }); C = withAccess(Obj, kinds); finalizableCtors.set(kinds, C); return C; @@ -684,14 +741,25 @@ export function setAllocationCheck(cap: number, usage: () => number, o: { gc?: ( 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() { 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; -export function setReclaim(f: () => boolean) { reclaim = f; } +// Lets go of what each VM holds for the program's sake (soft referents, caches +// of unloadable classes) before an OutOfMemoryError; true when there was any. +const reclaimers = new Set<() => boolean>(); +export function addReclaim(f: () => boolean) { reclaimers.add(f); } +export function removeReclaim(f: () => boolean) { reclaimers.delete(f); } +function reclaim(): boolean { + let any = false; + for (const f of reclaimers) if (f()) any = true; + return any; +} +// The collector java-web calls: its own wrapper, else the host's gc. A host's +// globalThis.gc is never replaced. +let vmGc: (() => void) | undefined; +export function setGc(f: () => void) { vmGc = f; } +export function collector(): (() => void) | undefined { return vmGc ?? (globalThis as { gc?: () => void }).gc; } // 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?.()) (alloc.check?.gc ?? (globalThis as { gc?: () => void }).gc)?.(); + if (reclaim()) (alloc.check?.gc ?? collector())?.(); } // A JObject made while a collection hands a finalizable object to its Finalizer: // it is not an allocation that can fail. @@ -776,7 +844,7 @@ function allocated(bytes: number) { if (check.usage() - check.baseline > check.cap) check.gc?.(); let over = check.usage() - check.baseline > check.cap; // soft references and unloadable classes go before an OutOfMemoryError, as in HotSpot - if (over && reclaim?.() && check.gc) { + if (over && reclaim() && check.gc) { check.gc(); over = check.usage() - check.baseline > check.cap; } diff --git a/src/snapshot.ts b/src/snapshot.ts index 5a8de4e..92f7628 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -624,11 +624,16 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) { }); d.flush(); restorePending(vm, d.now(v.pending)); - for (const [o, referent] of d.references) { - const r = d.dec(referent); - if (r) restoreReference(vm, o, r); - else setData(o, null); - } - d.flush(); + // decoding a referent can add references, so flush and go on until none are left + let i = 0; + do { + for (; i < d.references.length; i++) { + const [o, referent] = d.references[i]; + const r = d.dec(referent); + if (r) restoreReference(vm, o, r); + else setData(o, null); + } + d.flush(); + } while (i < d.references.length); for (const t of others) vm.startThread(t); } diff --git a/test/java/FinalizerCycles.java b/test/java/FinalizerCycles.java index 04a0263..ffb04de 100644 --- a/test/java/FinalizerCycles.java +++ b/test/java/FinalizerCycles.java @@ -20,17 +20,26 @@ static long used() { return r.totalMemory() - r.freeMemory(); } + // the used heap once finalizers stop freeing memory + static long settled() throws Exception { + long prev = Long.MAX_VALUE; + for (int i = 0; i < 25; i++) { + System.gc(); + System.runFinalization(); + Thread.sleep(20); + long now = used(); + if (prev - now < (1 << 20)) return Math.min(prev, now); + prev = now; + } + return prev; + } + public static void main(String[] args) throws Exception { long first = 0, last = 0; for (int round = 0; round < 5; round++) { for (int i = 0; i < 30000; i++) new Node(); - for (int k = 0; k < 5; k++) { - System.gc(); - System.runFinalization(); - Thread.sleep(20); - } - if (round == 1) first = used(); - last = used(); + last = settled(); + if (round == 1) first = last; } System.out.println("flat " + (last - first < (16 << 20))); } diff --git a/test/java/ObjectLayout.java b/test/java/ObjectLayout.java index b7d0255..d5236d1 100644 --- a/test/java/ObjectLayout.java +++ b/test/java/ObjectLayout.java @@ -137,8 +137,9 @@ public static void main(String[] args) throws Exception { } System.out.println(Thread.holdsLock(p)); - WeakReference ref = new WeakReference<>(new Leaf()); - System.out.println(ref.get() != null || ref.get() == null); + Leaf leaf = new Leaf(); + WeakReference ref = new WeakReference<>(leaf); + System.out.println(ref.get() == leaf); Thread t = new Thread(() -> { }); t.start(); t.join(); diff --git a/test/java/RefsAfterGc.java b/test/java/RefsAfterGc.java index d72db9e..0451be2 100644 --- a/test/java/RefsAfterGc.java +++ b/test/java/RefsAfterGc.java @@ -19,14 +19,14 @@ public static void main(String[] args) throws InterruptedException { WeakReference w = weak(q); PhantomReference p = phantom(q); System.gc(); - System.out.println("weak cleared " + (w.get() == null)); - System.out.println("phantom get " + p.get()); int n = 0; while (n < 2) { Reference r = q.remove(10000); if (r == null) break; n++; } + System.out.println("weak cleared " + (w.get() == null)); + System.out.println("phantom get " + p.get()); System.out.println("enqueued " + n); } } diff --git a/test/java/SoftRefs.java b/test/java/SoftRefs.java index 68c4ea0..25c7e18 100644 --- a/test/java/SoftRefs.java +++ b/test/java/SoftRefs.java @@ -1,4 +1,5 @@ // java: -Xmx16m +import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.ArrayList; @@ -41,5 +42,6 @@ public static void main(String[] args) throws Exception { int enqueued = 0; while (queue.remove(2000) != null) enqueued++; System.out.println("enqueued " + enqueued); + Reference.reachabilityFence(kept); } } diff --git a/test/programs.test.ts b/test/programs.test.ts index 4ac383c..f441e5c 100644 --- a/test/programs.test.ts +++ b/test/programs.test.ts @@ -74,6 +74,15 @@ test("System.gc collects under the command", { skip: !files.includes("Refs.java" assert.deepEqual({ stdout: got.stdout, code: got.status }, { stdout: ref.stdout, code: ref.status }); }); +// pages with a Content Security Policy without 'unsafe-eval' run without code generation +for (const main of ["Finalizers", "UnsafeAtomics"]) { + test(`${main} runs without code generation`, { skip: !files.includes(`${main}.java`) }, () => { + const ref = spawnSync(hotspot("java"), ["-cp", out, main], { encoding: "utf8" }); + const got = spawnSync(process.execPath, ["--disallow-code-generation-from-strings", join(root, "src", "node.ts"), "-cp", out, main], { encoding: "utf8" }); + assert.deepEqual({ stdout: got.stdout, code: got.status }, { stdout: ref.stdout, code: ref.status }); + }); +} + test("-Xmx caps an allocation under the command", () => { const classes = join(root, "build", "test-heap"); execFileSync(hotspot("javac"), ["-d", classes, join(root, "test", "heap", "Heap.java")]);