From c4407487795f6e0eac0a399181d71d541a7a2b8f Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 7 Aug 2020 12:48:45 +0200 Subject: [PATCH] n-api: fix use-after-free with napi_remove_async_cleanup_hook Fixes: https://github.com/nodejs/node/issues/34657 Refs: https://github.com/nodejs/node/pull/34572 PR-URL: https://github.com/nodejs/node/pull/34662 Reviewed-By: Gabriel Schulhof Reviewed-By: James M Snell --- src/node_api.cc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/node_api.cc b/src/node_api.cc index f57e879314733f..42d40c1b35de9f 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -533,6 +533,7 @@ napi_status napi_add_async_cleanup_hook( auto handle = node::AddEnvironmentCleanupHook(env->isolate, fun, arg); if (remove_handle != nullptr) { *remove_handle = new napi_async_cleanup_hook_handle__ { std::move(handle) }; + env->Ref(); } return napi_clear_last_error(env); @@ -547,6 +548,11 @@ napi_status napi_remove_async_cleanup_hook( node::RemoveEnvironmentCleanupHook(std::move(remove_handle->handle)); delete remove_handle; + // Release the `env` handle asynchronously since it would be surprising if + // a call to a N-API function would destroy `env` synchronously. + static_cast(env)->node_env() + ->SetImmediate([env](node::Environment*) { env->Unref(); }); + return napi_clear_last_error(env); }