node-api: stop ref gc during environment teardown · nodejs/node@d1a3e0e · GitHub
Skip to content

Commit d1a3e0e

Browse files
gabrielschulhofruyadorno
authored andcommitted
node-api: stop ref gc during environment teardown
A gc may happen during environment teardown. Thus, during finalization initiated by environment teardown we must remove the V8 finalizer before calling the Node-API finalizer. Fixes: #37236 PR-URL: #37616 Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: Michael Dawson <midawson@redhat.com>
1 parent bfe3f21 commit d1a3e0e

4 files changed

Lines changed: 86 additions & 1 deletion

File tree

src/js_native_api_v8.cc

Lines changed: 27 additions & 1 deletion
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include <stdlib.h>
2+
#include <node_api.h>
3+
#include "../../js-native-api/common.h"
4+
5+
static void MyObject_fini(napi_env env, void* data, void* hint) {
6+
napi_ref* ref = data;
7+
napi_value global;
8+
napi_value cleanup;
9+
NODE_API_CALL_RETURN_VOID(env, napi_get_global(env, &global));
10+
NODE_API_CALL_RETURN_VOID(
11+
env, napi_get_named_property(env, global, "cleanup", &cleanup));
12+
napi_status status = napi_call_function(env, global, cleanup, 0, NULL, NULL);
13+
// We may not be allowed to call into JS, in which case a pending exception
14+
// will be returned.
15+
NODE_API_ASSERT_RETURN_VOID(env,
16+
status == napi_ok || status == napi_pending_exception,
17+
"Unexpected status for napi_call_function");
18+
NODE_API_CALL_RETURN_VOID(env, napi_delete_reference(env, *ref));
19+
free(ref);
20+
}
21+
22+
static napi_value MyObject(napi_env env, napi_callback_info info) {
23+
napi_value js_this;
24+
napi_ref* ref = malloc(sizeof(*ref));
25+
NODE_API_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &js_this, NULL));
26+
NODE_API_CALL(env, napi_wrap(env, js_this, ref, MyObject_fini, NULL, ref));
27+
return NULL;
28+
}
29+
30+
NAPI_MODULE_INIT() {
31+
napi_value ctor;
32+
NODE_API_CALL(
33+
env, napi_define_class(
34+
env, "MyObject", NAPI_AUTO_LENGTH, MyObject, NULL, 0, NULL, &ctor));
35+
NODE_API_CALL(env, napi_set_named_property(env, exports, "MyObject", ctor));
36+
return exports;
37+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
'targets': [
3+
{
4+
'target_name': 'binding',
5+
'sources': [ 'binding.c' ]
6+
}
7+
]
8+
}
Lines changed: 14 additions & 0 deletions

0 commit comments

Comments
 (0)