Skip to content

fix(ext/napi): pass valid env to tsfn call_js_cb after close race - #32957

Merged
bartlomieju merged 3 commits into
denoland:mainfrom
bartlomieju:fix/napi-tsfn-null-env
Mar 24, 2026
Merged

bartlomieju merged 3 commits into
denoland:mainfrom
bartlomieju:fix/napi-tsfn-null-env

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fix SIGSEGV crash in native addons (e.g. node-pty) caused by a race condition in NAPI threadsafe function teardown
  • When a tsfn is released while calls are still pending, TsFn::drop can run before a queued call is processed. Previously, the call_js_cb was invoked with env=NULL, crashing addons that dereference env without a null check (SIGSEGV at address 0x90)
  • Fix captures the env pointer in the call closure so it's available after the TsFn is freed. The env is always valid (leaked via Box::into_raw, never freed) and V8 is alive (callback runs on V8 thread)
  • Add regression test test_tsfn_close_race that spawns concurrent calling/releasing threads to exercise the race

Towards #32846

bartlomieju and others added 2 commits March 24, 2026 18:50
When a NAPI threadsafe function is released while calls are still
pending, there is a race where TsFn::drop runs before a queued call
is processed. Previously, the call_js_cb was invoked with env=NULL
in this case, causing native addons like node-pty to SIGSEGV when
they dereference env without a null check (crash at address 0x90).

Fix: capture the env pointer in the call closure so it remains
available after the TsFn is freed. The env is always valid because
it is leaked via Box::into_raw in op_napi_open and never freed.
V8 is also alive since the callback runs on the V8 thread.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add test_tsfn_abort_race that exercises the same close-race scenario
as test_tsfn_close_race but using napi_tsfn_abort mode. Abort forces
immediate close regardless of thread_count, which is another path
to the is_closed=true state that previously passed null env.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@bartlomieju bartlomieju left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove em-dashes

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@bartlomieju
bartlomieju merged commit 802a788 into denoland:main Mar 24, 2026
111 checks passed
@bartlomieju
bartlomieju deleted the fix/napi-tsfn-null-env branch March 24, 2026 21:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant