Skip to content

Commit f4b0f7a

Browse files
author
Gabriel Schulhof
committed
n-api: ensure in-module exceptions are propagated
Whenever we call into an addon, whether it is for a callback, for module init, or for async work-related reasons, we should make sure that * the last error is cleared, * the scopes before the call are the same as after, and * if an exception was thrown and captured inside the module, then it is re-thrown after the call. Therefore we should call into the module in a unified fashion. This change introduces the macro NAPI_CALL_INTO_MODULE() which should be used whenever invoking a callback provided by the module. Fixes: nodejs#19437 PR-URL: nodejs#19537 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
1 parent 96fe46b commit f4b0f7a

File tree

3 files changed

+108
-43
lines changed

3 files changed

+108
-43
lines changed

src/node_api.cc

+42-37
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,24 @@ struct napi_env__ {
168168
(out) = v8::type::New((buffer), (byte_offset), (length)); \
169169
} while (0)
170170

171+
#define NAPI_CALL_INTO_MODULE(env, call, handle_exception) \
172+
do { \
173+
int open_handle_scopes = (env)->open_handle_scopes; \
174+
int open_callback_scopes = (env)->open_callback_scopes; \
175+
napi_clear_last_error((env)); \
176+
call; \
177+
CHECK_EQ((env)->open_handle_scopes, open_handle_scopes); \
178+
CHECK_EQ((env)->open_callback_scopes, open_callback_scopes); \
179+
if (!(env)->last_exception.IsEmpty()) { \
180+
handle_exception( \
181+
v8::Local<v8::Value>::New((env)->isolate, (env)->last_exception)); \
182+
(env)->last_exception.Reset(); \
183+
} \
184+
} while (0)
185+
186+
#define NAPI_CALL_INTO_MODULE_THROW(env, call) \
187+
NAPI_CALL_INTO_MODULE((env), call, (env)->isolate->ThrowException)
188+
171189
namespace v8impl {
172190

173191
// convert from n-api property attributes to v8::PropertyAttribute
@@ -349,10 +367,11 @@ class Finalizer {
349367
static void FinalizeBufferCallback(char* data, void* hint) {
350368
Finalizer* finalizer = static_cast<Finalizer*>(hint);
351369
if (finalizer->_finalize_callback != nullptr) {
352-
finalizer->_finalize_callback(
353-
finalizer->_env,
354-
data,
355-
finalizer->_finalize_hint);
370+
NAPI_CALL_INTO_MODULE_THROW(finalizer->_env,
371+
finalizer->_finalize_callback(
372+
finalizer->_env,
373+
data,
374+
finalizer->_finalize_hint));
356375
}
357376

358377
Delete(finalizer);
@@ -464,10 +483,11 @@ class Reference : private Finalizer {
464483
bool delete_self = reference->_delete_self;
465484

466485
if (reference->_finalize_callback != nullptr) {
467-
reference->_finalize_callback(
468-
reference->_env,
469-
reference->_finalize_data,
470-
reference->_finalize_hint);
486+
NAPI_CALL_INTO_MODULE_THROW(reference->_env,
487+
reference->_finalize_callback(
488+
reference->_env,
489+
reference->_finalize_data,
490+
reference->_finalize_hint));
471491
}
472492

473493
if (delete_self) {
@@ -552,32 +572,17 @@ class CallbackWrapperBase : public CallbackWrapper {
552572
napi_callback cb = reinterpret_cast<napi_callback>(
553573
v8::Local<v8::External>::Cast(
554574
_cbdata->GetInternalField(kInternalFieldIndex))->Value());
555-
v8::Isolate* isolate = _cbinfo.GetIsolate();
556575

557576
napi_env env = static_cast<napi_env>(
558577
v8::Local<v8::External>::Cast(
559578
_cbdata->GetInternalField(kEnvIndex))->Value());
560579

561-
// Make sure any errors encountered last time we were in N-API are gone.
562-
napi_clear_last_error(env);
563-
564-
int open_handle_scopes = env->open_handle_scopes;
565-
int open_callback_scopes = env->open_callback_scopes;
566-
567-
napi_value result = cb(env, cbinfo_wrapper);
580+
napi_value result;
581+
NAPI_CALL_INTO_MODULE_THROW(env, result = cb(env, cbinfo_wrapper));
568582

569583
if (result != nullptr) {
570584
this->SetReturnValue(result);
571585
}
572-
573-
CHECK_EQ(env->open_handle_scopes, open_handle_scopes);
574-
CHECK_EQ(env->open_callback_scopes, open_callback_scopes);
575-
576-
if (!env->last_exception.IsEmpty()) {
577-
isolate->ThrowException(
578-
v8::Local<v8::Value>::New(isolate, env->last_exception));
579-
env->last_exception.Reset();
580-
}
581586
}
582587

583588
const Info& _cbinfo;
@@ -885,8 +890,10 @@ void napi_module_register_cb(v8::Local<v8::Object> exports,
885890
// one is found.
886891
napi_env env = v8impl::GetEnv(context);
887892

888-
napi_value _exports =
889-
mod->nm_register_func(env, v8impl::JsValueFromV8LocalValue(exports));
893+
napi_value _exports;
894+
NAPI_CALL_INTO_MODULE_THROW(env,
895+
_exports = mod->nm_register_func(env,
896+
v8impl::JsValueFromV8LocalValue(exports)));
890897

891898
// If register function returned a non-null exports object different from
892899
// the exports object we passed it, set that as the "exports" property of
@@ -3465,19 +3472,17 @@ class Work : public node::AsyncResource {
34653472
v8::HandleScope scope(env->isolate);
34663473
CallbackScope callback_scope(work);
34673474

3468-
work->_complete(env, ConvertUVErrorCode(status), work->_data);
3475+
NAPI_CALL_INTO_MODULE(env,
3476+
work->_complete(env, ConvertUVErrorCode(status), work->_data),
3477+
[env] (v8::Local<v8::Value> local_err) {
3478+
// If there was an unhandled exception in the complete callback,
3479+
// report it as a fatal exception. (There is no JavaScript on the
3480+
// callstack that can possibly handle it.)
3481+
v8impl::trigger_fatal_exception(env, local_err);
3482+
});
34693483

34703484
// Note: Don't access `work` after this point because it was
34713485
// likely deleted by the complete callback.
3472-
3473-
// If there was an unhandled exception in the complete callback,
3474-
// report it as a fatal exception. (There is no JavaScript on the
3475-
// callstack that can possibly handle it.)
3476-
if (!env->last_exception.IsEmpty()) {
3477-
v8::Local<v8::Value> local_err = v8::Local<v8::Value>::New(
3478-
env->isolate, env->last_exception);
3479-
v8impl::trigger_fatal_exception(env, local_err);
3480-
}
34813486
}
34823487
}
34833488

test/addons-napi/test_exception/test.js

+29-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
11
'use strict';
2+
// Flags: --expose-gc
23

34
const common = require('../../common');
4-
const test_exception = require(`./build/${common.buildType}/test_exception`);
55
const assert = require('assert');
66
const theError = new Error('Some error');
77

8+
// The test module throws an error during Init, but in order for its exports to
9+
// not be lost, it attaches them to the error's "bindings" property. This way,
10+
// we can make sure that exceptions thrown during the module initialization
11+
// phase are propagated through require() into JavaScript.
12+
// https://github.com/nodejs/node/issues/19437
13+
const test_exception = (function() {
14+
let resultingException;
15+
try {
16+
require(`./build/${common.buildType}/test_exception`);
17+
} catch (anException) {
18+
resultingException = anException;
19+
}
20+
assert.strictEqual(resultingException.message, 'Error during Init');
21+
return resultingException.binding;
22+
})();
23+
824
{
925
const throwTheError = () => { throw theError; };
1026

@@ -50,3 +66,15 @@ const theError = new Error('Some error');
5066
'Exception state did not remain clear as expected,' +
5167
` .wasPending() returned ${exception_pending}`);
5268
}
69+
70+
// Make sure that exceptions that occur during finalization are propagated.
71+
function testFinalize(binding) {
72+
let x = test_exception[binding]();
73+
x = null;
74+
assert.throws(() => { global.gc(); }, /Error during Finalize/);
75+
76+
// To assuage the linter's concerns.
77+
(function() {})(x);
78+
}
79+
testFinalize('createExternal');
80+
testFinalize('createExternalBuffer');

test/addons-napi/test_exception/test_exception.c

+37-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
static bool exceptionWasPending = false;
55

6-
napi_value returnException(napi_env env, napi_callback_info info) {
6+
static napi_value returnException(napi_env env, napi_callback_info info) {
77
size_t argc = 1;
88
napi_value args[1];
99
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
@@ -22,7 +22,7 @@ napi_value returnException(napi_env env, napi_callback_info info) {
2222
return NULL;
2323
}
2424

25-
napi_value allowException(napi_env env, napi_callback_info info) {
25+
static napi_value allowException(napi_env env, napi_callback_info info) {
2626
size_t argc = 1;
2727
napi_value args[1];
2828
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
@@ -38,23 +38,55 @@ napi_value allowException(napi_env env, napi_callback_info info) {
3838
return NULL;
3939
}
4040

41-
napi_value wasPending(napi_env env, napi_callback_info info) {
41+
static napi_value wasPending(napi_env env, napi_callback_info info) {
4242
napi_value result;
4343
NAPI_CALL(env, napi_get_boolean(env, exceptionWasPending, &result));
4444

4545
return result;
4646
}
4747

48-
napi_value Init(napi_env env, napi_value exports) {
48+
static void finalizer(napi_env env, void *data, void *hint) {
49+
NAPI_CALL_RETURN_VOID(env,
50+
napi_throw_error(env, NULL, "Error during Finalize"));
51+
}
52+
53+
static napi_value createExternal(napi_env env, napi_callback_info info) {
54+
napi_value external;
55+
56+
NAPI_CALL(env,
57+
napi_create_external(env, NULL, finalizer, NULL, &external));
58+
59+
return external;
60+
}
61+
62+
static char buffer_data[12];
63+
64+
static napi_value createExternalBuffer(napi_env env, napi_callback_info info) {
65+
napi_value buffer;
66+
NAPI_CALL(env, napi_create_external_buffer(env, sizeof(buffer_data),
67+
buffer_data, finalizer, NULL, &buffer));
68+
return buffer;
69+
}
70+
71+
static napi_value Init(napi_env env, napi_value exports) {
4972
napi_property_descriptor descriptors[] = {
5073
DECLARE_NAPI_PROPERTY("returnException", returnException),
5174
DECLARE_NAPI_PROPERTY("allowException", allowException),
5275
DECLARE_NAPI_PROPERTY("wasPending", wasPending),
76+
DECLARE_NAPI_PROPERTY("createExternal", createExternal),
77+
DECLARE_NAPI_PROPERTY("createExternalBuffer", createExternalBuffer),
5378
};
54-
5579
NAPI_CALL(env, napi_define_properties(
5680
env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors));
5781

82+
napi_value error, code, message;
83+
NAPI_CALL(env, napi_create_string_utf8(env, "Error during Init",
84+
NAPI_AUTO_LENGTH, &message));
85+
NAPI_CALL(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &code));
86+
NAPI_CALL(env, napi_create_error(env, code, message, &error));
87+
NAPI_CALL(env, napi_set_named_property(env, error, "binding", exports));
88+
NAPI_CALL(env, napi_throw(env, error));
89+
5890
return exports;
5991
}
6092

0 commit comments

Comments
 (0)