Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
11 changes: 9 additions & 2 deletions src/jsc/bindings/FormatStackTraceForJS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

#include "JavaScriptCore/ArgList.h"
#include "JavaScriptCore/CallData.h"
#include "JavaScriptCore/DeferTermination.h"
#include "JavaScriptCore/FrameTracers.h"
#include "JavaScriptCore/TopExceptionScope.h"
#include "JavaScriptCore/Error.h"
#include "JavaScriptCore/ErrorInstance.h"
Expand Down Expand Up @@ -597,11 +599,16 @@ WTF::String computeErrorInfoWrapperToString(JSC::VM& vm, Vector<StackFrame>& sta
OrdinalNumber line = OrdinalNumber::fromOneBasedInt(line_in);
OrdinalNumber column = OrdinalNumber::fromOneBasedInt(column_in);

// Runs from the GC end phase while the mutator may have its own pending
// exception. A termination raised inside would survive the clear below and
// be clobbered by the restore, so hold it off until the mutator's next check.
Comment thread
robobun marked this conversation as resolved.
Resolved
JSC::DeferTerminationForAWhile deferTermination(vm);
JSC::SuspendExceptionScope suspendExceptionScope(vm);

auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
WTF::String result = computeErrorInfoToString(vm, stackTrace, line, column, sourceURL);
if (scope.exception()) {
// TODO: is this correct? vm.setOnComputeErrorInfo doesnt appear to properly handle a function that can throw
// test/js/node/test/parallel/test-stream-writable-write-writev-finish.js is the one that trips the exception checker
// The onComputeErrorInfo hook cannot propagate a throw.
(void)scope.tryClearException();
result = WTF::emptyString();
}
Expand Down
72 changes: 72 additions & 0 deletions test/js/bun/resolve/dynamic-import-evaluation-error-gc.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";

// computeErrorInfoWrapperToString (src/jsc/bindings/FormatStackTraceForJS.cpp,
// installed via vm.setOnComputeErrorInfo) runs from
// ErrorInstance::reconcileWeakReferencesAtGCEnd during Heap::runEndPhase, for
// any live Error whose stack frames now reference dead code. It used to clear
// whatever exception was pending after computing the stack string. With
// concurrent GC that end phase can land while the mutator is parked at a
// safepoint inside CyclicModuleRecord::evaluate, between step 9 (the module's
// evaluation error is the pending exception) and step 9.d
// (rejectWithCaughtException), which then finds no exception and crashes
// (`ASSERTION FAILED: exception` at JSPromise.cpp on assert builds, a SEGV at
// address 0x8 on release: Sentry BUN-4R6E).
//
// This is the plain import() face of the bug. Each iteration writes a fresh
// ESM graph with one member that throws at top level and one that uses
// top-level await. import(a) fails on the throwing member; import(b) reaches
// that already-errored member, so its Evaluate() rethrows the stored error and
// runs the step 9 -> 9.d window again. The race needs the accumulated graphs
// and GC cycles of a long loop; a single iteration does not fire, 100 fire on
// about 1 run in 6, 300 on essentially every run of the unfixed assert build.
// The fixture runs twice and a single crash fails the test.
//
// Skipped on Windows: two runs of a 300-iteration loop that writes 2100 files
// and evaluates 1200 module graphs are several times slower under
// Windows + ASAN in CI, and the fixed C++ path is not platform-specific.
test.skipIf(isWindows)(
"import() of a module whose evaluation throws survives a GC stack-trace finalizer",
Comment thread
robobun marked this conversation as resolved.
Resolved
async () => {
const fixture = `
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const root = join(import.meta.dir, "graphs");
for (let it = 0; it < 300; it++) {
const d = join(root, "g" + it);
mkdirSync(d, { recursive: true });
writeFileSync(join(d, "bad.mjs"), "export const x = " + it + ";\\nthrow new Error('boom " + it + "');\\n");
writeFileSync(join(d, "tla.mjs"), "await new Promise(r => setTimeout(r, 0));\\nexport const t = " + it + ";\\n");
writeFileSync(join(d, "leaf.mjs"), "export const l = " + it + ";\\n");
writeFileSync(join(d, "mid.mjs"), "import { l } from './leaf.mjs';\\nimport './bad.mjs';\\nexport const m = l + 1;\\n");
writeFileSync(join(d, "a.mjs"), "import { m } from './mid.mjs';\\nimport { t } from './tla.mjs';\\nexport const a = m + t;\\n");
writeFileSync(join(d, "b.mjs"), "import { t } from './tla.mjs';\\nimport './bad.mjs';\\nexport const b = t;\\n");
writeFileSync(join(d, "c.mjs"), "import { m } from './mid.mjs';\\nexport const c = m;\\n");

await import(join(d, "a.mjs")).catch(() => {});
await import(join(d, "b.mjs")).catch(() => {});
await import(join(d, "c.mjs")).catch(() => {});
await import("data:text/javascript,throw new Error('d" + it + "')").catch(() => {});
}
console.log("ok");
`;

using dir = tempDir("dynamic-import-eval-error-gc", { "fixture.mjs": fixture });

for (let i = 0; i < 2; i++) {
await using proc = Bun.spawn({
cmd: [bunExe(), "fixture.mjs"],
cwd: String(dir),
env: bunEnv,
stdio: ["ignore", "pipe", "pipe"],
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: stdout.trim(), exitCode }).toEqual({ stdout: "ok", exitCode: 0 });
void stderr;
}
},
// Two runs of a 300-iteration loop on a debug+ASAN build take well over the
// default 5s.
120_000,
);
142 changes: 141 additions & 1 deletion test/js/node/vm/sourcetextmodule-link-gc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// ~9× per link() call.

import { expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows } from "harness";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";

// collectContinuously is very slow under Windows + ASAN in CI; the code path
// is identical on Linux/macOS, so skip Windows to keep duration reasonable.
Expand Down Expand Up @@ -70,3 +70,143 @@ test.skipIf(isWindows)(
},
120_000,
);

// computeErrorInfoWrapperToString (src/jsc/bindings/FormatStackTraceForJS.cpp,
// installed via vm.setOnComputeErrorInfo) runs from ErrorInstance::
// finalizeUnconditionally during Heap::runEndPhase. It used to clear whatever
// exception was pending after computing a stack string. With concurrent GC,
// that finalizer lands at an arbitrary safepoint: if it fires while the mutator
// is mid vm.SourceTextModule evaluation with a module's evaluation error
// pending, it nulled that exception. CyclicModuleRecord::evaluate step 9.d then
// reached rejectWithCaughtException with no pending exception and crashed
// (`ASSERTION FAILED: exception` at JSPromise.cpp, or a SEGV at 0x8 on release).
// The fix only swallows an exception the stack computation itself raised.
//
// The race depends on concurrent GC landing in that window: --smol shrinks the
// heap so collections run often enough to hit it on essentially every run of
// the unfixed assert build, while collectContinuously moves the window and
// hides it. The fixture is a real file (a -e eval script has no source URL, so
// the stack-trace finalizer takes a different path and doesn't fire). The
// processes run one at a time (concurrency starves the collector and hides the
// race); a single crash fails the test.
//
// Skipped on Windows for the same reason as the test above: four runs of a
// 60-iteration GC-churn loop are several times slower under Windows + ASAN in
// CI, and the fixed C++ path is not platform-specific.
//
// The fixture is shared with the terminate() test below, which only needs it to
// keep the finalizer busy for as long as the worker lives.
function evaluationErrorFixture(iterations: number) {
return `
import * as vm from "node:vm";
// Separate, pre-existing bug: the throwing top-level-await module below
// (shared by two importers) reports one unhandled rejection per graph even
// though every evaluate() is awaited and caught. Tolerate exactly that one
// so the crash under test stays the only way this process exits nonzero.
process.on("unhandledRejection", e => {
if (e instanceof URIError && e.message === "tla") return;
console.error("unexpected unhandled rejection:", e);
process.exit(3);
});
const sl = async () => { await new Promise(r => setTimeout(r, 12)); for (let i = 0; i < 8; i++) await null; };
const CA = async f => { try { return await f(); } catch (e) { return e; } };
const ni = () => { throw new Error("noimports"); };
const M = (src, id, o) => new vm.SourceTextModule(src, { identifier: id, ...o });

async function fam(sd) {
{ const bad = M("throw new TypeError('boom')", "s1bad" + sd), a = M("import 'bad'; export const x=1;", "s1a" + sd), b = M("import 'bad'; export const y=2;", "s1b" + sd);
await a.link(() => bad); await b.link(() => bad);
try { await a.evaluate(); } catch {} try { await b.evaluate(); } catch {} try { await a.evaluate(); } catch {}
await CA(() => bad.evaluate()); }
{ const ctx = vm.createContext({ log: [] });
const leaf = M("log.push('L0'); export const v = await Promise.resolve(7); log.push('L1');", "s2l" + sd, { context: ctx });
const mid = M("import {v} from 'l'; export const m=v+1;", "s2m" + sd, { context: ctx });
const root = M("import {m} from 'm'; export const r=m+1;", "s2r" + sd, { context: ctx });
const map = { l: leaf, m: mid }; await root.link(s => map[s]);
const ep = root.evaluate(); await CA(async () => { await ep; }); await CA(() => root.evaluate()); }
{ const leaf = M("await 0; throw new URIError('tla');", "s3l" + sd), a = M("import 'l'; export const x=1;", "s3a" + sd), b = M("import 'l'; export const y=1;", "s3b" + sd);
await a.link(() => leaf); await b.link(() => leaf);
try { await a.evaluate(); } catch {} try { await b.evaluate(); } catch {} try { await leaf.evaluate(); } catch {} }
{ const m = M("export const a=1;", "s5" + sd); await m.link(ni); await m.evaluate();
const bad = M("null.x", "s5b" + sd); await bad.link(ni); await bad.evaluate().catch(() => {}); }
{ const val = ["str", "num", "null", "undef", "obj", "sym"][sd % 6];
const src = { str: "throw 'x'", num: "throw 42", null: "throw null", undef: "throw undefined", obj: "throw {a:1}", sym: "throw Symbol.iterator" }[val];
const m = M(src, "s6" + sd); await m.link(ni); await CA(() => m.evaluate()); }
await sl();
}
for (let sd = 0; sd < ${iterations}; sd++) await fam(sd);
console.log("ok");
`;
}

test.skipIf(isWindows)(
"vm.SourceTextModule evaluation error survives a concurrent-GC stack-trace finalizer",
async () => {
using dir = tempDir("vm-module-eval-error-gc", { "fixture.mjs": evaluationErrorFixture(60) });

async function run() {
await using proc = Bun.spawn({
cmd: [bunExe(), "--smol", "--experimental-vm-modules", "fixture.mjs"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
stdout: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout: stdout.trim(), stderr, exitCode };
}

for (let i = 0; i < 4; i++) {
const { stdout, stderr, exitCode } = await run();
expect({ stdout, exitCode }).toEqual({ stdout: "ok", exitCode: 0 });
void stderr;
}
},
120_000,
);

// The finalizer now sets the mutator's pending exception aside with a
// SuspendExceptionScope. That scope restores the slot blindly on exit, so a
// termination exception thrown inside the window (a RETURN_IF_EXCEPTION inside
// the stack computation services the worker's pending terminate() request)
// survived the clear and was then overwritten, leaving the NeedExceptionHandling
// trap bit set with no exception behind it. The next exception check asserted
// `!!exception == needHandling(NeedExceptionHandling)`. Termination is now
// deferred for the duration of the window (DeferTerminationForAWhile).
//
// Run the GC-churn fixture inside a Worker and terminate it mid-run, 20 times.
// Every run of the build with the suspend scope but without the deferral
// asserted; this guards that pairing rather than the original crash (it passes
// on a build with neither). Windows: same reason as above.
test.skipIf(isWindows)(
"terminate() while the stack-trace finalizer runs keeps the exception and trap state in sync",
async () => {
using dir = tempDir("vm-module-eval-error-gc-terminate", {
"fixture.mjs": evaluationErrorFixture(600),
"stress.mjs": `
import { readFileSync } from "node:fs";
const src = readFileSync(new URL("./fixture.mjs", import.meta.url), "utf8");
const url = URL.createObjectURL(new Blob([src], { type: "text/javascript" }));
for (let r = 0; r < 20; r++) {
const w = new Worker(url, { type: "module" });
Comment thread
robobun marked this conversation as resolved.
Resolved
await new Promise(res => setTimeout(res, 150 + ((r * 37) % 400)));
w.terminate();
await new Promise(res => w.addEventListener("close", res, { once: true }));
Comment thread
robobun marked this conversation as resolved.
Resolved
}
console.log("ok");
`,
});

await using proc = Bun.spawn({
cmd: [bunExe(), "--smol", "--experimental-vm-modules", "stress.mjs"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
stdout: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: stdout.trim(), exitCode }).toEqual({ stdout: "ok", exitCode: 0 });
void stderr;
},
120_000,
);
Loading