Skip to content

Free GC handles in cooperative mode: the easy cases - #138085

Merged
jkotas merged 2 commits into
dotnet:mainfrom
pcshrosbree:fix/gc-handles-coop-easy-cases
Nov 23, 2026
Merged

jkotas merged 2 commits into
dotnet:mainfrom
pcshrosbree:fix/gc-handles-coop-easy-cases

Conversation

@pcshrosbree

Copy link
Copy Markdown
Contributor

TL;DR: Some CoreCLR code frees GC handles to live objects in preemptive mode, so a compacting GC can write a relocated reference into a handle that was just freed. This PR makes four functions, ~CEEInfo among them, free their handles in cooperative mode, and tightens the mode contracts of two others. In the repro from #117138, on a Checked runtime, 223 of 500 runs asserted before the ~CEEInfo change and 0 of 500 after it. These are the easy cases asked for in #117138, so this PR contributes to that issue but does not fix it.

DestroyHandle is MODE_ANY, so it can run while the GC is relocating. As @jkotas explained in #117138 (comment), the GC can read the handle, the free can clear it, and the GC can then write the relocated reference back. The freed handle is left pointing at a live object. Checked runtimes assert when the free cache returns the slot to its block (HndIsNullOrDestroyedHandle(...) in BlockFreeHandlesInMask) or hands it out again (*(_UNCHECKED_OBJECTREF *)handle == NULL in HndCreateHandle). Release runtimes can keep the object alive longer than they should.

@jkotas asked for "a PR that handles the easy cases (just add GCX_COOP call, or fixup the contracts)" (#117138 (comment)). This is that PR. I went through all 50 places where CoreCLR at 8fef9c3 destroys a GC handle. The changes below are the ones where the freeing thread has a Thread and holds no lock that makes the switch unsafe.

Changes

  • ~CEEInfo (first commit) frees the handles that getJitHandleForObject creates for objects outside the frozen heap that the JIT asks about. An example is a static readonly array whose length the JIT folds. The destructor now switches to cooperative mode around the loop that frees them, but only if its handle list was ever allocated. The contract, which covers every instance, changes from LIMITED_METHOD_CONTRACT to NOTHROW/GC_TRIGGERS/MODE_ANY, in response to Delete GC handles in COOP mode #125350 (comment).
  • UMEntryThunkData::Terminate: GCX_COOP() inside if (pObjectHandle != NULL), and the contract gains GC_TRIGGERS. Its only caller, FreeUMEntryThunk, is already GC_TRIGGERS. The racy path is in COMDelegate::ConvertToCallback: when another thread installs a thunk first, the losing thread frees its own thunk under GCX_PREEMP. That thunk holds a long weak handle to the live delegate.
  • CustomAssemblyBinder::ReleaseLoadContext: GCX_COOP() before its two frees. Only LoaderAllocator::GCLoaderAllocators reaches this function, through AssemblyLoaderAllocator::ReleaseAssemblyLoadContext. GCLoaderAllocators runs in preemptive mode. The strong handle keeps the load context alive. The switch stays inside this function because the next call in GCLoaderAllocators' loop, CleanupDependentHandlesToNativeObjects, is MODE_PREEMPTIVE.
  • AssemblyLoaderAllocator::CleanupHandles: GCX_COOP() at function scope, before the loop that frees the handles. The function's existing switch sits inside #ifdef FEATURE_MULTITHREADING and an if. The caller already switches modes while holding the same lock, a normal Crst.
  • SyncBlockCache::DeleteSyncBlock and EnCSyncBlockInfo::Cleanup: MODE_ANY becomes MODE_COOPERATIVE. Their only callers, CleanupSyncBlocks on the finalizer thread and DeleteSyncBlock respectively, run in cooperative mode.

The ~CEEInfo change is @EgorBo's, from #125350, and he confirmed it fixes the repro (#117138 (comment)). Egor, would you like a Co-authored-by credit on the commit? I'll add it if so. #125350 was closed for inactivity. It also changed Terminate (in a different way), ReleaseLoadContext and the two contracts, but not CleanupHandles. Its other changes are not included, among them:

  • the MODE_COOPERATIVE contract on DestroyHandleCommon;
  • the GC interface change with a locked DestroyHandleInPreemptiveMode;
  • the Thread handle cleanup.

LCGMethodResolver::DestroyResolver, which #125350 also changed, is left alone. The managed finalizer calls Destroy only after GetResolver returns null, so this handle already holds NULL when it is freed and the GC has nothing to write back into it.

Not in this PR

Among the sites that cannot simply call GCX_COOP() are:

  • CLRException cleanup can occur when leaving an EX_CATCH, including in preemptive QCall frames. It also runs from ~Thread after the current thread is cleared. It stays racy.
  • Thread::~Thread can run with no current Thread, or under the ThreadStore lock.
  • ComWrappers and built-in COM interop: InteropLibImports::DestroyHandle and ComCallWrapper::ClearHandle are reached from a native Release, on a thread that may have no Thread.
  • The profiler's ProfToEEInterfaceImpl::DestroyHandle is an asynchronous entry point that does not require a Thread.
  • The debugger frees handles for DB_IPCE_DISPOSE_HANDLE and in UpdateForceCatchHandlerFoundTable on its helper thread, which normally has no Thread.

Testing

Apart from the Windows contract checks below, all runs are on osx-arm64, with a Checked runtime built from main at 8fef9c3. There are three builds: without either commit, with the first commit, and with both.

without either commit with the first commit
the repro from #117138, DOTNET_TieredCompilation=0, DOTNET_GCHeapHardLimit=0x1000000 223 of 500 runs assert 0 of 500
new test Regressions/coreclr/GitHub_117138 20 of 30 runs assert 0 of 30
the same test under DOTNET_GCStress=0xC, DOTNET_ReadyToRun=0 (about 2.4 s per run) 2 of 20 runs assert 0 of 20

The issue's DOTNET_GCHeapHardLimit=0x100000 fails GC initialization on this machine, so the repro used 0x1000000. The test needs no heap limit.

For the second commit, I wrote probes (not part of this PR) that marshal delegates, collect them, unload collectible load contexts and churn sync blocks. On the build with both commits, lldb counted calls on the paths below. Where this PR adds GCX_COOP, lldb read the GC mode that the GCX_COOP holder saved before switching. Elsewhere, it read the thread's current GC mode.

lldb counts: the race-loser, ReleaseLoadContext and CleanupHandles frees arrived in preemptive mode
free in calls mode on arrival
Terminate, race-loser path 98 preemptive, all 98
Terminate, finalizer path 300 cooperative
ReleaseLoadContext 10 preemptive
CleanupHandles 10 preemptive
DeleteSyncBlock (sync probe) 2,001 cooperative, all 2,001
EnCSyncBlockInfo::Cleanup 0 not reached (needs Edit and Continue)

Probe runs. With both commits, the five probe configurations ran 1,250 times (1,000 plain, 250 under DOTNET_GCStress=0xC) with no assert. The same runs on the base runtime gave one HndCreateHandle assert, in the sync probe. In another 1,000 sync-probe runs, the base runtime asserted 3 times, while the first commit alone and both commits asserted 0 times. That points to the ~CEEInfo handles.

No probe asserted on the base runtime on the race-loser or load-context paths: these runs show the new code runs there without asserting, not that the old code failed.

Regression checks with both commits. The repro passed 200 of 200 runs and GitHub_117138 30 of 30. In the merged Regressions runner, 99 tests passed and three failed: GitHub_102887, GitHub_117393 and GitHub_132581. Those three fail without asserts on all three builds because their native libraries were not built locally.

Contracts. CoreCLR compiles contracts out on Unix and on ARM and ARM64 (eng/native/configurecompiler.cmake), so none of the runs above checked the new contracts. No run reached EnCSyncBlockInfo::Cleanup, so I checked its contract only by reading its one caller. I checked the other contracts on Windows:

  • win-arm64, Checked, with contracts turned on locally (the ARM64 add_definitions(-DDISABLE_CONTRACTS) line removed; not part of this PR). Each probe ran 50 times plain and 20 times under DOTNET_GCStress=0xC, the repro 50 times and GitHub_117138 10 times. There were no contract violations or asserts. As a control, I changed DeleteSyncBlock's contract to MODE_PREEMPTIVE: the sync probe then failed 5 of 5 runs with CONTRACT VIOLATION by SyncBlockCache::DeleteSyncBlock ("MODE_PREEMPTIVE encountered while thread is in cooperative state").
  • win-x64, Checked, contracts on as the repository builds them. The same runs as on win-arm64 gave no contract violations or asserts, and the same control failed 5 of 5 runs with the same violation.

I have not run this on other platforms or across the CI stress legs.

Test

Regressions/coreclr/GitHub_117138 gives its compile loop 2 seconds; a whole run took about 3 seconds on win-x64. It repeatedly compiles a method of a generic class that reads the lengths of 32 static readonly arrays, with a new value-type instantiation each time. The instantiations nest two wrapper structs at most 30 deep. Meanwhile, one thread forces compacting collections and another allocates arrays of varied sizes. The test sets DOTNET_TieredCompilation=0 so that the JIT folds the lengths. Only Debug and Checked runtimes detect the race. A helper allocates the arrays, so that the last one cannot go on the frozen heap, where the JIT needs no handle. The test is CLRTestPriority 1, sets RequiresProcessIsolation, and is excluded on Mono, wasm and NativeAOT. If a timed stress test is unwanted in the tree, I can drop it.

Note

This PR was prepared with AI assistance (Anthropic Claude) at my request. I reviewed the change, the test and the measurements before opening it.

~CEEInfo freed the handles the JIT took during a compilation in preemptive
mode, so a compacting GC could store a relocated reference into a handle
that had just been freed. Free them in cooperative mode.

Contributes to dotnet#117138
UMEntryThunkData::Terminate, CustomAssemblyBinder::ReleaseLoadContext and
AssemblyLoaderAllocator::CleanupHandles could free a handle to a live object
while the thread was in preemptive mode, the same race as in ~CEEInfo.
Switch to cooperative mode around the frees.

SyncBlockCache::DeleteSyncBlock and EnCSyncBlockInfo::Cleanup are only
called in cooperative mode; say so in their contracts.

Contributes to dotnet#117138
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 21, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @agocke
See info in area-owners.md if you want to be subscribed.

@jkotas

jkotas commented Nov 23, 2026

Copy link
Copy Markdown
Member

/azp run runtime-coreclr outerloop

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the scoped cooperative-mode GC-handle cleanup changes.

No open issues 🎉

What changed in this PR

This PR addresses selected CoreCLR GC-handle cleanup races from #117138 by freeing handles in cooperative mode, preventing those frees from racing with object relocation. It covers the straightforward cases rather than resolving the entire issue.

Changes:

  • Add cooperative-mode scopes to JIT, callback-thunk, and loader-allocator handle cleanup.
  • Tighten sync-block cleanup contracts to require cooperative mode.
  • Add an isolated regression stress test that combines repeated JIT compilation with compacting collections and allocation pressure.
File Description
src/​tests/​Regressions/​coreclr/​GitHub_117138/​test117138.csproj Configures process isolation, platform exclusions, priority, and disabled tiered compilation.
src/​tests/​Regressions/​coreclr/​GitHub_117138/​test117138.cs Stresses JIT-time handle cleanup during compacting collections.
src/​coreclr/​vm/​syncblk.cpp Requires cooperative mode for DeleteSyncBlock.
src/​coreclr/​vm/​loaderallocator.cpp Enters cooperative mode before freeing registered handles.
src/​coreclr/​vm/​jitinterface.h Frees JIT handles cooperatively and updates the destructor’s GC contract.
src/​coreclr/​vm/​encee.cpp Requires cooperative mode for Edit and Continue sync-block cleanup.
src/​coreclr/​vm/​dllimportcallback.cpp Frees callback-thunk handles cooperatively and updates the GC contract.
src/​coreclr/​binder/​customassemblybinder.cpp Frees assembly-load-context handles within a cooperative-mode scope.

Review effort: Balanced

@jkotas jkotas 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.

Thank you!

@jkotas
jkotas merged commit f1d204b into dotnet:main Nov 23, 2026
160 of 164 checks passed
@pcshrosbree

Copy link
Copy Markdown
Contributor Author

Thank you for the review and merge!

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

Labels

area-VM-coreclr community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants