[napi_v8] Defer napi_finalize callbacks outside V8 GC pause Node-API napi_finalize callbacks receive a napi_env and are permitted to allocate JavaScript objects and call into the engine, which V8 forbids during its synchronous weak handle callbacks. Match Node.js by queuing collected references in WeakCallback, scheduling a batch drain onto globalThis.setImmediate in PostGarbageCollectionCallback, and invoking the finalizers from the event loop. Bug: 555264246 Change-Id: I83496ceb96a82f0fe581d682e71d99fa56647380 Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/341795 Reviewed-by: James Price <jrprice@google.com> Commit-Queue: Steven Perron <stevenperron@google.com>
diff --git a/src/dawn/node/napi_v8/napi_v8.cpp b/src/dawn/node/napi_v8/napi_v8.cpp index e6ff904..b336e65 100644 --- a/src/dawn/node/napi_v8/napi_v8.cpp +++ b/src/dawn/node/napi_v8/napi_v8.cpp
@@ -28,6 +28,7 @@ #include "src/dawn/node/napi_v8/napi_v8.h" #include <algorithm> +#include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> @@ -77,6 +78,9 @@ } napi_ref__::~napi_ref__() { + if (env != nullptr) { + std::erase(env->pending_finalizers, this); + } handle.Reset(); } @@ -88,25 +92,113 @@ handle.ClearWeak<void>(); } +void napi_env__::DrainFinalizers() { + while (!pending_finalizers.empty()) { + napi_ref__* ref = pending_finalizers.front(); + pending_finalizers.erase(pending_finalizers.begin()); + if (ref->finalize_cb == nullptr) { + continue; + } + + napi_finalize cb = ref->finalize_cb; + void* native_object = ref->native_object; + void* finalize_hint = ref->finalize_hint; + ref->finalize_cb = nullptr; + + ClearLastError(); + cb(this, native_object, finalize_hint); + if (DeliverPendingException(this)) { + break; + } + } +} + +namespace { + +void DrainFinalizersV8Callback(const v8::FunctionCallbackInfo<v8::Value>& info) { + auto* env = static_cast<napi_env>( + info.Data().As<v8::External>()->Value(v8::kExternalPointerTypeTagDefault)); + env->finalizer_drain_scheduled = false; + env->DrainFinalizers(); +} + +} // namespace + +// Node-API `napi_finalize` callbacks (https://nodejs.org/api/n-api.html#napi_finalize) receive a +// `napi_env` and are permitted to allocate JavaScript objects and call into the engine. However, +// V8's weak handle callback (`v8::PersistentBase::SetWeak`, +// https://chromium.googlesource.com/v8/v8/+/refs/heads/main/include/v8-persistent-handle.h) runs +// synchronously inside V8's atomic garbage collection pause while the heap is being swept. As +// documented on `v8::WeakCallbackInfo::SetSecondPassCallback` +// (https://chromium.googlesource.com/v8/v8/+/refs/heads/main/include/v8-weak-callback-info.h), the +// initial callback passed to `SetWeak` must call `Reset()` on the weak handle and is prohibited +// from making any other V8 API calls or allocating on the heap; any further work must be deferred +// via `SetSecondPassCallback()`. +// +// Finalization therefore runs in three stages: +// 1. `WeakCallback` (during the GC atomic pause): resets `self->handle`, appends `self` to +// `env->pending_finalizers`, and registers `PostGarbageCollectionCallback` via +// `SetSecondPassCallback()` once per GC cycle. +// 2. `PostGarbageCollectionCallback` (after the GC pause finishes): runs once V8's heap is +// consistent again (`AllowGarbageCollection`). It schedules a single +// `DrainFinalizersV8Callback` task onto `globalThis.setImmediate` (matching Node.js's +// `v8impl::Reference::WeakCallback` -> `SetImmediate` ordering so finalizers run in the event +// loop's check phase rather than inside `Heap::CollectGarbage()`, where V8 prohibits +// arbitrary JavaScript execution). +// 3. `DrainFinalizers` (on the event loop): invokes each queued `napi_finalize` callback in FIFO +// order. void napi_ref__::WeakCallback(const v8::WeakCallbackInfo<napi_ref__>& data) { napi_ref__* self = data.GetParameter(); - napi_env env = self->env; - void* native_object = self->native_object; - void* finalize_hint = self->finalize_hint; - napi_finalize finalize_cb = self->finalize_cb; - - // Reset the handle and clear finalize_cb before invoking the callback. - // The finalize_cb may call napi_delete_reference, which deletes `self`. self->handle.Reset(); - self->finalize_cb = nullptr; - - if (finalize_cb != nullptr) { - env->ClearLastError(); - finalize_cb(env, native_object, finalize_hint); - DeliverPendingException(env); + if (self->finalize_cb != nullptr) { + napi_env env = self->env; + env->pending_finalizers.push_back(self); + if (!env->post_gc_callback_scheduled && !env->finalizer_drain_scheduled) { + env->post_gc_callback_scheduled = true; + data.SetSecondPassCallback(&napi_ref__::PostGarbageCollectionCallback); + } } } +// Invoked by V8 (`GlobalHandles::InvokeSecondPassPhantomCallbacks`) after the garbage collection +// cycle completes (`Heap::NOT_IN_GC`), when V8 heap allocations are permitted again. Schedules +// `DrainFinalizers` onto `globalThis.setImmediate`. +void napi_ref__::PostGarbageCollectionCallback(const v8::WeakCallbackInfo<napi_ref__>& data) { + napi_env env = data.GetParameter()->env; + env->post_gc_callback_scheduled = false; + if (env->pending_finalizers.empty() || env->finalizer_drain_scheduled) { + return; + } + + // V8 lifts `DisallowGarbageCollection` before invoking second-pass callbacks, but leaves + // `DisallowJavascriptExecution` active on the isolate; re-enable JS execution so we can call + // `globalThis.setImmediate` to enqueue `DrainFinalizersV8Callback`. + v8::Isolate::AllowJavascriptExecutionScope allow_js(env->isolate); + v8::HandleScope handle_scope(env->isolate); + v8::Local<v8::Context> ctx = env->GetContext(); + v8::Context::Scope context_scope(ctx); + + // `napi_v8` does not depend on `standalone::EventLoop`, so it schedules the batch drain once + // per GC cycle through `globalThis.setImmediate`, and then drains all queued references in C++ + // inside `DrainFinalizers()`. + v8::Local<v8::String> key = v8::String::NewFromUtf8Literal(env->isolate, "setImmediate"); + v8::Local<v8::Value> set_immediate_val; + [[maybe_unused]] bool has_set_immediate = + ctx->Global()->Get(ctx, key).ToLocal(&set_immediate_val) && set_immediate_val->IsFunction(); + assert(has_set_immediate); + + v8::Local<v8::External> ext = + v8::External::New(env->isolate, env, v8::kExternalPointerTypeTagDefault); + v8::Local<v8::Function> drain_fn; + [[maybe_unused]] bool has_drain_fn = + v8::Function::New(ctx, DrainFinalizersV8Callback, ext).ToLocal(&drain_fn); + assert(has_drain_fn); + + env->finalizer_drain_scheduled = true; + v8::Local<v8::Value> arg = drain_fn; + (void)set_immediate_val.As<v8::Function>()->Call(ctx, ctx->Global(), 1, &arg); +} + namespace { // Validates that the environment pointer and all required argument pointers are non-null.
diff --git a/src/dawn/node/napi_v8/napi_v8.h b/src/dawn/node/napi_v8/napi_v8.h index b2e3300..1c30c70 100644 --- a/src/dawn/node/napi_v8/napi_v8.h +++ b/src/dawn/node/napi_v8/napi_v8.h
@@ -117,6 +117,7 @@ void ClearWeak(); static void WeakCallback(const v8::WeakCallbackInfo<napi_ref__>& data); + static void PostGarbageCollectionCallback(const v8::WeakCallbackInfo<napi_ref__>& data); }; // Internal struct representing a Node-API deferred promise (napi_deferred) @@ -149,6 +150,12 @@ // preserving insertion order so ~napi_env__ can finalize references in reverse creation order. absl::linked_hash_map<napi_ref__*, std::unique_ptr<napi_ref__>> references; + // References collected by V8 GC whose `napi_finalize` callbacks are waiting to run outside the + // GC atomic pause. + std::vector<napi_ref__*> pending_finalizers; + bool post_gc_callback_scheduled = false; + bool finalizer_drain_scheduled = false; + std::vector<std::unique_ptr<napi_deferred__>> deferreds; InstanceData instance_data{}; @@ -157,6 +164,8 @@ // invisible to JavaScript, so it cannot be observed, enumerated or tampered with by scripts. v8::Global<v8::Private> wrapper_key; + void DrainFinalizers(); + napi_env__(v8::Isolate* iso, v8::Local<v8::Context> ctx) : isolate(iso), context(iso, ctx) { ClearLastError(); }
diff --git a/src/dawn/node/test/NapiV8Test.cpp b/src/dawn/node/test/NapiV8Test.cpp index a0daf54..61db6c8 100644 --- a/src/dawn/node/test/NapiV8Test.cpp +++ b/src/dawn/node/test/NapiV8Test.cpp
@@ -56,6 +56,15 @@ void SetUp() override { V8IsolateTest::SetUp(); env_ = dawn::napi_v8::CreateEnv(isolate_, context()); + napi_value setup_script = nullptr; + ASSERT_EQ(napi_create_string_utf8( + env_, + "globalThis._immediateQueue = [];" + "globalThis.setImmediate = (fn) => { globalThis._immediateQueue.push(fn); };", + NAPI_AUTO_LENGTH, &setup_script), + napi_ok); + napi_value unused = nullptr; + ASSERT_EQ(napi_run_script(env_, setup_script, &unused), napi_ok); } void TearDown() override { @@ -69,8 +78,21 @@ void DestroySubEnv(napi_env sub_env) { dawn::napi_v8::DestroyEnv(sub_env); } + void DrainImmediates() { + napi_value drain_script = nullptr; + ASSERT_EQ(napi_create_string_utf8(env_, + "while (globalThis._immediateQueue.length > 0) {" + " globalThis._immediateQueue.shift()();" + "}", + NAPI_AUTO_LENGTH, &drain_script), + napi_ok); + napi_value unused = nullptr; + ASSERT_EQ(napi_run_script(env_, drain_script, &unused), napi_ok); + } + void RequestGC() { isolate_->RequestGarbageCollectionForTesting(v8::Isolate::kFullGarbageCollection); + DrainImmediates(); } // Executes pending JavaScript microtasks (such as Promise .then() / .catch() callbacks). @@ -3369,4 +3391,79 @@ EXPECT_EQ(unwrapped, &real); } +void AllocateJsObjectInFinalizer(napi_env env, void* finalize_data, void*) { + auto* ran = static_cast<bool*>(finalize_data); + napi_handle_scope scope = nullptr; + ASSERT_EQ(napi_open_handle_scope(env, &scope), napi_ok); + + napi_value obj = nullptr; + ASSERT_EQ(napi_create_object(env, &obj), napi_ok); + napi_value marker = nullptr; + ASSERT_EQ(napi_create_string_utf8(env, "allocated-in-finalizer", NAPI_AUTO_LENGTH, &marker), + napi_ok); + ASSERT_EQ(napi_set_named_property(env, obj, "status", marker), napi_ok); + + napi_value global = nullptr; + ASSERT_EQ(napi_get_global(env, &global), napi_ok); + ASSERT_EQ(napi_set_named_property(env, global, "_fromFinalizer", obj), napi_ok); + + ASSERT_EQ(napi_close_handle_scope(env, scope), napi_ok); + *ran = true; +} + +// Node-API `napi_finalize` callbacks receive a `napi_env` and are allowed to allocate JavaScript +// objects and call into V8, which requires running them outside V8's first-pass GC pause. +TEST_F(NapiV8Test, FinalizerCanAllocateJavaScriptObjects) { + bool finalized = false; + { + napi_handle_scope scope = nullptr; + ASSERT_EQ(napi_open_handle_scope(env_, &scope), napi_ok); + napi_value obj = nullptr; + ASSERT_EQ(napi_create_object(env_, &obj), napi_ok); + ASSERT_EQ(napi_add_finalizer(env_, obj, &finalized, AllocateJsObjectInFinalizer, nullptr, + nullptr), + napi_ok); + ASSERT_EQ(napi_close_handle_scope(env_, scope), napi_ok); + } + + RequestGC(); + EXPECT_TRUE(finalized); + + napi_value script = nullptr; + ASSERT_EQ(napi_create_string_utf8(env_, "globalThis._fromFinalizer.status", NAPI_AUTO_LENGTH, + &script), + napi_ok); + napi_value result = nullptr; + ASSERT_EQ(napi_run_script(env_, script, &result), napi_ok); + char buf[64] = {}; + size_t len = 0; + ASSERT_EQ(napi_get_value_string_utf8(env_, result, buf, sizeof(buf), &len), napi_ok); + EXPECT_STREQ(buf, "allocated-in-finalizer"); +} + +void RecordFinalizedFlag(napi_env, void* finalize_data, void*) { + *static_cast<bool*>(finalize_data) = true; +} + +// GC schedules `napi_finalize` callbacks onto `globalThis.setImmediate` rather than running them +// during `CollectGarbage()`. +TEST_F(NapiV8Test, FinalizerIsDeferredThroughSetImmediate) { + bool finalized = false; + { + napi_handle_scope scope = nullptr; + ASSERT_EQ(napi_open_handle_scope(env_, &scope), napi_ok); + napi_value obj = nullptr; + ASSERT_EQ(napi_create_object(env_, &obj), napi_ok); + ASSERT_EQ(napi_add_finalizer(env_, obj, &finalized, RecordFinalizedFlag, nullptr, nullptr), + napi_ok); + ASSERT_EQ(napi_close_handle_scope(env_, scope), napi_ok); + } + + isolate_->RequestGarbageCollectionForTesting(v8::Isolate::kFullGarbageCollection); + EXPECT_FALSE(finalized); + + DrainImmediates(); + EXPECT_TRUE(finalized); +} + } // namespace