Skip to content

src: detach cppgc wrappers from their Realm before it is freed - #65778

Open
codebytere wants to merge 1 commit into
nodejs:mainfrom
codebytere:fix/embedder-cppgc-wrapper-realm-lifetime
Open

src: detach cppgc wrappers from their Realm before it is freed#65778
codebytere wants to merge 1 commit into
nodejs:mainfrom
codebytere:fix/embedder-cppgc-wrapper-realm-lifetime

Conversation

@codebytere

Copy link
Copy Markdown
Member

Realm::RunCleanup() finalizes the cppgc-managed wrappers it tracks (vm.Script, contextified objects) so that none of them touches the Realm after it is gone, but it reaches them through weak persistents, and the GC clears those as soon as marking finds a wrapper dead - with lazy and concurrent sweeping that can be well before the destructor runs. A wrapper collected shortly before FreeEnvironment() and swept after it is skipped, keeps its realm_, and ~CppgcMixin() then writes should_purge_empty_cppgc_wrappers_ into the freed Realm; a subclass using the documented ~MyWrap() { Finalize(); } pattern would call Clean() with a dangling Realm the same way. A Worker that compiles a few vm.Scripts, gets a full GC from external memory pressure and calls process.exit() is enough: ASAN reports a heap-use-after-free write in ~ContextifyScript during isolate disposal.

Once the GC has found a wrapper dead only its own destructor may touch it, so the Realm cannot reach into those wrappers to clear anything. Instead the Realm pointer moves into the off-heap CppgcWrapperListNode, which the wrapper now owns and deletes in ~CppgcMixin(). CppgcWrapperList::Cleanup() pops every node, calls Finalize() on the wrappers whose weak persistent is still set, and clears the node's Realm pointer either way, so a collected wrapper's destructor sees no Realm instead of a freed one. Realm::PendingCleanup() also looks at the wrapper list so cleanup always drains it. The purge flag, its GC epilogue callback and PurgeEmpty() are no longer needed; removing them also stops the nodes of wrappers that are alive at FreeEnvironment() from leaking (they were unlinked by ~ListHead() and never freed).

Tests: CppgcTest.CleanIsNotCalledWithFreedRealm, VmScriptCollectedBeforeFreeEnvironmentSweptAfter and WrappersAliveAtFreeEnvironmentDoNotLeak in test_cppgc.cc. Under ASAN the first two fail on every run before (the second with the use-after-free above) and the third under LSAN; in a regular build the first fails before only when the sweeper has not reached the wrappers by the time FreeEnvironment() pumps the loop, about one run in three locally.

Refs: #56534


Disclosure: the code, tests and this description were written by Claude Code, directed and reviewed by @codebytere.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/realm
  • @nodejs/startup

@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Sep 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

`Realm::RunCleanup()` finalizes the cppgc-managed wrappers it tracks
so that none of them touches the Realm once it is gone, but it reaches
them through weak persistents, and the GC clears those as soon as it
finds a wrapper dead. With lazy and concurrent sweeping the destructor
can run much later, so a wrapper collected shortly before
`FreeEnvironment()` and swept after it was skipped by the cleanup and
kept its `realm_`: `~CppgcMixin()` then wrote
`should_purge_empty_cppgc_wrappers_` into the freed Realm, and a
subclass destructor calling `Finalize()` as documented would have
called `Clean()` with a dangling Realm. A Worker that compiles a few
`vm.Script`s, gets a full GC from external memory pressure and calls
`process.exit()` is enough to hit the first case.

Move the Realm pointer into the list node, which the wrapper now owns
and deletes in its destructor. `CppgcWrapperList::Cleanup()` unlinks
every node, finalizing the wrappers that are still alive and clearing
the Realm pointer for the collected ones, which only their own
destructor may still touch. `Realm::PendingCleanup()` accounts for the
list so it is always drained. The purge flag, its GC epilogue callback
and `PurgeEmpty()` are no longer needed, and removing them also stops
the list nodes of wrappers that are alive at `FreeEnvironment()` from
leaking.

Refs: nodejs#56534
Signed-off-by: Shelley Vohr <[email protected]>
@codebytere
codebytere force-pushed the fix/embedder-cppgc-wrapper-realm-lifetime branch from bbc133a to 6bb6296 Compare September 4, 2026 08:45
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@codecov

codecov Bot commented Sep 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.05%. Comparing base (2befec5) to head (6bb6296).
⚠️ Report is 54 commits behind head on main.

Files with missing lines Patch % Lines
src/cppgc_helpers-inl.h 81.81% 0 Missing and 2 partials ⚠️
src/node_realm.cc 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #65778      +/-   ##
==========================================
+ Coverage   89.99%   90.05%   +0.05%     
==========================================
  Files         757      769      +12     
  Lines      257739   261377    +3638     
  Branches    48881    49629     +748     
==========================================
+ Hits       231961   235377    +3416     
- Misses      16861    17033     +172     
- Partials     8917     8967      +50     
Files with missing lines Coverage Δ
src/cppgc_helpers.cc 64.28% <100.00%> (-27.39%) ⬇️
src/cppgc_helpers.h 60.00% <100.00%> (-33.34%) ⬇️
src/node_realm-inl.h 91.93% <100.00%> (+0.26%) ⬆️
src/node_realm.h 100.00% <ø> (ø)
src/node_realm.cc 75.47% <0.00%> (-1.18%) ⬇️
src/cppgc_helpers-inl.h 85.71% <81.81%> (-0.96%) ⬇️

... and 79 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

RSLGTM

@mcollina mcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Sep 4, 2026
@mcollina
mcollina requested a review from legendecas September 4, 2026 14:36
@github-actions github-actions Bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Sep 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants