diff --git a/src/codegen/builtins/host/unseen-code.builtins.ts b/src/codegen/builtins/host/unseen-code.builtins.ts index 615f4c333e56..e6c3ff675791 100644 --- a/src/codegen/builtins/host/unseen-code.builtins.ts +++ b/src/codegen/builtins/host/unseen-code.builtins.ts @@ -63,6 +63,8 @@ const seenCodeEntries = [ "native:NewCppFunction:ModuleGraph.cpp:jsFunctionModuleGraphOfFrame", "native:NewCppFunction:NodeModuleModule.cpp:jsFunctionIsModuleResolveFilenameSlowPathEnabled", "native:NewCppFunction:Worker.cpp:jsFunctionPostMessage", + "native:NewCppFunction:node/NodeTimers.cpp:functionClearTimeout", + "native:NewCppFunction:node/NodeTimers.cpp:functionSetTimeout", "native:Bindgen:napi_body.bind.ts:threadsafeFunctionLiveCount", "process.binding", ]; diff --git a/src/js/node/child_process.ts b/src/js/node/child_process.ts index 3102c2a468c4..982a8384045b 100644 --- a/src/js/node/child_process.ts +++ b/src/js/node/child_process.ts @@ -42,6 +42,10 @@ const StringPrototypeIndexOf = String.prototype.indexOf; var StringPrototypeStartsWith = String.prototype.startsWith; var Uint8ArrayPrototypeIncludes = Uint8Array.prototype.includes; +// Not the globals, which user code can replace: https://github.com/nodejs/node/blob/v26.12.1/lib/child_process.js#L76 +const setTimeout: typeof globalThis.setTimeout = $newCppFunction("node/NodeTimers.cpp", "functionSetTimeout", 1); +const clearTimeout: typeof globalThis.clearTimeout = $newCppFunction("node/NodeTimers.cpp", "functionClearTimeout", 1); + const MAX_BUFFER = 1024 * 1024; interface ExecException extends Error { @@ -178,7 +182,7 @@ function spawn(file, args, options) { child.emit("error", err); } } - }, timeout).unref(); + }, timeout); const clear = () => { if (timeoutId) { @@ -186,6 +190,7 @@ function spawn(file, args, options) { timeoutId = null; } }; + // Node clears on 'close' alone (https://github.com/nodejs/node/blob/v26.12.1/lib/child_process.js#L874-L880). Here 'exit' is not always followed by 'close'. child.once("exit", clear); child.once("close", clear); } @@ -263,7 +268,6 @@ function execFile(file, args, options?, callback?: ExecCallback) { const child = spawn(file, args, { cwd: options.cwd, env: options.env, - timeout: options.timeout, killSignal: options.killSignal, uid: options.uid, gid: options.gid, @@ -369,7 +373,9 @@ function execFile(file, args, options?, callback?: ExecCallback) { timeoutId = setTimeout(function delayedKill() { timeoutId = null; kill(); - }, optionsTimeout).unref(); + }, optionsTimeout); + // Past 'exit' the deadline only bounds the wait for 'close', which Bun can lose, so it stops holding the process. + child.once("exit", () => timeoutId?.unref()); } function addOnDataListener(child_buffer: $Node.Readable, _buffer: (string | Buffer)[], kind: string) { diff --git a/test/js/node/child_process/child_process.test.ts b/test/js/node/child_process/child_process.test.ts index 7845b6d9f361..5ee0f9e5ac26 100644 --- a/test/js/node/child_process/child_process.test.ts +++ b/test/js/node/child_process/child_process.test.ts @@ -1696,6 +1696,111 @@ describe("spawn/execFile({signal}) does not leak abort listeners on spawn failur }); }); +// `timeout` is one timer per call, and it calls child.kill(): spawn() arms it +// for spawn and fork, execFile() for execFile and exec. As in Node, it keeps the +// parent alive until it fires or the child is gone, child.unref() or not. +describe("options.timeout", () => { + const fixture = path.join(import.meta.dir, "fixtures", "child-process-timeout-fixture.js"); + + // What the parent in the fixture reports as it exits, and whether the child + // it started is still there afterwards. + type Expected = { killed?: boolean; kills: number; events?: string[]; callback?: unknown; alive?: boolean }; + const cases: Record = { + // Only the deadline keeps the parent alive. It waits, signals once, and then reaps the child. + "spawn": { killed: true, kills: 1, events: ["exit", "close"], alive: false }, + // Node emits no 'close' once the parent has called disconnect(), so the events are not part of this case. + "fork": { killed: true, kills: 1, alive: false }, + "execFile": { killed: true, kills: 1, events: ["exit", "close"], callback: { killed: true }, alive: false }, + "exec": { killed: true, kills: 1, events: ["exit", "close"], callback: { killed: true }, alive: false }, + "execFile, pipes open at the deadline": { + killed: true, + kills: 1, + events: ["exit", "close"], + callback: { killed: true }, + }, + // The callback has its error, so the deadline is over. The child ends by itself. + "execFile, 'error' before the deadline": { + killed: false, + kills: 0, + events: ["error", "exit", "close"], + callback: { killed: false }, + }, + // The child is gone before the deadline. The parent hears of it, and the timer does not keep it. + "spawn, child exits first": { kills: 0, events: ["exit", "close"] }, + "fork, child exits first": { kills: 0, events: ["exit", "close"] }, + "execFile, child exits first": { kills: 0, events: ["exit", "close"], callback: "no error" }, + // No 'close' comes after these 'exit's (Node emits one), so the events are not part of the cases. + "spawn, 'exit' listener pauses stdout": { killed: false, kills: 0 }, + "execFile, 'exit' listener pauses the pipes": { killed: false, kills: 0 }, + "spawn of a missing file": { kills: 0, events: ["error", "close"] }, + // The timers are not the globals, which a fake-timers library replaces. A fake setTimeout would + // arm nothing, and the parent would be gone before the 'exit'. A fake clearTimeout would clear + // nothing, and the parent would wait for the deadline. + "spawn, timers replaced after the module loaded": { kills: 0, events: ["exit", "close"] }, + "execFile, timers replaced after the module loaded": { kills: 0, events: ["exit", "close"], callback: "no error" }, + // execFile()'s timer stops holding the parent at 'exit'. No 'exit' comes here, so only the clear releases it. + "execFile of a missing file, timers replaced after the module loaded": { + kills: 0, + events: ["error", "close"], + callback: { killed: false }, + }, + "timers replaced while the module loads, then restored": { + killed: true, + kills: 1, + events: ["exit", "close"], + alive: false, + }, + // No timeout, no timer: the parent leaves at once and the child stays. + "no timeout": { killed: false, kills: 0, events: [], alive: true }, + // The graph ends its child and its timers. No 'close' comes to clear the deadline. + "spawn in a Bun.ModuleGraph that is disposed": { killed: false, kills: 0 }, + }; + + const isAlive = (pid: number) => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }; + + // One at a time: a case is two processes, and a debug build that starts + // them all together needs the whole test timeout for the slowest. + it.each(Object.entries(cases))("%s", async (mode, expected) => { + await using parent = Bun.spawn({ + cmd: [bunExe(), fixture, mode], + // The runner sets this flag on ASAN lanes. With it the parent kills its + // child as it exits, whether or not the deadline was reached. + env: { ...bunEnv, BUN_FEATURE_FLAG_NO_ORPHANS: undefined }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([parent.stdout.text(), parent.stderr.text(), parent.exited]); + const report = stdout ? JSON.parse(stdout) : {}; + // A child whose 'exit' the parent saw is reaped, and its pid can be another process by now. + const pid: number | undefined = report.events?.includes("exit") ? undefined : report.pid; + try { + const alive = pid !== undefined && isAlive(pid); + const reported = Object.fromEntries( + Object.keys(expected).map(key => [key, key === "alive" ? alive : report[key]]), + ); + expect({ stderr, ...reported, exitCode, signalCode: parent.signalCode }).toEqual({ + stderr: "", + ...expected, + exitCode: 0, + signalCode: null, + }); + } finally { + if (pid !== undefined) { + try { + process.kill(pid, "SIGKILL"); + } catch {} + } + } + }); +}); + // A 'data' handler runs inside the native read loop that delivered its chunk, // and node streams pull again from there, so that pull reads synchronously, // nested in the outer loop, and can run all the way to EOF. The reader used to diff --git a/test/js/node/child_process/fixtures/child-process-timeout-fixture.js b/test/js/node/child_process/fixtures/child-process-timeout-fixture.js new file mode 100644 index 000000000000..d00c1c1f1c50 --- /dev/null +++ b/test/js/node/child_process/fixtures/child-process-timeout-fixture.js @@ -0,0 +1,144 @@ +// The parent process of the `timeout` tests in child_process.test.ts, and the +// child it starts. The tests are about when the parent exits and what it did +// first, so each case runs in a process of its own and reports from 'exit'. +const { writeSync } = require("node:fs"); + +const mode = process.argv[2]; + +// What a fake-timers library puts in place of the globals: timers that never +// fire and have numbers for ids, and a clear that knows only its own. +const replaceTimers = () => { + const { setTimeout, clearTimeout } = globalThis; + let id = 0; + globalThis.setTimeout = () => ++id; + globalThis.clearTimeout = () => {}; + return () => Object.assign(globalThis, { setTimeout, clearTimeout }); +}; +const restoreTimers = mode === "timers replaced while the module loads, then restored" && replaceTimers(); +const { spawn, fork, exec, execFile } = require("node:child_process"); +if (restoreTimers) restoreTimers(); + +// A deadline the parent must reach, and one it must clear long before. The second is longer than the +// test timeout of every CI lane (scripts/runner.node.ts), so a parent that waits for it fails its test. +const soon = 200; +const never = 600_000; + +if (mode === "idle") { + // Long enough for every case to end it, and not for ever when a run fails to. + setTimeout(() => {}, 30_000); +} else if (mode === "brief") { + setTimeout(() => {}, 3 * soon); +} else if (mode === "leaves its pipes open") { + // Exits at once. A process of its own holds stdout and stderr a little longer. + spawn(process.execPath, [__filename, "brief"], { stdio: "inherit", detached: true }).unref(); +} else if (mode !== "exit") { + const idle = [__filename, "idle"]; + const brief = [__filename, "brief"]; + const exits = [__filename, "exit"]; + const events = []; + let kills = 0; + let callback; + const done = error => { + callback = error ? { killed: !!error.killed } : "no error"; + }; + const watch = child => { + const kill = child.kill; + child.kill = function (...args) { + kills++; + const sent = kill.apply(this, args); + // The deadline is over. Staying to reap the child leaves no zombie for the test to take for alive. + this.ref(); + return sent; + }; + for (const event of ["error", "exit", "close"]) child.on(event, () => events.push(event)); + process.on("exit", () => { + writeSync(1, JSON.stringify({ pid: child.pid, killed: child.killed, kills, events, callback })); + }); + return child; + }; + // Leaves the deadline as the only thing that can keep this process alive. + const forget = child => { + child.stdout?.destroy(); + child.stderr?.destroy(); + child.unref(); + }; + + switch (mode) { + case "spawn": + case "timers replaced while the module loads, then restored": + forget(watch(spawn(process.execPath, idle, { stdio: "ignore", detached: true, timeout: soon }))); + break; + case "fork": { + const child = watch(fork(__filename, ["idle"], { stdio: "ignore", detached: true, timeout: soon })); + forget(child); + child.disconnect(); + break; + } + case "execFile": + forget(watch(execFile(process.execPath, idle, { timeout: soon }, done))); + break; + case "exec": { + // `exec` makes the shell become the child, so the pid reported is the one the signal has to reach. + // cmd.exe has no `exec`. There the signal ends the shell only, so its child is one that ends by itself. + const posix = process.platform !== "win32"; + const command = `"${process.execPath}" "${__filename}" ${posix ? "idle" : "brief"}`; + forget(watch(exec(posix ? `exec ${command}` : command, { timeout: soon }, done))); + break; + } + case "execFile, pipes open at the deadline": + watch(execFile(process.execPath, idle, { timeout: soon }, done)); + break; + case "execFile, 'error' before the deadline": + watch(execFile(process.execPath, brief, { timeout: soon }, done)).emit("error", new Error("early")); + break; + case "spawn, child exits first": + watch(spawn(process.execPath, exits, { timeout: never })).unref(); + break; + case "fork, child exits first": + watch(fork(__filename, ["exit"], { stdio: "ignore", timeout: never })).unref(); + break; + case "execFile, child exits first": + forget(watch(execFile(process.execPath, exits, { timeout: never }, done))); + break; + case "spawn, 'exit' listener pauses stdout": { + const child = watch(spawn(process.execPath, exits, { timeout: never })); + child.once("exit", () => child.stdout.pause()); + break; + } + case "execFile, 'exit' listener pauses the pipes": { + const child = watch(execFile(process.execPath, [__filename, "leaves its pipes open"], { timeout: never }, done)); + child.once("exit", () => { + child.stdout.pause(); + child.stderr.pause(); + }); + break; + } + case "spawn of a missing file": + watch(spawn(__filename + ".does-not-exist", [], { timeout: never })); + break; + case "spawn, timers replaced after the module loaded": + replaceTimers(); + watch(spawn(process.execPath, exits, { stdio: "ignore", timeout: never })).unref(); + break; + case "execFile, timers replaced after the module loaded": + replaceTimers(); + forget(watch(execFile(process.execPath, exits, { timeout: never }, done))); + break; + case "execFile of a missing file, timers replaced after the module loaded": + replaceTimers(); + watch(execFile(__filename + ".does-not-exist", { timeout: never }, done)); + break; + case "no timeout": + forget(watch(spawn(process.execPath, idle, { stdio: "ignore", detached: true }))); + break; + case "spawn in a Bun.ModuleGraph that is disposed": { + // A disposed graph hears no 'close'. Its timers end with it. + const graph = new Bun.ModuleGraph(); + watch(graph.run(() => spawn(process.execPath, idle, { stdio: "ignore", timeout: never }))); + graph.dispose(); + break; + } + default: + throw new Error(`unknown mode: ${mode}`); + } +} diff --git a/test/js/node/test/parallel/test-child-process-spawn-timeout-clear-on-error.js b/test/js/node/test/parallel/test-child-process-spawn-timeout-clear-on-error.js new file mode 100644 index 000000000000..f674e4ed55f0 --- /dev/null +++ b/test/js/node/test/parallel/test-child-process-spawn-timeout-clear-on-error.js @@ -0,0 +1,19 @@ +'use strict'; + +// Measures the child's actual exit time, not just its 'error' event. +// The outer spawnSync timeout catches a leaked inner timer. + +const common = require('../common'); +const { spawnSyncAndExitWithoutError } = require('../common/child_process'); + +const bugStallMs = common.platformTimeout(10000); +const outerTimeoutMs = common.platformTimeout(2000); + +spawnSyncAndExitWithoutError(process.execPath, ['-e', ` + const { spawn } = require('child_process'); + const cp = spawn(process.execPath, ['--version'], { + cwd: '/nonexistent/path/that/should/never/exist', + timeout: ${bugStallMs}, + }); + cp.on('error', () => {}); +`], { timeout: outerTimeoutMs });