Skip to content

Commit 9e22647

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: #19437 PR-URL: #19537 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Michael Dawson <[email protected]>
1 parent 8eca6b8 commit 9e22647

File tree

3 files changed

+107
-43
lines changed

3 files changed

+107
-43
lines changed

src/node_api.cc

+41-37
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,23 @@ struct napi_env__ {
157157
(out) = v8::type::New((buffer), (byte_offset), (length)); \
158158
} while (0)
159159

160+
#define NAPI_CALL_INTO_MODULE(env, call, handle_exception) \
161+
do { \
162+
int open_handle_scopes = (env)->open_handle_scopes; \
163+
int open_callback_scopes = (env)->open_callback_scopes; \
164+
napi_clear_last_error((env)); \
165+
call; \
166+
CHECK_EQ((env)->open_handle_scopes, open_handle_scopes); \
167+
CHECK_EQ((env)->open_callback_scopes, open_callback_scopes); \
168+
if (!(env)->last_exception.IsEmpty()) { \
169+
handle_exception( \
170+
v8::Local<v8::Value>::New((env)->isolate, (env)->last_exception)); \
171+
(env)->last_exception.Reset(); \
172+
} \
173+
} while (0)
174+
175+
#define NAPI_CALL_INTO_MODULE_THROW(env, call) \
176+
NAPI_CALL_INTO_MODULE((env), call, (env)->isolate->ThrowException)
160177

161178
namespace {
162179
namespace v8impl {
@@ -336,10 +353,11 @@ class Finalizer {
336353
static void FinalizeBufferCallback(char* data, void* hint) {
337354
Finalizer* finalizer = static_cast<Finalizer*>(hint);
338355
if (finalizer->_finalize_callback != nullptr) {
339-
finalizer->_finalize_callback(
340-
finalizer->_env,
341-
data,
342-
finalizer->_finalize_hint);
356+
NAPI_CALL_INTO_MODULE_THROW(finalizer->_env,
357+
finalizer->_finalize_callback(
358+
finalizer->_env,
359+
data,
360+
finalizer->_finalize_hint));
343361
}
344362

345363
Delete(finalizer);
@@ -441,10 +459,11 @@ class Reference : private Finalizer {
441459
bool delete_self = reference->_delete_self;
442460

443461
if (reference->_finalize_callback != nullptr) {
444-
reference->_finalize_callback(
445-
reference->_env,
446-
reference->_finalize_data,
447-
reference->_finalize_hint);
462+
NAPI_CALL_INTO_MODULE_THROW(reference->_env,
463+
reference->_finalize_callback(
464+
reference->_env,
465+
reference->_finalize_data,
466+
reference->_finalize_hint));
448467
}
449468

450469
if (delete_self) {
@@ -529,32 +548,17 @@ class CallbackWrapperBase : public CallbackWrapper {
529548
napi_callback cb = reinterpret_cast<napi_callback>(
530549
v8::Local<v8::External>::Cast(
531550
_cbdata->GetInternalField(kInternalFieldIndex))->Value());
532-
v8::Isolate* isolate = _cbinfo.GetIsolate();
533551

534552
napi_env env = static_cast<napi_env>(
535553
v8::Local<v8::External>::Cast(
536554
_cbdata->GetInternalField(kEnvIndex))->Value());
537555

538-
// Make sure any errors encountered last time we were in N-API are gone.
539-
napi_clear_last_error(env);
540-
541-
int open_handle_scopes = env->open_handle_scopes;
542-
int open_callback_scopes = env->open_callback_scopes;
543-
544-
napi_value result = cb(env, cbinfo_wrapper);
556+
napi_value result;
557+
NAPI_CALL_INTO_MODULE_THROW(env, result = cb(env, cbinfo_wrapper));
545558

546559
if (result != nullptr) {
547560
this->SetReturnValue(result);
548561
}
549-
550-
CHECK_EQ(env->open_handle_scopes, open_handle_scopes);
551-
CHECK_EQ(env->open_callback_scopes, open_callback_scopes);
552-
553-
if (!env->last_exception.IsEmpty()) {
554-
isolate->ThrowException(
555-
v8::Local<v8::Value>::New(isolate, env->last_exception));
556-
env->last_exception.Reset();
557-
}
558562
}
559563

560564
const Info& _cbinfo;
@@ -861,8 +865,10 @@ void napi_module_register_cb(v8::Local<v8::Object> exports,
861865
// one is found.
862866
napi_env env = v8impl::GetEnv(context);
863867

864-
napi_value _exports =
865-
mod->nm_register_func(env, v8impl::JsValueFromV8LocalValue(exports));
868+
napi_value _exports;
869+
NAPI_CALL_INTO_MODULE_THROW(env,
870+
_exports = mod->nm_register_func(env,
871+
v8impl::JsValueFromV8LocalValue(exports)));
866872

867873
// If register function returned a non-null exports object different from
868874
// the exports object we passed it, set that as the "exports" property of
@@ -3357,19 +3363,17 @@ class Work : public node::AsyncResource {
33573363
v8::HandleScope scope(env->isolate);
33583364
CallbackScope callback_scope(work);
33593365

3360-
work->_complete(env, ConvertUVErrorCode(status), work->_data);
3366+
NAPI_CALL_INTO_MODULE(env,
3367+
work->_complete(env, ConvertUVErrorCode(status), work->_data),
3368+
[env] (v8::Local<v8::Value> local_err) {
3369+
// If there was an unhandled exception in the complete callback,
3370+
// report it as a fatal exception. (There is no JavaScript on the
3371+
// callstack that can possibly handle it.)
3372+
v8impl::trigger_fatal_exception(env, local_err);
3373+
});
33613374

33623375
// Note: Don't access `work` after this point because it was
33633376
// likely deleted by the complete callback.
3364-
3365-
// If there was an unhandled exception in the complete callback,
3366-
// report it as a fatal exception. (There is no JavaScript on the
3367-
// callstack that can possibly handle it.)
3368-
if (!env->last_exception.IsEmpty()) {
3369-
v8::Local<v8::Value> local_err = v8::Local<v8::Value>::New(
3370-
env->isolate, env->last_exception);
3371-
v8impl::trigger_fatal_exception(env, local_err);
3372-
}
33733377
}
33743378
}
33753379

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)