Repository navigation
[release/11.0] Fix collectible thread-static lifetime and index reuse - #136478
Merged
Merged
Conversation
## Summary Collectible thread-static indices can be reused after their owning `LoaderAllocator` is reclaimed. The old implementation made an index immediately available for reuse even though surviving threads could still contain loader handles, weak TLS handles, or in-flight initialization data belonging to the previous owner. That allowed stale state to be interpreted as belonging to a replacement type, leading to memory corruption, stale backing storage, use-after-free, or linked-list cycles. ## Changes ### Fix in-flight entry lifetime `InFlightTLSData` temporarily owns thread-static storage while a type initializer is running. A surviving thread could retain an entry after its collectible weak target was cleared, and a replacement type reusing the index could delete and then reuse the stale node. The lookup now removes entries whose weak target has disappeared, clears the deleted lookup pointer, and separates existing entries from newly allocated nodes. Only newly allocated nodes are linked, and their holder retains ownership until publication completes. ### Quarantine collectible indices before reuse Loader allocator cleanup now marks collectible TLS indices as retired rather than immediately reusable. `FindClearedIndex` ignores retired entries. At the next successful EE synchronization, `SyncClean::CleanUp` walks every runtime thread and clears state associated with each retired index: - Allocator-relative loader handles. - Collectible TLS weak handles. - Matching in-flight initialization entries. Only after the complete thread walk is the index marked reusable. This prevents thread teardown from freeing an old handle through a replacement `LoaderAllocator`, and prevents replacement types from observing storage belonging to the previous owner. `ThreadSuspend::RestartEE` now runs synchronized cleanup only after a successful suspension. A failed debugger suspension can reach `RestartEE(false)` while threads are still running, so none of the `SyncClean` reclamation work is safe in that case. ### Make index publication failure-atomic The owning loader allocator's TLS cleanup list now reserves capacity before the `MethodTable` is published in the global index map. Once publication succeeds, recording the index cannot allocate or fail. The next-index counter advances only after both records are complete. This prevents an OOM from leaving a globally published collectible index that is not tracked for loader allocator cleanup. ### Correct collectible TLS memory bookkeeping - DAC enumeration now converts the collectible handle count to bytes, so the complete `OBJECTHANDLE` array is captured. - The per-thread collectible handle array is deleted through its allocated `OBJECTHANDLE[]` type instead of through `uint8_t*`. ## Testing - Windows x86 Checked CoreCLR build. - `CollectibleTLSStaticCollection` passed five consecutive runs on the split branch. - The in-flight regression was verified during development to crash against the unfixed runtime and pass with these changes. - The existing collectible shutdown regression exercises index reuse during thread termination. Resolves #134928 Resolves #134931 > [!NOTE] > This pull request description was generated with GitHub Copilot. --------- Co-authored-by: Copilot <[email protected]> Copilot-Session: 839edb45-24ee-47bd-be2e-91446c5f7037
|
Azure Pipelines: Successfully started running 3 pipeline(s). 13 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 |
jkotas
approved these changes
Oct 26, 2026
2 of 4 tasks
JulieLeeMSFT
pushed a commit
that referenced
this pull request
Nov 3, 2026
…#136481) Fixes Issue <!-- Issue Number --> #134928 and #134931 main PR <!-- Link to PR if any that fixed this in the main branch. --> #134983 # Description <!-- Give a brief summary of the issue and how the pull request is fixing it. --> Backports #134983 to `release/10.0`. The corresponding .NET 11 backport is #136478. A collectible thread-static index could become available for reuse while surviving threads still held loader-allocator-relative handles, weak handles, or in-flight initialization state belonging to its previous owner. Reusing the index could then corrupt memory, return stale thread-static storage, or access freed initialization data. The fix quarantines retired indices until synchronized cleanup has removed the old state from every thread. It also corrects in-flight entry ownership, makes index publication failure-atomic, and fixes related handle cleanup and diagnostic memory enumeration. This is a manual backport of commit `fd41fc4d7de02724f0009872e52928d69a2ea999`. Release-specific adaptations preserve .NET 10's existing SyncClean hash-table cleanup, its two-argument `RestartEE` contract, and `CLASS__THREAD_BLOCKING_INFO` initialization. Cleanup is gated on successful EE suspension without importing newer interpreter or multithreading feature guards. Tests use .NET 10's existing capability checks and TestLibrary project reference to retain the intended CoreCLR coverage. # Customer Impact <!-- What is the impact to customers of not taking this fix? --> - [x] Customer reported - [ ] Found internally Reported in #134928 and #134931. Applications that unload collectible assemblies containing thread-static fields can experience process crashes, unexpected null references, or memory corruption when another collectible type reuses an index. Correct behavior is for the replacement type to receive independent storage, with no references to the unloaded owner's state. Reports include Windows x64 and macOS arm64, including a Unity Editor scenario. One customer reports repeated crashes during testing that are blocking a release. The underlying implementation is platform-independent CoreCLR code; applications that do not use collectible assemblies are not the reported scenario. Avoiding collectible assembly loading is a reported workaround, but prevents the affected assemblies from being unloaded. # Regression <!-- Is this fixing a problem that was introduced in the most recent release, ie., fixing a regression? --> - [x] Yes - [ ] No Regression introduced in .NET 9 by #99183 ("Make normal statics simpler"), which introduced the relevant thread-static index reuse and in-flight state machinery. The reporter of #134931 verified that the same reproduction passed on .NET 8.0.31 and crashed on .NET 9.0.20 and .NET 10.0.12. # Testing <!-- What kind of testing has been done with the fix. --> Local validation used Windows x86, Checked CoreCLR, and Release libraries. The .NET 10 backport was built from `release/10.0` commit `00a171f44e0` plus this fix. The .NET 11 comparison used the exact #136478 head, `5a1c26d6de811cb7a77a782eb29377f035621040`, rather than the development branch. Core_Root's `coreclr.dll` SHA256 was checked against each newly built product DLL before execution. The following commands passed in both release worktrees: ```powershell .\build.cmd -subset clr+libs+host -arch x86 -rc Checked -c Release .\src\tests\build.cmd -Test Loader\CollectibleAssemblies\Statics\CollectibleTLSStaticCollection.csproj x86 Checked -SkipNative .\src\tests\build.cmd -GenerateLayoutOnly x86 Checked ``` Both full builds and both test/layout builds completed with zero warnings and zero errors. The test builds selected the requested project. For the execution commands below, `$root` was the worktree's `artifacts\tests\coreclr\windows.x86.Checked\Tests\Core_Root`, and `$dir` was its `artifacts\tests\coreclr\windows.x86.Checked\Loader\CollectibleAssemblies\Statics\CollectibleTLSStaticCollection` directory: ```powershell & "$root\corerun.exe" "$dir\CollectibleTLSStaticCollection.dll" & "$root\corerun.exe" "$dir\ValidationRunner.dll" "$dir\CollectibleTLSStaticCollection.dll" all 5 & "$root\corerun.exe" C:\git\runtime\artifacts\tmp\tls-backport-validation\customer\built\Host.dll 300 none finalizer 2 4000 collectible 10 ``` `ValidationRunner.dll` is a local reflection harness, not a repository change. It explicitly invokes `ReuseCollectibleThreadStaticIndex`, `CleanupCollectibleThreadStaticsWhileStartingThreads`, and `TestEntryPoint` five times each, logging every invocation. The customer Host and Plugin were built from the attached reproduction source, retargeted to `net10.0` so the same binaries could run on both versions. | Runtime | Generated regression executable | Explicit regression invocations | Original customer reproduction | | --- | --- | --- | --- | | Fixed .NET 10 (`10.0.14-dev`) | Passed, exit 100 | Passed, 15/15, exit 0 | Passed, 90 contexts / 900 rounds in 302 seconds, exit 0 | | Fixed .NET 11 (`11.0.0-dev`, exact backport head) | Passed, exit 100 | Passed, 15/15, exit 0 | Passed, 191 contexts / 1,910 rounds in 301 seconds, exit 0 | As negative controls, the same customer reproduction was run with the same arguments on official unfixed Windows x86 runtimes .NET 10.0.12 and .NET 11.0.0-rc.1.26425.128. Both failed before completing the requested 300 seconds, with unexpected `NullReferenceException` failures in `SegmentedArrayBuilder<T>.Expand` through LINQ/PLINQ, matching the customer report. The backport includes coverage for unloading a collectible type with in-flight thread-static initialization and then accessing a replacement type, plus cleanup while threads are being started. Existing coverage exercises cleanup during thread termination. The collection helper asserts that the first assembly load context was collected, rather than allowing the test to pass without reaching the unload scenario. These are bounded local reliability runs, not a proof against all possible races or performance measurements. Other architectures and operating systems were not run locally. # Risk <!-- Please assess the risk of taking this fix. Provide details backing up your assessment. --> Medium. This changes native runtime lifetime management and synchronized cleanup, so the consequences of a mistake could be significant. The cleanup walk also adds work when collectible TLS indices have been retired. The fix targets the reported lifetime violations: indices cannot be reused until old per-thread state has been cleared; cleanup runs only after successful EE suspension; partially initialized threads without relevant storage are skipped before taking their TLS spin lock; and publication reserves cleanup-list capacity before exposing a new index. The manual adaptations retain .NET 10's surrounding cleanup behavior. Regression tests cover the in-flight lifetime and thread-start interactions. There are no public API changes. # Package authoring no longer needed in .NET 9 IMPORTANT: Starting with .NET 9, you no longer need to edit a NuGet package's csproj to enable building and bump the version. Keep in mind that we still need package authoring in .NET 8 and older versions. Resolves #134928 Resolves #134931 > [!NOTE] > This backport and PR description were prepared with GitHub Copilot. Co-authored-by: Copilot <[email protected]> Copilot-Session: 7553307e-916a-4ea6-9eac-8adeb08e0f55
Member
|
@davidwrighton, please check test failures. |
Member
|
/ba-g Failures are unrelated. |
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.
Backport of #134983 to release/11.0
/cc @davidwrighton
Fixes collectible thread-static lifetime and index reuse. A TLS index could become available for reuse while surviving threads still held handles or in-flight initialization state belonging to its previous owner. Reusing that index could then corrupt memory, return stale thread-static storage, or access freed initialization data.
The fix quarantines retired indices until synchronized cleanup has removed the old state from every thread. It also corrects in-flight entry ownership, makes index publication failure-atomic, and fixes related handle cleanup and diagnostic memory enumeration.
Customer Impact
Reported in #134928 and #134931. Applications that unload collectible assemblies containing thread-static fields can experience process crashes, unexpected null references, or memory corruption when another collectible type reuses an index. Correct behavior is for the replacement type to receive independent storage, with no references to the unloaded owner's state.
Reports include Windows x64 and macOS arm64, including a Unity Editor scenario. One customer reports repeated crashes during testing that are blocking a release. The underlying implementation is platform-independent CoreCLR code; applications that do not use collectible assemblies are not the reported scenario.
Avoiding collectible assembly loading is a reported workaround, but prevents the affected assemblies from being unloaded.
Regression
Regression introduced in .NET 9 by #99183 ("Make normal statics simpler"), which introduced the relevant thread-static index reuse and in-flight state machinery. The reporter of #134931 verified that the same reproduction passed on .NET 8.0.31 and crashed on .NET 9.0.20 and .NET 10.0.12.
Testing
The in-flight regression reproduction crashed against the unfixed runtime and passed with the fix.
The backport includes regression coverage for unloading a collectible type with in-flight thread-static initialization and then accessing a replacement type, plus cleanup while threads are being started. Existing coverage exercises collectible thread-static cleanup during thread termination. The collection helper asserts that the first assembly load context was collected, rather than allowing the test to pass without reaching the unload scenario.
The issue depends on the ordering of assembly collection, native loader-allocator cleanup, TLS index reuse, and surviving-thread activity. Ordinary thread-static tests without collectible unloading and reuse do not exercise that sequence.
Risk
Medium. This changes native runtime lifetime management and synchronized cleanup, so the consequences of a mistake could be significant. The cleanup walk also adds work when collectible TLS indices have been retired.
The fix is targeted at the reported lifetime violations: indices cannot be reused until old per-thread state has been cleared; cleanup runs only after successful EE suspension; partially initialized threads without relevant storage are skipped before taking their TLS spin lock; and publication reserves cleanup-list capacity before exposing a new index. Regression tests cover the in-flight lifetime and thread-start interactions. There are no public API changes.
Package authoring no longer needed in .NET 9
IMPORTANT: Starting with .NET 9, you no longer need to edit a NuGet package's csproj to enable building and bump the version.
Keep in mind that we still need package authoring in .NET 8 and older versions.