Skip to content

Commit 1880f4e

Browse files
authored
Make System.gc collect under the java-web command (#9)
1 parent 8223896 commit 1880f4e

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

‎src/node.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { isAssertionFlag, parseAssertions } from "./assertions.ts";
44
import * as fs from "node:fs";
55
import * as os from "node:os";
66
import * as path from "node:path";
7+
import { setFlagsFromString } from "node:v8";
8+
import { runInNewContext } from "node:vm";
79
import { fileURLToPath, pathToFileURL } from "node:url";
810
import { VFS } from "./fs.ts";
911
import type { Backend, Stat } from "./fs.ts";
@@ -180,7 +182,20 @@ function fixedInput(data: Uint8Array) {
180182
const bridges = new WeakMap<object, Bridge>();
181183

182184
// The host file system is the VFS root, with the JDK image mounted at /jdk.
185+
// System.gc() calls globalThis.gc, which node defines only under --expose-gc
186+
function exposeGc() {
187+
const g = globalThis as { gc?: unknown };
188+
if (typeof g.gc === "function") return;
189+
// V8 aborts on a flag change once flags are frozen
190+
if (/(^|\s)--freeze-flags-after-init\b/.test([...process.execArgv, process.env.NODE_OPTIONS ?? ""].join(" "))) return;
191+
setFlagsFromString("--expose-gc");
192+
// absent when --expose-gc-as gave it another name
193+
const gc = runInNewContext("typeof gc === 'function' ? gc : undefined");
194+
if (gc) g.gc = gc;
195+
}
196+
183197
function nodeVm(o: NodeRunOptions): JVM {
198+
exposeGc();
184199
const vfs = new VFS();
185200
vfs.mount("/", new NodeBackend("/", true));
186201
// built as dist/node.js, it reads the packaged image next to it

‎test/programs.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ for (const file of files) {
5656
});
5757
}
5858

59+
// the java-web command, which node starts without --expose-gc
60+
test("System.gc collects under the command", { skip: !files.includes("Refs.java") }, () => {
61+
const ref = spawnSync(hotspot("java"), ["-cp", out, "Refs"], { encoding: "utf8" });
62+
assert.equal(ref.status, 0);
63+
const got = spawnSync(process.execPath, [join(root, "src", "node.ts"), "-cp", out, "Refs"], { encoding: "utf8" });
64+
assert.deepEqual({ stdout: got.stdout, code: got.status }, { stdout: ref.stdout, code: ref.status });
65+
});
66+
5967
function flags(file: string, tool: string): string[] {
6068
const m = new RegExp(`^// ${tool}: (.*)$`, "m").exec(readFileSync(join(src, file), "utf8"));
6169
return m ? m[1].split(" ") : [];

0 commit comments

Comments
 (0)