Fix crash running Node-API finalizers during VM destruction #18767
+75
−25
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
GlobalObjectis destroyed, and theGlobalObjectowns thenapi_envs, which means that finalizers will read a bunch of bogus data from the space taken up by thenapi_envand 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 theScriptExecutionContextinstead of theGlobalObject. But this doesn't work because theScriptExecutionContextis reference-counted and theGlobalObjectholds the last one, so its destructor will free theScriptExecutionContextand free thenapi_envs. A solution could be to makenapi_envreference counted and have a ref owned by each finalizer. Then the env just needs to detect if theGlobalObjectwas already freed when running a finalizer (which it'll be able to do without concern over thenapi_envhaving 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_EXITfrom #18758.