Skip to content

Commit 496f7ea

Browse files
mhdawsondanielleadams
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 6da4aa3 commit 496f7ea

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
@@ -39,8 +39,13 @@ struct node_napi_env__ : public napi_env__ {
3939
}
4040

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

0 commit comments

Comments
 (0)