Skip to content

Commit 559afb1

Browse files
maxhfisherlegendecas
authored andcommitted
src: add SetAbortHandler
Signed-off-by: Max H Fisher <mfisher187@bloomberg.net> PR-URL: #64684 Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent eff293f commit 559afb1

7 files changed

Lines changed: 171 additions & 9 deletions

File tree

src/node.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,16 @@ NODE_EXTERN void SetProcessExitHandler(
844844
std::function<void(Environment*, int)>&& handler);
845845
NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
846846

847+
// Sets a process-global handler invoked when Node.js programmatically aborts.
848+
// Nullable strings representing the location and reason for the abort may or
849+
// may not be passed as a parameter to the handler. The handler should not
850+
// return, but node will ensure that the process exits after the handler is
851+
// called regardless of whether or not it returns. Passing nullptr restores the
852+
// default handler. This is process-global and may be invoked before any Isolate
853+
// or Environment exists.
854+
using AbortHandler = void (*)(const char* location, const char* message);
855+
NODE_EXTERN void SetAbortHandler(AbortHandler handler);
856+
847857
// This may return nullptr if context is not associated with a Node instance.
848858
NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
849859
NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env);

src/node_errors.cc

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,30 @@ void AppendExceptionLine(Environment* env,
393393
.FromMaybe(false));
394394
}
395395

396+
namespace {
397+
// Default handler: Dumps native + JS backtraces to stderr and exits. This
398+
// indirectly calls backtrace so it can not be marked as [[noreturn]] (see the
399+
// comment on node::Assert() below). `message` and `location` are ignored
400+
// because the assertion/fatal-error message, if any, is already printed to
401+
// stderr by the caller (Assert()/OnFatalError()) before this handler runs.
402+
void DefaultAbortHandler(const char* /*location*/, const char* /*message*/) {
403+
DumpNativeBacktrace(stderr);
404+
DumpJavaScriptBacktrace(stderr);
405+
fflush(stderr);
406+
ABORT_NO_BACKTRACE();
407+
}
408+
// Constant-initialized, so this is valid from load time, safe even for a
409+
// CHECK() during early startup, before any SetAbortHandler call.
410+
AbortHandler g_abort_handler = DefaultAbortHandler;
411+
} // namespace
412+
413+
void SetAbortHandler(AbortHandler handler) {
414+
g_abort_handler = handler ? handler : DefaultAbortHandler;
415+
}
416+
AbortHandler GetAbortHandler() {
417+
return g_abort_handler;
418+
}
419+
396420
void Assert(const AssertionInfo& info) {
397421
std::string name = GetHumanReadableProcessName();
398422

@@ -406,7 +430,7 @@ void Assert(const AssertionInfo& info) {
406430
info.message);
407431

408432
fflush(stderr);
409-
ABORT();
433+
ABORT_WITH_DETAILS(info.file_line, info.message);
410434
}
411435

412436
enum class EnhanceFatalException { kEnhance, kDontEnhance };
@@ -584,7 +608,7 @@ static void ReportFatalException(Environment* env,
584608
}
585609

586610
fflush(stderr);
587-
ABORT();
611+
ABORT_WITH_DETAILS(location, message);
588612
}
589613

590614
void OOMErrorHandler(const char* location, const v8::OOMDetails& details) {
@@ -620,7 +644,7 @@ void OOMErrorHandler(const char* location, const v8::OOMDetails& details) {
620644
}
621645

622646
fflush(stderr);
623-
ABORT();
647+
ABORT_WITH_DETAILS(location, message);
624648
}
625649

626650
v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings(

src/util.h

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ void NODE_EXTERN_PRIVATE Assert(const AssertionInfo& info);
128128
void DumpNativeBacktrace(FILE* fp);
129129
void DumpJavaScriptBacktrace(FILE* fp);
130130

131+
// Returns the currently installed abort handler which is never null.
132+
AbortHandler GetAbortHandler();
133+
131134
// Windows 8+ does not like abort() in Release mode
132135
#ifdef _WIN32
133136
#define ABORT_NO_BACKTRACE() _exit(static_cast<int>(node::ExitCode::kAbort))
@@ -140,13 +143,12 @@ void DumpJavaScriptBacktrace(FILE* fp);
140143
// when generating code for them the compiler can choose not to
141144
// maintain the frame pointers or link registers that are necessary for
142145
// correct backtracing.
143-
// `ABORT` must be a macro and not a [[noreturn]] function to make sure the
144-
// backtrace is correct.
145-
#define ABORT() \
146+
// `ABORT` and `ABORT_WITH_DETAILS` must be a macro and not a [[noreturn]]
147+
// function to make sure the backtrace is correct.
148+
#define ABORT() ABORT_WITH_DETAILS(__FILE__ ":" STRINGIFY(__LINE__), nullptr)
149+
#define ABORT_WITH_DETAILS(location, message) \
146150
do { \
147-
node::DumpNativeBacktrace(stderr); \
148-
node::DumpJavaScriptBacktrace(stderr); \
149-
fflush(stderr); \
151+
node::GetAbortHandler()(location, message); \
150152
ABORT_NO_BACKTRACE(); \
151153
} while (0)
152154

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#include <node.h>
2+
#include <v8.h>
3+
#include <cstdio>
4+
5+
namespace {
6+
void TestAbortHandler(const char* /*location*/, const char* /*message*/) {
7+
fputs("CUSTOM_ABORT_HANDLER_RAN\n", stderr);
8+
fflush(stderr);
9+
}
10+
11+
void InstallAbortHandler(const v8::FunctionCallbackInfo<v8::Value>&) {
12+
node::SetAbortHandler(TestAbortHandler);
13+
}
14+
} // namespace
15+
16+
NODE_MODULE_INIT() {
17+
NODE_SET_METHOD(exports, "installAbortHandler", InstallAbortHandler);
18+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
'targets': [
3+
{
4+
'target_name': 'binding',
5+
'sources': [ 'binding.cc' ],
6+
'includes': ['../common.gypi'],
7+
}
8+
]
9+
}

test/addons/abort-handler/test.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
const common = require('../../common');
3+
const assert = require('assert');
4+
const fs = require('fs');
5+
const path = require('path');
6+
const { exec } = require('child_process');
7+
8+
const bindingPath = path.resolve(
9+
__dirname, 'build', common.buildType, 'binding.node');
10+
11+
if (!fs.existsSync(bindingPath))
12+
common.skip('binding not built yet');
13+
14+
if (process.argv[2] === 'child') {
15+
const binding = require(bindingPath);
16+
binding.installAbortHandler();
17+
process.abort();
18+
return;
19+
}
20+
21+
const escapedArgs =
22+
common.escapePOSIXShell`"${process.execPath}" "${__filename}" child`;
23+
if (!common.isWindows) {
24+
// Do not create core files, as it can take a lot of disk space on
25+
// continuous testing and developers' machines.
26+
escapedArgs[0] = 'ulimit -c 0 && ' + escapedArgs[0];
27+
}
28+
29+
exec(...escapedArgs, common.mustCall((err, stdout, stderr) => {
30+
assert.ok(
31+
stderr.includes('CUSTOM_ABORT_HANDLER_RAN'),
32+
`Expected custom abort handler marker in stderr, got:\n${stderr}`);
33+
assert.ok(
34+
!stderr.includes('Native stack trace'),
35+
`Expected the custom handler to replace the default dump, got:\n${stderr}`);
36+
37+
// The child aborts. Whether that surfaces as the SIGABRT signal or as exit
38+
// code 134 depends on shell wrapping: the `ulimit -c 0 && ...` prefix makes
39+
// /bin/sh wait on (rather than exec-replace itself with) the node grandchild,
40+
// so sh reports the aborted grandchild as a normal exit with code 134.
41+
// common.nodeProcessAborted() accepts both forms.
42+
assert.ok(
43+
err && common.nodeProcessAborted(err.code, err.signal),
44+
`Expected the child to abort, got code=${err?.code} signal=${err?.signal}`);
45+
}));

test/cctest/test_environment.cc

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1201,3 +1201,57 @@ TEST_F(EnvironmentTest, LoadEnvironmentWithCallbackWithESModule) {
12011201
printf("Frame: %s\n", *frame_str);
12021202
EXPECT_EQ(frame_str.ToString(), " at embedded:esm.mjs:3:15");
12031203
}
1204+
1205+
namespace {
1206+
void CustomAbortHandlerForContractTest(const char* location,
1207+
const char* message) {}
1208+
1209+
bool abort_handler_dispatch_flag = false;
1210+
const char* abort_handler_received_location = nullptr;
1211+
const char* abort_handler_received_message = nullptr;
1212+
void AbortHandlerThatSetsDispatchFlag(const char* location,
1213+
const char* message) {
1214+
abort_handler_dispatch_flag = true;
1215+
abort_handler_received_location = location;
1216+
abort_handler_received_message = message;
1217+
}
1218+
} // namespace
1219+
1220+
TEST(AbortHandlerTest, DefaultIsNonNullAndSetAbortHandlerRoundTrips) {
1221+
node::AbortHandler old = node::GetAbortHandler();
1222+
1223+
// There should always be a non-null default handler installed.
1224+
EXPECT_NE(node::GetAbortHandler(), nullptr);
1225+
1226+
node::SetAbortHandler(CustomAbortHandlerForContractTest);
1227+
EXPECT_EQ(node::GetAbortHandler(), CustomAbortHandlerForContractTest);
1228+
1229+
node::SetAbortHandler(nullptr);
1230+
EXPECT_NE(node::GetAbortHandler(), nullptr);
1231+
EXPECT_NE(node::GetAbortHandler(), CustomAbortHandlerForContractTest);
1232+
1233+
node::SetAbortHandler(old);
1234+
}
1235+
1236+
TEST(AbortHandlerTest, InstalledHandlerIsInvokedWhenCalled) {
1237+
node::AbortHandler old = node::GetAbortHandler();
1238+
abort_handler_dispatch_flag = false;
1239+
abort_handler_received_location = nullptr;
1240+
abort_handler_received_message = nullptr;
1241+
1242+
node::SetAbortHandler(AbortHandlerThatSetsDispatchFlag);
1243+
node::AbortHandler h = node::GetAbortHandler();
1244+
// Fail cleanly (instead of crashing on a null call) if the handler wasn't
1245+
// actually installed.
1246+
ASSERT_NE(h, nullptr);
1247+
1248+
// Dispatch through the public GetAbortHandler() accessor directly (not via
1249+
// the ABORT() macro, so nothing terminates), and verify the message is
1250+
// passed through unchanged.
1251+
node::GetAbortHandler()("some-test-location", "some-test-message");
1252+
EXPECT_TRUE(abort_handler_dispatch_flag);
1253+
EXPECT_STREQ(abort_handler_received_location, "some-test-location");
1254+
EXPECT_STREQ(abort_handler_received_message, "some-test-message");
1255+
1256+
node::SetAbortHandler(old);
1257+
}

0 commit comments

Comments
 (0)