Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/support.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/jit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 7 additions & 2 deletions src/jvm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -191,6 +191,8 @@ export class JVM {
readonly props: Map<string, string>;
// per-VM state natives keep (open files, etc.)
readonly state = new Map<string, any>();
// 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<ReturnType<typeof setTimeout>>();
Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions src/natives/lang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions src/natives/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
20 changes: 9 additions & 11 deletions src/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -386,13 +386,14 @@ function fixedInput(data: Uint8Array) {
const bridges = new WeakMap<object, Bridge>();

// 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;
Expand All @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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<void>((done) => { s.write("", () => done()); }));
await Promise.race([Promise.all(flushed), new Promise((done) => setTimeout(done, 10000).unref())]);
Expand Down
108 changes: 88 additions & 20 deletions src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(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);
Expand Down Expand Up @@ -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;
}
Expand All @@ -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);
}
Expand All @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
Expand Down
17 changes: 11 additions & 6 deletions src/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
23 changes: 16 additions & 7 deletions test/java/FinalizerCycles.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
}
Expand Down
Loading