Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash running Node-API finalizers during VM destruction #18767

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

190n
Copy link
Collaborator

@190n 190n commented Apr 4, 2025

What does this PR do?

Split off from #18758.

This will be the fix for #18139 (right now it's incomplete). The issue is that we can run Node-API finalizers after the GlobalObject is destroyed, and the GlobalObject owns the napi_envs, which means that finalizers will read a bunch of bogus data from the space taken up by the napi_env and probably crash (e.g. macOS free() memsets it to zero).

The current way I've tried to fix this is by making napi_envs owned by the ScriptExecutionContext instead of the GlobalObject. But this doesn't work because the ScriptExecutionContext is reference-counted and the GlobalObject holds the last one, so its destructor will free the ScriptExecutionContext and free the napi_envs. A solution could be to make napi_env reference counted and have a ref owned by each finalizer. Then the env just needs to detect if the GlobalObject was already freed when running a finalizer (which it'll be able to do without concern over the napi_env having been freed), and skip it (or we could try running the finalizer anyway, but it would only work if the finalizer avoids using basically any Node-API function).

How did you verify your code works?

There's a test (which currently fails since the fix is incomplete). The test also depends on BUN_DESTRUCT_VM_ON_EXIT from #18758.

@robobun
Copy link

robobun commented Apr 4, 2025

Updated 5:12 PM PT - Apr 7th, 2025

@190n, your commit 1fb9a72 has some failures in Build #14605


🧪   try this PR locally:

bunx bun-pr 18767

@190n 190n changed the title Ben/finalizer destruct crash Fix crash running Node-API finalizers during VM destruction Apr 4, 2025
@190n 190n mentioned this pull request Apr 4, 2025
4 tasks
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.

2 participants