Repository navigation
Free GC handles in cooperative mode: the easy cases - #138085
Merged
Merged
Conversation
~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
|
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. |
Contributor
|
Tagging subscribers to this area: @agocke |
Member
|
/azp run runtime-coreclr outerloop |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
This was referenced Nov 23, 2026
Contributor
There was a problem hiding this comment.
🟢 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
Contributor
Author
|
Thank you for the review and merge! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
DestroyHandleisMODE_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(...)inBlockFreeHandlesInMask) or hands it out again (*(_UNCHECKED_OBJECTREF *)handle == NULLinHndCreateHandle). 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
Threadand holds no lock that makes the switch unsafe.Changes
~CEEInfo(first commit) frees the handles thatgetJitHandleForObjectcreates for objects outside the frozen heap that the JIT asks about. An example is astatic readonlyarray 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 fromLIMITED_METHOD_CONTRACTtoNOTHROW/GC_TRIGGERS/MODE_ANY, in response to Delete GC handles in COOP mode #125350 (comment).UMEntryThunkData::Terminate:GCX_COOP()insideif (pObjectHandle != NULL), and the contract gainsGC_TRIGGERS. Its only caller,FreeUMEntryThunk, is alreadyGC_TRIGGERS. The racy path is inCOMDelegate::ConvertToCallback: when another thread installs a thunk first, the losing thread frees its own thunk underGCX_PREEMP. That thunk holds a long weak handle to the live delegate.CustomAssemblyBinder::ReleaseLoadContext:GCX_COOP()before its two frees. OnlyLoaderAllocator::GCLoaderAllocatorsreaches this function, throughAssemblyLoaderAllocator::ReleaseAssemblyLoadContext.GCLoaderAllocatorsruns in preemptive mode. The strong handle keeps the load context alive. The switch stays inside this function because the next call inGCLoaderAllocators' loop,CleanupDependentHandlesToNativeObjects, isMODE_PREEMPTIVE.AssemblyLoaderAllocator::CleanupHandles:GCX_COOP()at function scope, before the loop that frees the handles. The function's existing switch sits inside#ifdef FEATURE_MULTITHREADINGand anif. The caller already switches modes while holding the same lock, a normal Crst.SyncBlockCache::DeleteSyncBlockandEnCSyncBlockInfo::Cleanup:MODE_ANYbecomesMODE_COOPERATIVE. Their only callers,CleanupSyncBlockson the finalizer thread andDeleteSyncBlockrespectively, run in cooperative mode.The
~CEEInfochange is @EgorBo's, from #125350, and he confirmed it fixes the repro (#117138 (comment)). Egor, would you like aCo-authored-bycredit on the commit? I'll add it if so. #125350 was closed for inactivity. It also changedTerminate(in a different way),ReleaseLoadContextand the two contracts, but notCleanupHandles. Its other changes are not included, among them:MODE_COOPERATIVEcontract onDestroyHandleCommon;DestroyHandleInPreemptiveMode;Threadhandle cleanup.LCGMethodResolver::DestroyResolver, which #125350 also changed, is left alone. The managed finalizer callsDestroyonly afterGetResolverreturns 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:CLRExceptioncleanup can occur when leaving anEX_CATCH, including in preemptive QCall frames. It also runs from~Threadafter the current thread is cleared. It stays racy.Thread::~Threadcan run with no currentThread, or under the ThreadStore lock.InteropLibImports::DestroyHandleandComCallWrapper::ClearHandleare reached from a nativeRelease, on a thread that may have noThread.ProfToEEInterfaceImpl::DestroyHandleis an asynchronous entry point that does not require aThread.DB_IPCE_DISPOSE_HANDLEand inUpdateForceCatchHandlerFoundTableon its helper thread, which normally has noThread.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.
DOTNET_TieredCompilation=0,DOTNET_GCHeapHardLimit=0x1000000Regressions/coreclr/GitHub_117138DOTNET_GCStress=0xC,DOTNET_ReadyToRun=0(about 2.4 s per run)The issue's
DOTNET_GCHeapHardLimit=0x100000fails 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 theGCX_COOPholder saved before switching. Elsewhere, it read the thread's current GC mode.lldb counts: the race-loser,
ReleaseLoadContextandCleanupHandlesfrees arrived in preemptive modeTerminate, race-loser pathTerminate, finalizer pathReleaseLoadContextCleanupHandlesDeleteSyncBlock(sync probe)EnCSyncBlockInfo::CleanupProbe 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 oneHndCreateHandleassert, 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~CEEInfohandles.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_11713830 of 30. In the mergedRegressionsrunner, 99 tests passed and three failed:GitHub_102887,GitHub_117393andGitHub_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 reachedEnCSyncBlockInfo::Cleanup, so I checked its contract only by reading its one caller. I checked the other contracts on Windows:add_definitions(-DDISABLE_CONTRACTS)line removed; not part of this PR). Each probe ran 50 times plain and 20 times underDOTNET_GCStress=0xC, the repro 50 times andGitHub_11713810 times. There were no contract violations or asserts. As a control, I changedDeleteSyncBlock's contract toMODE_PREEMPTIVE: the sync probe then failed 5 of 5 runs withCONTRACT VIOLATION by SyncBlockCache::DeleteSyncBlock("MODE_PREEMPTIVE encountered while thread is in cooperative state").I have not run this on other platforms or across the CI stress legs.
Test
Regressions/coreclr/GitHub_117138gives 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 32static readonlyarrays, 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 setsDOTNET_TieredCompilation=0so 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 isCLRTestPriority1, setsRequiresProcessIsolation, 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.