Fix crash running Node-API finalizers during VM destruction #18767
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 theGlobalObject
owns thenapi_env
s, which means that finalizers will read a bunch of bogus data from the space taken up by thenapi_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_env
s owned by theScriptExecutionContext
instead of theGlobalObject
. But this doesn't work because theScriptExecutionContext
is reference-counted and theGlobalObject
holds the last one, so its destructor will free theScriptExecutionContext
and free thenapi_env
s. A solution could be to makenapi_env
reference counted and have a ref owned by each finalizer. Then the env just needs to detect if theGlobalObject
was already freed when running a finalizer (which it'll be able to do without concern over thenapi_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.