Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
73 changes: 56 additions & 17 deletions src/jsc/bindings/BunProcess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,9 @@ static const NeverDestroyed<String>* getSignalNames()
MAKE_STATIC_STRING_IMPL("SIGINFO"),
MAKE_STATIC_STRING_IMPL("SIGSYS"),
MAKE_STATIC_STRING_IMPL("SIGBREAK"),
MAKE_STATIC_STRING_IMPL("SIGSTKFLT"),
MAKE_STATIC_STRING_IMPL("SIGPOLL"),
MAKE_STATIC_STRING_IMPL("SIGPWR"),
};

return signalNames;
Expand All @@ -1060,7 +1063,7 @@ static void loadSignalNumberMap()
std::call_once(signalNameToNumberMapOnceFlag, [] {
auto signalNames = getSignalNames();
signalNameToNumberMap = new HashMap<String, int>();
signalNameToNumberMap->reserveInitialCapacity(31);
signalNameToNumberMap->reserveInitialCapacity(35);
#if OS(WINDOWS)
// libuv-supported console-control signals on Windows:
// CTRL_C_EVENT → SIGINT, CTRL_BREAK_EVENT → SIGBREAK,
Expand Down Expand Up @@ -1150,6 +1153,15 @@ static void loadSignalNumberMap()
#ifdef SIGSYS
signalNameToNumberMap->add(signalNames[30], SIGSYS);
#endif
#ifdef SIGSTKFLT
signalNameToNumberMap->add(signalNames[32], SIGSTKFLT);
#endif
#ifdef SIGPOLL
signalNameToNumberMap->add(signalNames[33], SIGPOLL);
#endif
#ifdef SIGPWR
signalNameToNumberMap->add(signalNames[34], SIGPWR);
#endif
Comment thread
robobun marked this conversation as resolved.
Resolved
#endif
});
}
Expand All @@ -1163,14 +1175,20 @@ bool isSignalName(WTF::String input)
extern "C" void Bun__onSignalForJS(int signalNumber, Zig::GlobalObject* globalObject)
{
Process* process = globalObject->processObject();
auto& vm = JSC::getVM(globalObject);

String signalName = signalNumberToNameMap->get(signalNumber);
Identifier signalNameIdentifier = Identifier::fromString(JSC::getVM(globalObject), signalName);
MarkedArgumentBuffer args;
args.append(jsString(JSC::getVM(globalObject), signalNameIdentifier.string()));
args.append(jsNumber(signalNumber));

process->wrapped().emitForBindings(signalNameIdentifier, args);
// A single signal number can map to multiple names (SIGABRT/SIGIOT, SIGIO/SIGPOLL).
// Emit the event for every name that resolves to this number so listeners registered
// under either alias fire, matching Node.js.
for (auto& entry : *signalNameToNumberMap) {
if (entry.value != signalNumber)
continue;
Identifier signalNameIdentifier = Identifier::fromString(vm, entry.key);
MarkedArgumentBuffer args;
args.append(jsString(vm, signalNameIdentifier.string()));
args.append(jsNumber(signalNumber));
process->wrapped().emitForBindings(signalNameIdentifier, args);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}

#if OS(WINDOWS)
Expand Down Expand Up @@ -1433,7 +1451,7 @@ static void onDidChangeListeners(EventEmitter& eventEmitter, const Identifier& e
std::call_once(signalNumberToNameMapOnceFlag, [] {
auto signalNames = getSignalNames();
signalNumberToNameMap = new HashMap<int, String>();
signalNumberToNameMap->reserveInitialCapacity(31);
signalNumberToNameMap->reserveInitialCapacity(35);
signalNumberToNameMap->add(SIGHUP, signalNames[0]);
signalNumberToNameMap->add(SIGINT, signalNames[1]);
signalNumberToNameMap->add(SIGQUIT, signalNames[2]);
Expand Down Expand Up @@ -1509,6 +1527,15 @@ static void onDidChangeListeners(EventEmitter& eventEmitter, const Identifier& e
#endif
#ifdef SIGBREAK
signalNumberToNameMap->add(SIGBREAK, signalNames[31]);
#endif
#ifdef SIGSTKFLT
signalNumberToNameMap->add(SIGSTKFLT, signalNames[32]);
#endif
#ifdef SIGPOLL
signalNumberToNameMap->add(SIGPOLL, signalNames[33]);
#endif
#ifdef SIGPWR
signalNumberToNameMap->add(SIGPWR, signalNames[34]);
#endif
});

Expand Down Expand Up @@ -1566,17 +1593,29 @@ static void onDidChangeListeners(EventEmitter& eventEmitter, const Identifier& e
}
} else {
if (signalToContextIdsMap->find(signalNumber) != signalToContextIdsMap->end() && eventEmitter.listenerCount(eventName) == 0) {

#if !OS(WINDOWS)
if (void (*oldHandler)(int) = signal(signalNumber, SIG_DFL); oldHandler != forwardSignal) {
// Don't uninstall the old handler if it's not the one we installed.
signal(signalNumber, oldHandler);
// A single signal number can be registered under multiple names
// (SIGABRT/SIGIOT, SIGIO/SIGPOLL). Only restore the default
// disposition once no alias has a listener left.
auto& vm = JSC::getVM(eventEmitter.scriptExecutionContext()->jsGlobalObject());
bool anyAliasRemaining = false;
for (auto& entry : *signalNameToNumberMap) {
if (entry.value == signalNumber && eventEmitter.listenerCount(Identifier::fromString(vm, entry.key)) > 0) {
anyAliasRemaining = true;
break;
}
}
if (!anyAliasRemaining) {
#if !OS(WINDOWS)
if (void (*oldHandler)(int) = signal(signalNumber, SIG_DFL); oldHandler != forwardSignal) {
// Don't uninstall the old handler if it's not the one we installed.
signal(signalNumber, oldHandler);
}
#else
SignalHandleValue signal_handle = signalToContextIdsMap->get(signalNumber);
Bun__UVSignalHandle__close(signal_handle.handle);
SignalHandleValue signal_handle = signalToContextIdsMap->get(signalNumber);
Bun__UVSignalHandle__close(signal_handle.handle);
#endif
signalToContextIdsMap->remove(signalNumber);
signalToContextIdsMap->remove(signalNumber);
}
}
}
}
Expand Down
121 changes: 121 additions & 0 deletions test/js/node/process/process.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { spawnSync, which } from "bun";
import { describe, expect, it } from "bun:test";
import { familySync } from "detect-libc";
import { bunEnv, bunExe, isMacOS, isWindows, tempDir, tmpdirSync } from "harness";
import os from "node:os";
import { basename, join, resolve } from "path";

const process_sleep = resolve(import.meta.dir, "process-sleep.js");
Expand Down Expand Up @@ -918,6 +919,126 @@ describe.concurrent(() => {
expect(() => process.kill(2147483640, "SIGPOOP")).toThrow();
expect(() => process.kill(2147483640, 456)).toThrow();
});

// SIGSTKFLT, SIGPOLL and SIGPWR are Linux-only signals that are in
// os.constants.signals but were missing from the process.kill name table.
it.skipIf(process.platform !== "linux")(
"process.kill accepts every signal name in os.constants.signals",
async () => {
const results = {};
for (const name of Object.keys(os.constants.signals)) {
try {
process.kill(0x7fffffff, name);
results[name] = "sent";
} catch (e) {
results[name] = e.code;
}
}
// Every name in os.constants.signals must be resolved as a signal name,
// so the only error we should ever see is ESRCH from kill(2) for the
// nonexistent pid, never ERR_UNKNOWN_SIGNAL from the name lookup.
const unknown = Object.entries(results).filter(([, v]) => v === "ERR_UNKNOWN_SIGNAL");
expect(unknown).toEqual([]);
},
);

it.skipIf(process.platform !== "linux")(
"process.on('SIGSTKFLT') installs a real handler and the listener runs",
async () => {
const script = /*js*/ `
const { promise, resolve } = Promise.withResolvers();
process.on("SIGSTKFLT", (name, num) => {
console.log("handler", name, num);
resolve();
});
process.kill(process.pid, "SIGSTKFLT");
await promise;
console.log("survived");
`;
await using child = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([child.stdout.text(), child.stderr.text(), child.exited]);
expect({ stdout, stderr, signalCode: child.signalCode }).toEqual({
stdout: "handler SIGSTKFLT 16\nsurvived\n",
stderr: "",
signalCode: null,
});
expect(exitCode).toBe(0);
},
);

// SIGPOLL is an alias for SIGIO on Linux. Node.js emits both event names
// when the signal arrives; the listener registered under each alias must
// fire with its own name.
it.skipIf(process.platform !== "linux")(
"process.on fires listeners for every alias of a signal number",
async () => {
const script = /*js*/ `
const fired = [];
const { promise, resolve } = Promise.withResolvers();
process.on("SIGPOLL", (name, num) => {
fired.push(["SIGPOLL", name, num]);
if (fired.length === 2) resolve();
});
process.on("SIGIO", (name, num) => {
fired.push(["SIGIO", name, num]);
if (fired.length === 2) resolve();
});
process.kill(process.pid, "SIGPOLL");
await promise;
console.log(JSON.stringify(fired.sort((a, b) => a[0].localeCompare(b[0]))));
`;
await using child = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([child.stdout.text(), child.stderr.text(), child.exited]);
expect({ stdout: stdout.trim(), stderr, signalCode: child.signalCode }).toEqual({
stdout: JSON.stringify([
["SIGIO", "SIGIO", 29],
["SIGPOLL", "SIGPOLL", 29],
]),
stderr: "",
signalCode: null,
});
expect(exitCode).toBe(0);
},
);

// Removing the listener for one alias must not uninstall the OS handler
// while another alias of the same signal number still has a listener.
it.skipIf(isWindows)("removing one alias's listener keeps the handler installed for the other alias", async () => {
const script = /*js*/ `
const { promise, resolve } = Promise.withResolvers();
function a() { console.log("SIGABRT handler (removed) fired"); }
function b(name, num) { console.log("SIGIOT handler", name, num); resolve(); }
process.on("SIGABRT", a);
process.on("SIGIOT", b);
process.removeListener("SIGABRT", a);
process.kill(process.pid, "SIGABRT");
await promise;
console.log("survived");
`;
await using child = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([child.stdout.text(), child.stderr.text(), child.exited]);
expect({ stdout, stderr, signalCode: child.signalCode }).toEqual({
stdout: "SIGIOT handler SIGIOT 6\nsurvived\n",
stderr: "",
signalCode: null,
});
expect(exitCode).toBe(0);
});
});

const undefinedStubs = [
Expand Down
Loading