Skip to content

Commit 8ccd867

Browse files
mhdawsontargos
authored andcommitted
node-api: fix shutdown crashes
Refs: nodejs/node-addon-api#906 Ensure that finalization is not defered during shutdown. The env for the addon is deleted immediately after iterating the list of finalizers to be run. Defering causes crashes as the finalization uses the already deleted env. Signed-off-by: Michael Dawson <[email protected]> PR-URL: #38492 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Chengzhong Wu <[email protected]> Reviewed-By: Gabriel Schulhof <[email protected]>
1 parent daa1a16 commit 8ccd867

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/js_native_api_v8.h

+31
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,37 @@ struct napi_env__ {
122122
void* instance_data = nullptr;
123123
};
124124

125+
// This class is used to keep a napi_env live in a way that
126+
// is exception safe versus calling Ref/Unref directly
127+
class EnvRefHolder {
128+
public:
129+
explicit EnvRefHolder(napi_env env) : _env(env) {
130+
_env->Ref();
131+
}
132+
133+
explicit EnvRefHolder(const EnvRefHolder& other): _env(other.env()) {
134+
_env->Ref();
135+
}
136+
137+
EnvRefHolder(EnvRefHolder&& other) {
138+
_env = other._env;
139+
other._env = nullptr;
140+
}
141+
142+
~EnvRefHolder() {
143+
if (_env != nullptr) {
144+
_env->Unref();
145+
}
146+
}
147+
148+
napi_env env(void) const {
149+
return _env;
150+
}
151+
152+
private:
153+
napi_env _env;
154+
};
155+
125156
static inline napi_status napi_clear_last_error(napi_env env) {
126157
env->last_error.error_code = napi_ok;
127158

src/node_api.cc

+7-2
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,13 @@ struct node_napi_env__ : public napi_env__ {
3737
}
3838

3939
void CallFinalizer(napi_finalize cb, void* data, void* hint) override {
40-
napi_env env = static_cast<napi_env>(this);
41-
node_env()->SetImmediate([=](node::Environment* node_env) {
40+
// we need to keep the env live until the finalizer has been run
41+
// EnvRefHolder provides an exception safe wrapper to Ref and then
42+
// Unref once the lamba is freed
43+
EnvRefHolder liveEnv(static_cast<napi_env>(this));
44+
node_env()->SetImmediate([=, liveEnv = std::move(liveEnv)]
45+
(node::Environment* node_env) {
46+
napi_env env = liveEnv.env();
4247
v8::HandleScope handle_scope(env->isolate);
4348
v8::Context::Scope context_scope(env->context());
4449
env->CallIntoModule([&](napi_env env) {

0 commit comments

Comments
 (0)