Skip to content
Open
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
12 changes: 12 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -3005,13 +3005,16 @@
<!-- YAML
added: v22.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/00000
description: Forwards signals to the script and propagates its exit status.
- version:
- v26.9.0
- v24.22.0
pr-url: https://github.com/nodejs/node/pull/64606
description: Passing `--run` without a command lists the available scripts.
- version: v22.3.0
pr-url: https://github.com/nodejs/node/pull/53032

Check warning on line 3017 in doc/api/cli.md

View workflow job for this annotation

GitHub Actions / lint-pr-url

pr-url doesn't match the URL of the current PR.
description: NODE_RUN_SCRIPT_NAME environment variable is added.
- version: v22.3.0
pr-url: https://github.com/nodejs/node/pull/53058
Expand Down Expand Up @@ -3083,6 +3086,15 @@
Environment variables loaded from a file with [`--env-file`][] are not applied
to the command executed by `--run`.

#### Signals and exit codes

`node --run` exits with the exit code of the script, or with the signal that
terminated it.

On POSIX, `SIGINT` and `SIGTERM` are forwarded to the script. If the shell
stays running (e.g. `build && start`), the signal reaches the shell instead;
use `exec` to avoid this.

### `--secure-heap-min=n`

<!-- YAML
Expand Down
55 changes: 52 additions & 3 deletions src/node_task_runner.cc
Original file line number Diff line number Diff line change
Expand Up @@ -199,26 +199,75 @@ void ProcessRunner::ExitCallback(uv_process_t* handle,
int term_signal) {
const auto self = static_cast<ProcessRunner*>(handle->data);
uv_close(reinterpret_cast<uv_handle_t*>(handle), nullptr);
#ifndef _WIN32
for (auto& signal_handle : self->signal_handles_) {
uv_close(reinterpret_cast<uv_handle_t*>(&signal_handle), nullptr);
}
#endif // _WIN32
self->OnExit(exit_status, term_signal);
}

void ProcessRunner::OnExit(int64_t exit_status, int term_signal) {
if (exit_status > 0) {
init_result_->exit_code_ = ExitCode::kGenericUserError;
if (term_signal != 0) {
// Fallback if the signal can't be re-raised.
term_signal_ = term_signal;
init_result_->exit_code_ = static_cast<ExitCode>(128 + term_signal);
} else {
init_result_->exit_code_ = ExitCode::kNoFailure;
init_result_->exit_code_ = static_cast<ExitCode>(exit_status);
}
}

#ifndef _WIN32
void ProcessRunner::SignalCallback(uv_signal_t* handle, int signum) {
const auto self = static_cast<ProcessRunner*>(handle->data);
USE(uv_process_kill(&self->process_, signum));
}

// Exit with the same signal as the child.
static void ReraiseSignal(int signum) {
ResetStdio(true);

struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_DFL;
CHECK_EQ(sigaction(signum, &sa, nullptr), 0);
Comment on lines +230 to +233

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sigaction fails for SIGKILL and SIGSTOP, as outlined here. So for those CHECK_EQ will abort with SIGABORT instead of reraising it

Not an expert in POSIX, but I remember that it should always be guarded against:

Suggested change
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_DFL;
CHECK_EQ(sigaction(signum, &sa, nullptr), 0);
if (signum != SIGKILL && signum != SIGSTOP) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_DFL;
CHECK_EQ(sigaction(signum, &sa, nullptr), 0);
}


sigset_t sigmask;
sigemptyset(&sigmask);
sigaddset(&sigmask, signum);
CHECK_EQ(pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr), 0);

raise(signum);
}
#endif // _WIN32

void ProcessRunner::Run() {
// keeps the string alive until destructor
cwd_ = ConvertPathToUTF8(package_json_path_.parent_path());
options_.cwd = cwd_.c_str();
if (int r = uv_spawn(loop_, &process_, &options_)) {
fprintf(stderr, "Error: %s\n", uv_strerror(r));
} else {
#ifndef _WIN32
// Closed in ExitCallback.
for (size_t i = 0; i < std::size(kForwardedSignals); i++) {
uv_signal_t* signal_handle = &signal_handles_[i];
CHECK_EQ(uv_signal_init(loop_, signal_handle), 0);
signal_handle->data = this;
CHECK_EQ(
uv_signal_start(signal_handle, SignalCallback, kForwardedSignals[i]),
0);
}
#endif // _WIN32
}

uv_run(loop_, UV_RUN_DEFAULT);

#ifndef _WIN32
if (term_signal_ != 0) {
ReraiseSignal(term_signal_);
}
#endif // _WIN32
}

std::optional<std::tuple<std::filesystem::path, std::string, std::string>>
Expand Down
12 changes: 12 additions & 0 deletions src/node_task_runner.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
#include "spawn_sync.h"
#include "uv.h"

#include <csignal>
#include <filesystem>
#include <iterator>
#include <optional>
#include <string_view>
#include <tuple>
Expand Down Expand Up @@ -44,6 +46,16 @@ class ProcessRunner {
std::unique_ptr<char* []> env_ {}; // memory for options_.env
std::unique_ptr<char* []> arg_ {}; // memory for options_.args
std::string cwd_;
// Signal that killed the child, or 0.
int term_signal_ = 0;

#ifndef _WIN32
// Forwarded to the child, like npm.
static constexpr int kForwardedSignals[] = {SIGINT, SIGTERM};
uv_signal_t signal_handles_[std::size(kForwardedSignals)]{};

static void SignalCallback(uv_signal_t* handle, int signum);
#endif // _WIN32

// OnExit is the callback function that is called when the process exits.
void OnExit(int64_t exit_status, int term_signal);
Expand Down
111 changes: 111 additions & 0 deletions test/parallel/test-node-run-signals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
'use strict';

const common = require('../common');

if (common.isWindows) {
common.skip('POSIX signals are not supported on Windows');
}

const assert = require('node:assert');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const fs = require('node:fs');
const { describe, it } = require('node:test');

const tmpdir = require('../common/tmpdir');

tmpdir.refresh();

const node = JSON.stringify(process.execPath);
const forwardedSignals = ['SIGINT', 'SIGTERM'];

fs.writeFileSync(tmpdir.resolve('handle-signals.js'), `
const timer = setInterval(() => {}, 1000);
for (const signal of ${JSON.stringify(forwardedSignals)}) {
process.on(signal, () => {
console.log('received ' + signal);
process.exitCode = 7;
clearInterval(timer);
});
}
console.log('ready', process.pid);
`);

fs.writeFileSync(tmpdir.resolve('package.json'), JSON.stringify({
scripts: {
'exit-code': 'exit 42',
'self-terminate': 'kill -TERM $$',
// `exec` so signals reach node, not the shell.
'handle-signals': `exec ${node} handle-signals.js`,
'no-signal-handlers':
`exec ${node} -e "console.log('ready', process.pid); setInterval(() => {}, 1000)"`,
},
}));

function run(script) {
return common.spawnPromisified(process.execPath, ['--run', script], {
cwd: tmpdir.path,
});
}

// Sends `signal` to the runner once the script is ready.
async function runAndSignal(script, signal) {
const child = spawn(process.execPath, ['--run', script], {
cwd: tmpdir.path,
stdio: ['ignore', 'pipe', 'inherit'],
});
const exited = once(child, 'exit');
const closed = once(child, 'close');
let stdout = '';
let scriptPid;
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
stdout += chunk;
const ready = scriptPid === undefined && /^ready (\d+)\n/.exec(stdout);
if (ready) {
scriptPid = Number(ready[1]);
child.kill(signal);
}
});
const [code, exitSignal] = await exited;
// Don't leak the script if the runner didn't wait for it.
if (scriptPid !== undefined) {
try {
process.kill(scriptPid, 'SIGKILL');
} catch {
// Already exited.
}
}
await closed;
return { code, signal: exitSignal, stdout };
}

describe('node --run signal handling', () => {
it('uses the exit code of the script', async () => {
const child = await run('exit-code');
assert.strictEqual(child.code, 42);
assert.strictEqual(child.signal, null);
});

it('terminates with the signal that terminated the script', async () => {
const child = await run('self-terminate');
assert.strictEqual(child.code, null);
assert.strictEqual(child.signal, 'SIGTERM');
});

for (const signal of forwardedSignals) {
it(`forwards ${signal} and waits for the script to exit`, async () => {
const child = await runAndSignal('handle-signals', signal);
assert.match(child.stdout, new RegExp(`^ready \\d+\\nreceived ${signal}\\n$`));
assert.strictEqual(child.code, 7);
assert.strictEqual(child.signal, null);
});
}

it('terminates with a forwarded signal the script does not handle',
async () => {
const child = await runAndSignal('no-signal-handlers', 'SIGTERM');
assert.strictEqual(child.code, null);
assert.strictEqual(child.signal, 'SIGTERM');
});
});
Loading