Skip to content

Commit fbd411d

Browse files
committed
n-api: fix use-after-free with napi_remove_async_cleanup_hook
Fixes: #34657 Refs: #34572 PR-URL: #34662 Reviewed-By: Gabriel Schulhof <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 6502489 commit fbd411d

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

src/node_api.cc

+6
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,7 @@ napi_status napi_add_async_cleanup_hook(
533533
auto handle = node::AddEnvironmentCleanupHook(env->isolate, fun, arg);
534534
if (remove_handle != nullptr) {
535535
*remove_handle = new napi_async_cleanup_hook_handle__ { std::move(handle) };
536+
env->Ref();
536537
}
537538

538539
return napi_clear_last_error(env);
@@ -547,6 +548,11 @@ napi_status napi_remove_async_cleanup_hook(
547548
node::RemoveEnvironmentCleanupHook(std::move(remove_handle->handle));
548549
delete remove_handle;
549550

551+
// Release the `env` handle asynchronously since it would be surprising if
552+
// a call to a N-API function would destroy `env` synchronously.
553+
static_cast<node_napi_env>(env)->node_env()
554+
->SetImmediate([env](node::Environment*) { env->Unref(); });
555+
550556
return napi_clear_last_error(env);
551557
}
552558

0 commit comments

Comments
 (0)