Skip to content

Commit ae41fe3

Browse files
committed
n-api: emit uncaught-exception on unhandled tsfn callbacks
1 parent fec093b commit ae41fe3

File tree

12 files changed

+283
-48
lines changed

12 files changed

+283
-48
lines changed

doc/api/cli.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,13 @@ added: v9.0.0
585585
Disables runtime checks for `async_hooks`. These will still be enabled
586586
dynamically when `async_hooks` is enabled.
587587

588+
### `--no-force-napi-uncaught-exceptions-policy`
589+
<!-- YAML
590+
added: REPLACEME
591+
-->
592+
593+
Disables 'uncaughtException' event on N-API asynchronous callbacks.
594+
588595
### `--no-warnings`
589596
<!-- YAML
590597
added: v6.0.0
@@ -1378,6 +1385,7 @@ Node.js options that are allowed are:
13781385
* `--napi-modules`
13791386
* `--no-deprecation`
13801387
* `--no-force-async-hooks-checks`
1388+
* `--no-force-napi-uncaught-exceptions-policy`
13811389
* `--no-warnings`
13821390
* `--node-memory-debug`
13831391
* `--openssl-config`

src/js_native_api_v8.h

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,7 @@ struct napi_env__ {
5757
context_persistent(isolate, context) {
5858
CHECK_EQ(isolate, context->GetIsolate());
5959
}
60-
virtual ~napi_env__() {
61-
// First we must finalize those references that have `napi_finalizer`
62-
// callbacks. The reason is that addons might store other references which
63-
// they delete during their `napi_finalizer` callbacks. If we deleted such
64-
// references here first, they would be doubly deleted when the
65-
// `napi_finalizer` deleted them subsequently.
66-
v8impl::RefTracker::FinalizeAll(&finalizing_reflist);
67-
v8impl::RefTracker::FinalizeAll(&reflist);
68-
}
60+
virtual ~napi_env__() { FinalizeAll(); }
6961
v8::Isolate* const isolate; // Shortcut for context()->GetIsolate()
7062
v8impl::Persistent<v8::Context> context_persistent;
7163

@@ -102,10 +94,17 @@ struct napi_env__ {
10294
}
10395

10496
virtual void CallFinalizer(napi_finalize cb, void* data, void* hint) {
105-
v8::HandleScope handle_scope(isolate);
106-
CallIntoModule([&](napi_env env) {
107-
cb(env, data, hint);
108-
});
97+
// Forward declaration virtual member. Implemented in node_napi_env__.
98+
}
99+
100+
void FinalizeAll() {
101+
// First we must finalize those references that have `napi_finalizer`
102+
// callbacks. The reason is that addons might store other references which
103+
// they delete during their `napi_finalizer` callbacks. If we deleted such
104+
// references here first, they would be doubly deleted when the
105+
// `napi_finalizer` deleted them subsequently.
106+
v8impl::RefTracker::FinalizeAll(&finalizing_reflist);
107+
v8impl::RefTracker::FinalizeAll(&reflist);
109108
}
110109

111110
v8impl::Persistent<v8::Value> last_exception;

src/node_api.cc

Lines changed: 62 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "node_buffer.h"
99
#include "node_errors.h"
1010
#include "node_internals.h"
11+
#include "node_process.h"
1112
#include "threadpoolwork-inl.h"
1213
#include "tracing/traced_value.h"
1314
#include "util-inl.h"
@@ -20,6 +21,8 @@ struct node_napi_env__ : public napi_env__ {
2021
CHECK_NOT_NULL(node_env());
2122
}
2223

24+
~node_napi_env__() { FinalizeAll(); }
25+
2326
inline node::Environment* node_env() const {
2427
return node::Environment::GetCurrent(context());
2528
}
@@ -36,15 +39,55 @@ struct node_napi_env__ : public napi_env__ {
3639
v8::True(isolate));
3740
}
3841

42+
inline void trigger_fatal_exception(v8::Local<v8::Value> local_err) {
43+
v8::Local<v8::Message> local_msg =
44+
v8::Exception::CreateMessage(isolate, local_err);
45+
node::errors::TriggerUncaughtException(isolate, local_err, local_msg);
46+
}
47+
48+
// option enforceUncaughtExceptionPolicy is added for not breaking existing
49+
// running n-api add-ons, and should be deprecated in the next major Node.js
50+
// release.
51+
template <typename T>
52+
inline void CallbackIntoModule(T&& call,
53+
bool enforceUncaughtExceptionPolicy = false) {
54+
CallIntoModule(
55+
call,
56+
[enforceUncaughtExceptionPolicy](napi_env env_,
57+
v8::Local<v8::Value> local_err) {
58+
node_napi_env__* env = static_cast<node_napi_env__*>(env_);
59+
node::Environment* node_env = env->node_env();
60+
if (node_env->options()->no_force_napi_uncaught_exception_policy &&
61+
!enforceUncaughtExceptionPolicy) {
62+
ProcessEmitDeprecationWarning(
63+
node_env,
64+
"Uncaught N-API callback exception detected, please run node "
65+
"without option "
66+
"--no-force-napi-uncaught-exceptions-policy to handle those"
67+
"exceptions properly.",
68+
"DEP0XXX");
69+
return;
70+
}
71+
// If there was an unhandled exception in the complete callback,
72+
// report it as a fatal exception. (There is no JavaScript on the
73+
// callstack that can possibly handle it.)
74+
env->trigger_fatal_exception(local_err);
75+
});
76+
}
77+
3978
void CallFinalizer(napi_finalize cb, void* data, void* hint) override {
79+
CallFinalizer(cb, data, hint, true);
80+
}
81+
82+
inline void CallFinalizer(napi_finalize cb,
83+
void* data,
84+
void* hint,
85+
bool enforceUncaughtExceptionPolicy) {
4086
napi_env env = static_cast<napi_env>(this);
41-
node_env()->SetImmediate([=](node::Environment* node_env) {
42-
v8::HandleScope handle_scope(env->isolate);
43-
v8::Context::Scope context_scope(env->context());
44-
env->CallIntoModule([&](napi_env env) {
45-
cb(env, data, hint);
46-
});
47-
});
87+
v8::HandleScope handle_scope(env->isolate);
88+
v8::Context::Scope context_scope(env->context());
89+
CallbackIntoModule([&](napi_env env) { cb(env, data, hint); },
90+
enforceUncaughtExceptionPolicy);
4891
}
4992
};
5093

@@ -71,12 +114,9 @@ class BufferFinalizer : private Finalizer {
71114
v8::HandleScope handle_scope(finalizer->_env->isolate);
72115
v8::Context::Scope context_scope(finalizer->_env->context());
73116

74-
finalizer->_env->CallIntoModule([&](napi_env env) {
75-
finalizer->_finalize_callback(
76-
env,
77-
finalizer->_finalize_data,
78-
finalizer->_finalize_hint);
79-
});
117+
finalizer->_env->CallFinalizer(finalizer->_finalize_callback,
118+
finalizer->_finalize_data,
119+
finalizer->_finalize_hint);
80120
});
81121
}
82122

@@ -107,13 +147,6 @@ static inline napi_env NewEnv(v8::Local<v8::Context> context) {
107147
return result;
108148
}
109149

110-
static inline void trigger_fatal_exception(
111-
napi_env env, v8::Local<v8::Value> local_err) {
112-
v8::Local<v8::Message> local_msg =
113-
v8::Exception::CreateMessage(env->isolate, local_err);
114-
node::errors::TriggerUncaughtException(env->isolate, local_err, local_msg);
115-
}
116-
117150
class ThreadSafeFunction : public node::AsyncResource {
118151
public:
119152
ThreadSafeFunction(v8::Local<v8::Function> func,
@@ -312,19 +345,16 @@ class ThreadSafeFunction : public node::AsyncResource {
312345
v8::Local<v8::Function>::New(env->isolate, ref);
313346
js_callback = v8impl::JsValueFromV8LocalValue(js_cb);
314347
}
315-
env->CallIntoModule([&](napi_env env) {
316-
call_js_cb(env, js_callback, context, data);
317-
});
348+
env->CallbackIntoModule(
349+
[&](napi_env env) { call_js_cb(env, js_callback, context, data); });
318350
}
319351
}
320352

321353
void Finalize() {
322354
v8::HandleScope scope(env->isolate);
323355
if (finalize_cb) {
324356
CallbackScope cb_scope(this);
325-
env->CallIntoModule([&](napi_env env) {
326-
finalize_cb(env, finalize_data, context);
327-
});
357+
env->CallFinalizer(finalize_cb, finalize_data, context, false);
328358
}
329359
EmptyQueueAndDelete();
330360
}
@@ -693,7 +723,7 @@ napi_status napi_fatal_exception(napi_env env, napi_value err) {
693723
CHECK_ARG(env, err);
694724

695725
v8::Local<v8::Value> local_err = v8impl::V8LocalValueFromJsValue(err);
696-
v8impl::trigger_fatal_exception(env, local_err);
726+
static_cast<node_napi_env>(env)->trigger_fatal_exception(local_err);
697727

698728
return napi_clear_last_error(env);
699729
}
@@ -1043,14 +1073,11 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork {
10431073

10441074
CallbackScope callback_scope(this);
10451075

1046-
_env->CallIntoModule([&](napi_env env) {
1047-
_complete(env, ConvertUVErrorCode(status), _data);
1048-
}, [](napi_env env, v8::Local<v8::Value> local_err) {
1049-
// If there was an unhandled exception in the complete callback,
1050-
// report it as a fatal exception. (There is no JavaScript on the
1051-
// callstack that can possibly handle it.)
1052-
v8impl::trigger_fatal_exception(env, local_err);
1053-
});
1076+
_env->CallbackIntoModule(
1077+
[&](napi_env env) {
1078+
_complete(env, ConvertUVErrorCode(status), _data);
1079+
},
1080+
true);
10541081

10551082
// Note: Don't access `work` after this point because it was
10561083
// likely deleted by the complete callback.

src/node_options.cc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
391391
"disable checks for async_hooks",
392392
&EnvironmentOptions::no_force_async_hooks_checks,
393393
kAllowedInEnvironment);
394+
AddOption("--no-force-napi-uncaught-exceptions-policy",
395+
"disable 'uncaughtException' event on N-API asynchronous callbacks",
396+
&EnvironmentOptions::no_force_napi_uncaught_exception_policy,
397+
kAllowedInEnvironment);
394398
AddOption("--no-warnings",
395399
"silence all process warnings",
396400
&EnvironmentOptions::no_warnings,

src/node_options.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ class EnvironmentOptions : public Options {
120120
uint64_t max_http_header_size = 16 * 1024;
121121
bool no_deprecation = false;
122122
bool no_force_async_hooks_checks = false;
123+
bool no_force_napi_uncaught_exception_policy = false;
123124
bool no_warnings = false;
124125
bool force_context_aware = false;
125126
bool pending_deprecation = false;
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
// Flags: --expose-gc --no-concurrent-array-buffer-freeing --no-concurrent-array-buffer-sweeping
3+
4+
const common = require('../../common');
5+
const test_reference = require(`./build/${common.buildType}/test_reference`);
6+
const assert = require('assert');
7+
8+
process.on('uncaughtException', common.mustCall((err) => {
9+
assert.throws(() => { throw err; }, /finalizer error/);
10+
}));
11+
12+
(async function() {
13+
{
14+
test_reference.createExternalWithJsFinalize(
15+
common.mustCall(() => {
16+
throw new Error('finalizer error');
17+
}));
18+
}
19+
global.gc();
20+
})().then(common.mustCall());

test/js-native-api/test_reference/test_reference.c

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,20 @@ static void FinalizeExternal(napi_env env, void* data, void* hint) {
2020
finalize_count++;
2121
}
2222

23+
static void FinalizeExternalCallJs(napi_env env, void* data, void* hint) {
24+
int *actual_value = data;
25+
NAPI_ASSERT_RETURN_VOID(env, actual_value == &test_value,
26+
"The correct pointer was passed to the finalizer");
27+
28+
napi_ref finalizer_ref = (napi_ref)hint;
29+
napi_value js_finalizer;
30+
napi_value recv;
31+
NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, finalizer_ref, &js_finalizer));
32+
NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &recv));
33+
NAPI_CALL_RETURN_VOID(env, napi_call_function(env, recv, js_finalizer, 0, NULL, NULL));
34+
NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, finalizer_ref));
35+
}
36+
2337
static napi_value CreateExternal(napi_env env, napi_callback_info info) {
2438
int* data = &test_value;
2539

@@ -49,6 +63,31 @@ CreateExternalWithFinalize(napi_env env, napi_callback_info info) {
4963
return result;
5064
}
5165

66+
static napi_value
67+
CreateExternalWithJsFinalize(napi_env env, napi_callback_info info) {
68+
size_t argc = 1;
69+
napi_value args[1];
70+
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
71+
NAPI_ASSERT(env, argc == 1, "Wrong number of arguments");
72+
napi_value finalizer = args[0];
73+
napi_valuetype finalizer_valuetype;
74+
NAPI_CALL(env, napi_typeof(env, finalizer, &finalizer_valuetype));
75+
NAPI_ASSERT(env, finalizer_valuetype == napi_function, "Wrong type of first argument");
76+
napi_ref finalizer_ref;
77+
NAPI_CALL(env, napi_create_reference(env, finalizer, 1, &finalizer_ref));
78+
79+
napi_value result;
80+
NAPI_CALL(env,
81+
napi_create_external(env,
82+
&test_value,
83+
FinalizeExternalCallJs,
84+
finalizer_ref, /* finalize_hint */
85+
&result));
86+
87+
finalize_count = 0;
88+
return result;
89+
}
90+
5291
static napi_value CheckExternal(napi_env env, napi_callback_info info) {
5392
size_t argc = 1;
5493
napi_value arg;
@@ -176,6 +215,8 @@ napi_value Init(napi_env env, napi_value exports) {
176215
DECLARE_NAPI_PROPERTY("createExternal", CreateExternal),
177216
DECLARE_NAPI_PROPERTY("createExternalWithFinalize",
178217
CreateExternalWithFinalize),
218+
DECLARE_NAPI_PROPERTY("createExternalWithJsFinalize",
219+
CreateExternalWithJsFinalize),
179220
DECLARE_NAPI_PROPERTY("checkExternal", CheckExternal),
180221
DECLARE_NAPI_PROPERTY("createReference", CreateReference),
181222
DECLARE_NAPI_PROPERTY("deleteReference", DeleteReference),

test/node-api/test_buffer/test_buffer.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,17 @@ static void noopDeleter(napi_env env, void* data, void* finalize_hint) {
2020
deleterCallCount++;
2121
}
2222

23+
static void malignDeleter(napi_env env, void* data, void* finalize_hint) {
24+
NAPI_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, theText) == 0, "invalid data");
25+
napi_ref finalizer_ref = (napi_ref)finalize_hint;
26+
napi_value js_finalizer;
27+
napi_value recv;
28+
NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, finalizer_ref, &js_finalizer));
29+
NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &recv));
30+
NAPI_CALL_RETURN_VOID(env, napi_call_function(env, recv, js_finalizer, 0, NULL, NULL));
31+
NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, finalizer_ref));
32+
}
33+
2334
static napi_value newBuffer(napi_env env, napi_callback_info info) {
2435
napi_value theBuffer;
2536
char* theCopy;
@@ -119,6 +130,30 @@ static napi_value staticBuffer(napi_env env, napi_callback_info info) {
119130
return theBuffer;
120131
}
121132

133+
static napi_value malignFinalizerBuffer(napi_env env, napi_callback_info info) {
134+
size_t argc = 1;
135+
napi_value args[1];
136+
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
137+
NAPI_ASSERT(env, argc == 1, "Wrong number of arguments");
138+
napi_value finalizer = args[0];
139+
napi_valuetype finalizer_valuetype;
140+
NAPI_CALL(env, napi_typeof(env, finalizer, &finalizer_valuetype));
141+
NAPI_ASSERT(env, finalizer_valuetype == napi_function, "Wrong type of first argument");
142+
napi_ref finalizer_ref;
143+
NAPI_CALL(env, napi_create_reference(env, finalizer, 1, &finalizer_ref));
144+
145+
napi_value theBuffer;
146+
NAPI_CALL(
147+
env,
148+
napi_create_external_buffer(env,
149+
sizeof(theText),
150+
(void*)theText,
151+
malignDeleter,
152+
finalizer_ref, // finalize_hint
153+
&theBuffer));
154+
return theBuffer;
155+
}
156+
122157
static napi_value Init(napi_env env, napi_value exports) {
123158
napi_value theValue;
124159

@@ -134,6 +169,7 @@ static napi_value Init(napi_env env, napi_value exports) {
134169
DECLARE_NAPI_PROPERTY("bufferHasInstance", bufferHasInstance),
135170
DECLARE_NAPI_PROPERTY("bufferInfo", bufferInfo),
136171
DECLARE_NAPI_PROPERTY("staticBuffer", staticBuffer),
172+
DECLARE_NAPI_PROPERTY("malignFinalizerBuffer", malignFinalizerBuffer),
137173
};
138174

139175
NAPI_CALL(env, napi_define_properties(

0 commit comments

Comments
 (0)