Skip to content

Commit 6a8d457

Browse files
committed
node-api: avoid TSFN mutex reentry during teardown
ThreadSafeFunction releases its Node-API environment reference while finalizing its loop-owned resources. That operation can synchronously invoke an external finalizer, which may release a still-valid TSFN ownership. Do not hold the TSFN mutex across this reentrant path. Use an intermediate resource-cleanup state to retain the TSFN until resource cleanup completes, then permit the loop or final native owner to destroy it. Fixes: nodejs#65100 Signed-off-by: Jimmy Miller <[email protected]> Assisted-by: OpenCode
1 parent fd6682c commit 6a8d457

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

‎src/node_api.cc‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ class ThreadSafeFunction {
218218
node::Utf8Value(env_->isolate, name).ToStringView()),
219219
thread_count(thread_count_),
220220
state(kOpen),
221+
resources_released(false),
221222
dispatch_state(kDispatchIdle),
222223
context(context_),
223224
max_queue_size(max_queue_size_),
@@ -320,17 +321,22 @@ class ThreadSafeFunction {
320321
}
321322

322323
void MaybeDelete() {
324+
bool delete_this;
323325
{
324326
node::Mutex::ScopedLock lock(this->mutex);
325-
if (thread_count > 0) {
326-
// At this point this TSFN is effectively done, but we need to keep
327-
// it alive for other threads that still have pointers to it until
328-
// they release them.
329-
// But we already release all the resources that we can at this point
330-
ReleaseResources();
331-
return;
332-
}
327+
state = kResourceCleanup;
328+
}
329+
330+
ReleaseResources();
331+
332+
{
333+
node::Mutex::ScopedLock lock(this->mutex);
334+
state = kClosed;
335+
delete_this = thread_count == 0;
333336
}
337+
338+
if (!delete_this) return;
339+
334340
// Make sure to release lock before destroying
335341
delete this;
336342
}
@@ -384,8 +390,8 @@ class ThreadSafeFunction {
384390

385391
protected:
386392
void ReleaseResources() {
387-
if (state != kClosed) {
388-
state = kClosed;
393+
if (!resources_released) {
394+
resources_released = true;
389395
ref.Reset();
390396
node::RemoveEnvironmentCleanupHook(env->isolate, Cleanup, this);
391397
env->Unref();
@@ -553,7 +559,7 @@ class ThreadSafeFunction {
553559
using node::AsyncResource::CallbackScope;
554560
};
555561

556-
enum State : unsigned char { kOpen, kClosing, kClosed };
562+
enum State : unsigned char { kOpen, kClosing, kResourceCleanup, kClosed };
557563

558564
static const unsigned char kDispatchIdle = 0;
559565
static const unsigned char kDispatchRunning = 1 << 0;
@@ -570,6 +576,8 @@ class ThreadSafeFunction {
570576
uv_async_t async;
571577
size_t thread_count;
572578
State state;
579+
580+
bool resources_released;
573581
std::atomic_uchar dispatch_state;
574582

575583
// These are variables set once, upon creation, and then never again, which

0 commit comments

Comments
 (0)