Skip to content

Commit a7224c9

Browse files
mhdawsonrichardlau
authored andcommittedMar 30, 2022
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 <mdawson@devrus.com> PR-URL: #38492 Backport-PR-URL: #42512 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: Gabriel Schulhof <gabrielschulhof@gmail.com>
1 parent e707514 commit a7224c9

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
@@ -35,8 +35,13 @@ struct node_napi_env__ : public napi_env__ {
3535
}
3636

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

0 commit comments

Comments
 (0)
Please sign in to comment.