Skip to content

Commit 8ff16fd

Browse files
legendecasruyadorno
authored andcommitted
node-api: fix immediate napi_remove_wrap test
As documented in napi_wrap section, the returned reference must be deleted with `napi_delete_reference` in response to the finalize callback, in which `napi_unwrap` and `napi_remove_wrap` is not available. When the reference needs to be deleted early, it should be deleted after the wrapped value is not accessed with `napi_unwrap` and `napi_remove_wrap` too. This test is previously added in response to duplicating the test https://github.com/nodejs/node-addon-api/blob/main/test/objectwrap_constructor_exception.cc in the node-addon-api. As Napi::ObjectWrap<> is a subclass of Napi::Reference<>, napi_remove_wrap in the destructor of Napi::ObjectWrap<> is called before napi_delete_reference in the destructor of Napi::Reference<>. PR-URL: #45406 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Michael Dawson <midawson@redhat.com>
1 parent 2b760c3 commit 8ff16fd

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

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

+8-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ static napi_value New(napi_env env, napi_callback_info info) {
4444

4545
static void NoopDeleter(napi_env env, void* data, void* hint) {}
4646

47+
// Tests that calling napi_remove_wrap and napi_delete_reference consecutively
48+
// doesn't crash the process.
49+
// This is analogous to the test https://github.com/nodejs/node-addon-api/blob/main/test/objectwrap_constructor_exception.cc.
50+
// In which the Napi::ObjectWrap<> is being destructed immediately after napi_wrap.
51+
// As Napi::ObjectWrap<> is a subclass of Napi::Reference<>, napi_remove_wrap
52+
// in the destructor of Napi::ObjectWrap<> is called before napi_delete_reference
53+
// in the destructor of Napi::Reference<>.
4754
static napi_value DeleteImmediately(napi_env env, napi_callback_info info) {
4855
size_t argc = 1;
4956
napi_value js_obj;
@@ -56,8 +63,8 @@ static napi_value DeleteImmediately(napi_env env, napi_callback_info info) {
5663
NODE_API_ASSERT(env, type == napi_object, "Expected object parameter");
5764

5865
NODE_API_CALL(env, napi_wrap(env, js_obj, NULL, NoopDeleter, NULL, &ref));
59-
NODE_API_CALL(env, napi_delete_reference(env, ref));
6066
NODE_API_CALL(env, napi_remove_wrap(env, js_obj, NULL));
67+
NODE_API_CALL(env, napi_delete_reference(env, ref));
6168

6269
return NULL;
6370
}

0 commit comments

Comments
 (0)