Skip to content

[release/11.0] Fix collectible thread-static lifetime and index reuse - #136478

Merged
JulieLeeMSFT merged 2 commits into
release/11.0from
backport/pr-134983-to-release/11.0
Nov 5, 2026
Merged

JulieLeeMSFT merged 2 commits into
release/11.0from
backport/pr-134983-to-release/11.0

Conversation

@github-actions

@github-actions github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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

  • 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

  • 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

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.

## 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

Copy link
Copy Markdown
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.

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

@davidwrighton
davidwrighton requested a review from jkotas October 26, 2026 18:00
@davidwrighton davidwrighton added the Servicing-approved Approved for servicing release label Nov 3, 2026
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
@JulieLeeMSFT JulieLeeMSFT added this to the 11.0.0 milestone Nov 3, 2026
@JulieLeeMSFT

JulieLeeMSFT commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

@davidwrighton, please check test failures.
Seems unrelated.

@davidwrighton

Copy link
Copy Markdown
Member

/ba-g Failures are unrelated.


┌─────────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Failure                                                     │ Evidence                                                                                                                                       │
├─────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Mutex directory permissions (40755)                         │ Matches dotnet/runtime#135889; the missing release/11.0 correction is tracked by dotnet/runtime#136325.                                        │
├─────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ MutexTests.NameOptionsApiCompatibilityTest, including       │ Matches dotnet/runtime#135888: test expectations conflict with the changed default mutex scope. Also covered by dotnet/runtime#136325.         │
│ Chrome, Firefox and V8                                      │                                                                                                                                                │
├─────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ HighNumberedFd_NotLeakedAfterLoweringRLimit on Alpine arm32 │ Matches dotnet/runtime#135795: incorrect test-side rlimit interop on 32-bit musl. Fails at setrlimit, before exercising the intended scenario; │
│                                                             │ fixed on main by dotnet/runtime#135867.                                                                                                        │
└─────────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

@JulieLeeMSFT
JulieLeeMSFT merged commit 8f0cccb into release/11.0 Nov 5, 2026
116 of 119 checks passed
@JulieLeeMSFT
JulieLeeMSFT deleted the backport/pr-134983-to-release/11.0 branch November 5, 2026 02:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-VM-coreclr Servicing-approved Approved for servicing release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants