Skip to content

Commit 306a403

Browse files
authored
fix: create objects without code generation when eval is forbidden, keep the host's gc, and reclaim per VM (#105)
1 parent da92b6c commit 306a403

13 files changed

Lines changed: 157 additions & 58 deletions

File tree

‎docs/support.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ java-web targets headless Java: console apps, libraries and javac.
5151
`--finalization=disabled`) and Cleaners run, and a class loader that nothing
5252
refers to is unloaded with its classes and hidden classes. Soft references
5353
are cleared before an `OutOfMemoryError`, and by `System.gc()` when more than
54-
half the heap limit is in use.
54+
half the heap limit is in use. `System.gc()` collects only when a host collector
55+
is available, so not under `--freeze-flags-after-init` without `--expose-gc`.
5556
An object with a finalizer is finalized only if no cycle leads from its own
5657
fields back to it (JS cannot finalize such an object): the VM drops the
5758
finalizer of an object it finds on such a cycle, so the object is freed

‎src/jit.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
// interpreted call.
1616

1717
import { cpB, cpTag, cpValue, Tag, utf8 } from "./classfile.ts";
18-
import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, dataOf } from "./runtime.ts";
18+
import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, dataOf, evalBlocked } from "./runtime.ts";
1919
import { memberTarget } from "./natives/invoke.ts";
2020
import { concatStrings } from "./natives/strings.ts";
2121
import { Frame, JavaThrow, NativeFrame, PendingThrow, fromNative } from "./thread.ts";
@@ -95,7 +95,7 @@ function compile(t: JThread, m: JMethod) {
9595
if (stats) stats.set(`compiled ${m}`, src.length);
9696
m.fallbacks = 0;
9797
} catch (e) {
98-
if (e instanceof EvalError || (e instanceof Error && /unsafe-eval|Content Security/i.test(e.message))) disabled = true;
98+
if (evalBlocked(e)) disabled = true;
9999
if (!(e instanceof Unsupported)) t.vm.debug("jit failed for", m.toString(), e);
100100
if (stats) stats.set(`nojit ${m}: ${e instanceof Error ? e.message : e}`, 1e9);
101101
m.noJit = true;

‎src/jvm.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
ACC_ABSTRACT, ACC_FINAL, ACC_INTERFACE, ACC_NATIVE, ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC,
1313
ACC_STATIC, ACC_SUPER, ACC_VARARGS, ERRONEOUS, INITIALIZED, INITIALIZING, JArray, JClass, JField,
1414
JMethod, JObject, LINKED, Monitor, dataOf, defaultValue, dropsWithLoader, hashOf, monitorFor, monitorOf, newArrayData, noteYield,
15-
fieldKey, sched, setData, setHash,
15+
fieldKey, removeReclaim, sched, setData, setHash,
1616
} from "./runtime.ts";
1717
import type { CallSite, FieldKey, NativeFn } from "./runtime.ts";
1818
import {
@@ -191,6 +191,8 @@ export class JVM {
191191
readonly props: Map<string, string>;
192192
// per-VM state natives keep (open files, etc.)
193193
readonly state = new Map<string, any>();
194+
// registered with runtime.ts while the VM runs
195+
reclaim: (() => boolean) | null = null;
194196
readonly net: NetBackend;
195197
// pending sleeps and timed waits, cancelled on halt
196198
readonly timers = new Set<ReturnType<typeof setTimeout>>();
@@ -407,7 +409,9 @@ export class JVM {
407409
c.methodMap.set(m.key, m);
408410
}
409411
const fin = c.methodMap.get("finalize()V");
410-
c.finalizable = superclass?.finalizable === true || (fin !== undefined && !fin.isStatic && (fin.code?.code.length ?? 0) > 1);
412+
// as HotSpot: only a body of one return (0xb1) is empty; a native finalize() counts
413+
const emptyFin = fin?.code?.code.length === 1 && fin.code.code[0] === 0xb1;
414+
c.finalizable = superclass?.finalizable === true || (fin !== undefined && !fin.isStatic && !emptyFin);
411415
// Runtime members own the metadata now; discard the parsed member records.
412416
cf.fields = [];
413417
cf.methods = [];
@@ -1170,6 +1174,7 @@ export class JVM {
11701174
halt(code: number) {
11711175
if (this.exitCode !== null) return;
11721176
this.exitCode = code;
1177+
if (this.reclaim) removeReclaim(this.reclaim);
11731178
this.lib?.close();
11741179
for (const timer of this.timers) clearTimeout(timer);
11751180
this.timers.clear();

‎src/natives/lang.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { isHidden } from "./stackwalk.ts";
44
import { gcStats, javaHeap } from "./management.ts";
55
import { assertionsEnabled } from "../assertions.ts";
66
import { normalize } from "../fs.ts";
7-
import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, dataOf, fieldsOf, monitorOf, newArrayData, releasePins, setData, setFields } from "../runtime.ts";
7+
import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, collector, dataOf, fieldsOf, monitorOf, newArrayData, releasePins, setData, setFields } from "../runtime.ts";
88
import type { Monitor } from "../runtime.ts";
99
import { canUnmount, dropOwned, unblockOnRelease } from "./continuation.ts";
1010
import { collect, registerFinalizer, releaseFinalizerCycles, releaseSoftReferences } from "./ref.ts";
@@ -379,7 +379,7 @@ export const natives: Natives = {
379379
"java/lang/Runtime.gc()V": function* (t): NativeGen {
380380
const stats = gcStats(t.vm);
381381
stats.count++;
382-
const gc = (globalThis as { gc?: () => void }).gc;
382+
const gc = collector();
383383
if (!gc) return;
384384
yield t.block(new Promise((r) => setTimeout(r, 0)));
385385
// values popped off an operand stack are not roots in HotSpot

‎src/natives/ref.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
// finalizer is watched too: its wrapper is collected, and the Finalizer gets a
77
// new wrapper over the same storage.
88

9-
import { INITIALIZED, MAX_HEAP, dataOf, fieldsOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, setReclaim, wrapperOver } from "../runtime.ts";
9+
import { INITIALIZED, MAX_HEAP, dataOf, fieldsOf, freeHeap, hasMaxHeap, releasePins, setData, setHash, addReclaim, wrapperOver } from "../runtime.ts";
1010
import { JObject } from "../runtime.ts";
1111
import type { JClass } from "../runtime.ts";
1212
import { Signal } from "../thread.ts";
@@ -73,11 +73,12 @@ function refs(vm: JVM): RefState {
7373
softs: new WeakMap(),
7474
softCount: 0,
7575
};
76-
setReclaim(() => {
76+
vm.reclaim = () => {
7777
const cycles = forgetCycles(s!, SCAN_AT_GC);
7878
const soft = clearSoftReferences(vm);
7979
return releasePins() || soft || cycles;
80-
});
80+
};
81+
addReclaim(vm.reclaim);
8182
vm.state.set("refs", s);
8283
}
8384
return s;

‎src/node.ts‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import { NodeNet } from "./net-node.ts";
2222
import { ENV_CHANNEL, javaChild, processNatives } from "./process-node.ts";
2323
import { PendingThrow } from "./thread.ts";
2424
import { heapSize } from "./heapsize.ts";
25-
import { clearAllocationCheck, hasMaxHeap, MAX_HEAP, resetAllocationCheck, setAllocationCheck, setMaxHeap } from "./runtime.ts";
25+
import { clearAllocationCheck, collector, hasMaxHeap, MAX_HEAP, resetAllocationCheck, setAllocationCheck, setGc, setMaxHeap } from "./runtime.ts";
2626
import type { NetBackend } from "./sockets.ts";
2727

2828
// A host directory exposed read-only (or writable) inside the VFS.
@@ -386,13 +386,14 @@ function fixedInput(data: Uint8Array) {
386386
const bridges = new WeakMap<object, Bridge>();
387387

388388
// The host file system is the VFS root, with the JDK image mounted at /jdk.
389-
// System.gc() calls globalThis.gc, which node defines only under --expose-gc.
389+
// System.gc() needs a collector: globalThis.gc, which node defines only under
390+
// --expose-gc, is used as the host left it.
390391
// The engine keeps a WeakRef's target alive until the job that made or read it
391392
// ends, so a collection from inside running Java code would miss what Java
392393
// just dropped; a microtask checkpoint of another context ends the job.
393394
let jobEnd: Context | null = null;
394395
function exposeGc() {
395-
const g = globalThis as { gc?: unknown };
396+
const g = globalThis as { gc?: () => void };
396397
if (typeof g.gc !== "function") {
397398
// V8 aborts on a flag change once flags are frozen
398399
if (/(^|\s)--freeze-flags-after-init\b/.test([...process.execArgv, process.env.NODE_OPTIONS ?? ""].join(" "))) return;
@@ -402,13 +403,11 @@ function exposeGc() {
402403
if (!gc) return;
403404
g.gc = gc;
404405
}
405-
const gc = g.gc as (() => void) & { endsJob?: true };
406-
if (gc.endsJob) return;
407-
const endingJob = Object.assign(() => {
406+
const gc = g.gc!;
407+
setGc(() => {
408408
runInContext("0", (jobEnd ??= createContext({}, { microtaskMode: "afterEvaluate" })));
409409
gc();
410-
}, { endsJob: true as const });
411-
g.gc = endingJob;
410+
});
412411
}
413412

414413
// Once the reader goes away (a closed pipe), writes fail with an IOException as
@@ -600,11 +599,10 @@ export function nodeVm(o: LauncherOptions): JVM {
600599
const classpath = o.jar ? [toVfs(o.jar)] : o.classpath.map(toVfs);
601600
const natives = o.natives ?? {};
602601
if (hasMaxHeap()) {
603-
const gc = (globalThis as { gc?: () => void }).gc;
604602
setAllocationCheck(MAX_HEAP, () => {
605603
const m = process.memoryUsage();
606604
return m.heapUsed + m.arrayBuffers;
607-
}, { gc });
605+
}, { gc: collector() });
608606
} else clearAllocationCheck();
609607
const bridge = new Bridge({
610608
call: (_, req) => vm.library.request(req),
@@ -847,7 +845,7 @@ export function main(argv: string[]) {
847845
// Collecting first: node's exit teardown can deadlock while it frees very
848846
// large array buffers (seen on x64 CI runners with a few hundred MB left).
849847
Promise.resolve().then(() => runNode(o)).then(async (code) => {
850-
globalThis.gc?.();
848+
collector()?.();
851849
// output a pipe has not taken yet goes out before the process does
852850
const flushed = [process.stdout, process.stderr].map((s) => new Promise<void>((done) => { s.write("", () => done()); }));
853851
await Promise.race([Promise.all(flushed), new Promise((done) => setTimeout(done, 10000).unref())]);

‎src/runtime.ts‎

Lines changed: 88 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -197,18 +197,36 @@ export class JObject {
197197
// slot has its own functions, so the engine caches the property per slot, not
198198
// per call site, and a read-modify-write touches the object once.
199199
const MAX_FAST_SLOT = 4096;
200+
201+
// Pages that forbid eval throw on the first new Function. Detect it once, then
202+
// build accessors and constructors from closures.
203+
let noEval = false;
204+
export function evalBlocked(e: unknown): boolean {
205+
return e instanceof EvalError || (e instanceof Error && /unsafe-eval|Content Security/i.test(e.message));
206+
}
207+
function generate<T>(make: () => T, fallback: () => T): T {
208+
if (!noEval) {
209+
try {
210+
return make();
211+
} catch (e) {
212+
if (!evalBlocked(e)) throw e;
213+
noEval = true;
214+
}
215+
}
216+
return fallback();
217+
}
200218
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 };
201219
const slotFns: SlotFns[] = [];
202220
function fnsFor(slot: number): SlotFns | null {
203221
if (!(slot >= 0 && slot < MAX_FAST_SLOT && Number.isInteger(slot))) return null;
204-
return (slotFns[slot] ??= {
222+
return slotFns[slot] ?? generate(() => (slotFns[slot] = {
205223
read: new Function("o", `return o.f${slot}`) as SlotFns["read"],
206224
write: new Function("o", "v", `o.f${slot}=v`) as SlotFns["write"],
207225
cas: new Function("o", "e", "v", `const c=o.f${slot};if(c===e)o.f${slot}=v;return c`) as SlotFns["cas"],
208226
swap: new Function("o", "v", `const c=o.f${slot};o.f${slot}=v;return c`) as SlotFns["swap"],
209227
add: new Function("o", "d", `const c=o.f${slot};o.f${slot}=(c+d)|0;return c`) as SlotFns["add"],
210228
addLong: new Function("o", "d", `const c=o.f${slot};o.f${slot}=BigInt.asIntN(64,c+d);return c`) as SlotFns["addLong"],
211-
});
229+
}), () => null);
212230
}
213231
export function readField(o: JObject, slot: number): any {
214232
const f = fnsFor(slot);
@@ -271,14 +289,22 @@ function withAccess(C: unknown, kinds: string): ObjCtor {
271289
const T = C as ObjCtor;
272290
// generated on first use: boot does not need them
273291
T.dump = (o) => {
274-
let body = "return[";
275-
for (let i = 0; i < kinds.length; i++) body += `o.f${i},`;
276-
return (T.dump = new Function("o", `${body}]`) as ObjCtor["dump"])(o);
292+
T.dump = generate(() => {
293+
let body = "return[";
294+
for (let i = 0; i < kinds.length; i++) body += `o.f${i},`;
295+
return new Function("o", `${body}]`) as ObjCtor["dump"];
296+
}, () => (o) => Array.from(kinds, (_, i) => o[fieldKey(i)]));
297+
return T.dump(o);
277298
};
278299
T.load = (o, f) => {
279-
let body = "";
280-
for (let i = 0; i < kinds.length; i++) body += `o.f${i}=f[${i}];`;
281-
(T.load = new Function("o", "f", body) as ObjCtor["load"])(o, f);
300+
T.load = generate(() => {
301+
let body = "";
302+
for (let i = 0; i < kinds.length; i++) body += `o.f${i}=f[${i}];`;
303+
return new Function("o", "f", body) as ObjCtor["load"];
304+
}, () => (o, f) => {
305+
for (let i = 0; i < kinds.length; i++) o[fieldKey(i)] = f[i];
306+
});
307+
T.load(o, f);
282308
};
283309
return T;
284310
}
@@ -288,9 +314,19 @@ function ctorFor(kinds: string): ObjCtor {
288314
if (C) return C;
289315
if (kinds === "") C = withAccess(JObject, kinds);
290316
else {
291-
let body = "this.cls=cls;this.s=null;";
292-
for (let i = 0; i < kinds.length; i++) body += `this.f${i}=${kinds[i] === "J" ? "0n" : kinds[i] === "L" ? "null" : "0"};`;
293-
const Obj = new Function("A", "T", `return function Obj(cls){${body}if(A.check!==null&&A.check.enabled)T(32);}`)(alloc, allocated);
317+
const Obj = generate(() => {
318+
let body = "this.cls=cls;this.s=null;";
319+
for (let i = 0; i < kinds.length; i++) body += `this.f${i}=${kinds[i] === "J" ? "0n" : kinds[i] === "L" ? "null" : "0"};`;
320+
return new Function("A", "T", `return function Obj(cls){${body}if(A.check!==null&&A.check.enabled)T(32);}`)(alloc, allocated);
321+
}, () => {
322+
const zeros = Array.from(kinds, (k) => (k === "J" ? 0n : k === "L" ? null : 0));
323+
return function Obj(this: any, cls: JClass) {
324+
this.cls = cls;
325+
this.s = null;
326+
for (let i = 0; i < zeros.length; i++) this[fieldKey(i)] = zeros[i];
327+
if (alloc.check !== null && alloc.check.enabled) allocated(32);
328+
};
329+
});
294330
Obj.prototype = JObject.prototype;
295331
C = withAccess(Obj, kinds);
296332
}
@@ -306,13 +342,34 @@ function finalizableCtorFor(kinds: string): ObjCtor {
306342
let C = finalizableCtors.get(kinds);
307343
if (C) return C;
308344
const Storage = ctorFor(kinds);
309-
let accessors = "";
310-
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},`;
311-
const Obj = new Function("P", "S", "A", "T", `
345+
const Obj = generate(() => {
346+
let accessors = "";
347+
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},`;
348+
return new Function("P", "S", "A", "T", `
312349
const proto = Object.create(P, Object.getOwnPropertyDescriptors({${accessors}}));
313350
function Obj(cls){this.cls=cls;this.s=null;this.st=new S(cls);if(A.check!==null&&A.check.enabled)T(32);}
314351
Obj.prototype = proto;
315352
return Obj;`)(JObject.prototype, Storage, alloc, allocated);
353+
}, () => {
354+
const proto = Object.create(JObject.prototype);
355+
for (let i = 0; i < kinds.length; i++) {
356+
const k = fieldKey(i);
357+
Object.defineProperty(proto, k, {
358+
get(this: any) { return this.st[k]; },
359+
set(this: any, v: any) { this.st[k] = v; },
360+
enumerable: true,
361+
configurable: true,
362+
});
363+
}
364+
function Obj(this: any, cls: JClass) {
365+
this.cls = cls;
366+
this.s = null;
367+
this.st = new Storage(cls);
368+
if (alloc.check !== null && alloc.check.enabled) allocated(32);
369+
}
370+
Obj.prototype = proto;
371+
return Obj;
372+
});
316373
C = withAccess(Obj, kinds);
317374
finalizableCtors.set(kinds, C);
318375
return C;
@@ -684,14 +741,25 @@ export function setAllocationCheck(cap: number, usage: () => number, o: { gc?: (
684741
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 };
685742
}
686743
export function clearAllocationCheck() { alloc.check = null; }
687-
// Lets go of what the VM holds for the program's sake (soft referents, caches
688-
// of unloadable classes) before an OutOfMemoryError; returns whether there was any.
689-
let reclaim: (() => boolean) | null = null;
690-
export function setReclaim(f: () => boolean) { reclaim = f; }
744+
// Lets go of what each VM holds for the program's sake (soft referents, caches
745+
// of unloadable classes) before an OutOfMemoryError; true when there was any.
746+
const reclaimers = new Set<() => boolean>();
747+
export function addReclaim(f: () => boolean) { reclaimers.add(f); }
748+
export function removeReclaim(f: () => boolean) { reclaimers.delete(f); }
749+
function reclaim(): boolean {
750+
let any = false;
751+
for (const f of reclaimers) if (f()) any = true;
752+
return any;
753+
}
754+
// The collector java-web calls: its own wrapper, else the host's gc. A host's
755+
// globalThis.gc is never replaced.
756+
let vmGc: (() => void) | undefined;
757+
export function setGc(f: () => void) { vmGc = f; }
758+
export function collector(): (() => void) | undefined { return vmGc ?? (globalThis as { gc?: () => void }).gc; }
691759
// An allocation that cannot succeed still collects first, as HotSpot does, so
692760
// the program sees soft references cleared and unloaded classes gone.
693761
function collectBeforeGivingUp() {
694-
if (reclaim?.()) (alloc.check?.gc ?? (globalThis as { gc?: () => void }).gc)?.();
762+
if (reclaim()) (alloc.check?.gc ?? collector())?.();
695763
}
696764
// A JObject made while a collection hands a finalizable object to its Finalizer:
697765
// it is not an allocation that can fail.
@@ -776,7 +844,7 @@ function allocated(bytes: number) {
776844
if (check.usage() - check.baseline > check.cap) check.gc?.();
777845
let over = check.usage() - check.baseline > check.cap;
778846
// soft references and unloadable classes go before an OutOfMemoryError, as in HotSpot
779-
if (over && reclaim?.() && check.gc) {
847+
if (over && reclaim() && check.gc) {
780848
check.gc();
781849
over = check.usage() - check.baseline > check.cap;
782850
}

‎src/snapshot.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -624,11 +624,16 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) {
624624
});
625625
d.flush();
626626
restorePending(vm, d.now(v.pending));
627-
for (const [o, referent] of d.references) {
628-
const r = d.dec(referent);
629-
if (r) restoreReference(vm, o, r);
630-
else setData(o, null);
631-
}
632-
d.flush();
627+
// decoding a referent can add references, so flush and go on until none are left
628+
let i = 0;
629+
do {
630+
for (; i < d.references.length; i++) {
631+
const [o, referent] = d.references[i];
632+
const r = d.dec(referent);
633+
if (r) restoreReference(vm, o, r);
634+
else setData(o, null);
635+
}
636+
d.flush();
637+
} while (i < d.references.length);
633638
for (const t of others) vm.startThread(t);
634639
}

‎test/java/FinalizerCycles.java‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,26 @@ static long used() {
2020
return r.totalMemory() - r.freeMemory();
2121
}
2222

23+
// the used heap once finalizers stop freeing memory
24+
static long settled() throws Exception {
25+
long prev = Long.MAX_VALUE;
26+
for (int i = 0; i < 25; i++) {
27+
System.gc();
28+
System.runFinalization();
29+
Thread.sleep(20);
30+
long now = used();
31+
if (prev - now < (1 << 20)) return Math.min(prev, now);
32+
prev = now;
33+
}
34+
return prev;
35+
}
36+
2337
public static void main(String[] args) throws Exception {
2438
long first = 0, last = 0;
2539
for (int round = 0; round < 5; round++) {
2640
for (int i = 0; i < 30000; i++) new Node();
27-
for (int k = 0; k < 5; k++) {
28-
System.gc();
29-
System.runFinalization();
30-
Thread.sleep(20);
31-
}
32-
if (round == 1) first = used();
33-
last = used();
41+
last = settled();
42+
if (round == 1) first = last;
3443
}
3544
System.out.println("flat " + (last - first < (16 << 20)));
3645
}

0 commit comments

Comments
 (0)