Skip to content

Wait for EE startup before finalizer managed execution - #135452

Merged
davidwrighton merged 1 commit into
dotnet:mainfrom
davidwrighton:fix/finalizer-wait-for-ee-startup
Oct 9, 2026
Merged

davidwrighton merged 1 commit into
dotnet:mainfrom
davidwrighton:fix/finalizer-wait-for-ee-startup

Conversation

@davidwrighton

@davidwrighton davidwrighton commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Make the dedicated finalizer thread wait for EE startup to finish before entering its managed worker.

CoreLib activation is not a sufficient readiness barrier: startup initializes shared statics and thread-static infrastructure afterward. The finalizer thread can already be running during that interval, and GC.RunFinalizers accesses Thread.CurrentThread before checking for finalizable objects.

After HasStarted() and background-thread registration, call EnsureEEStarted() in preemptive GC mode. EE startup creates the finalizer thread while holding the startup lock, so this call waits for the existing initializer rather than initiating loading on the finalizer thread. Keep the early Windows COM/FLS handshake and debugger helper thread unchanged.

If startup is unavailable or has failed, log the HRESULT, skip managed execution, and signal finalizer shutdown completion.

Validation

Linux x64, Checked CoreCLR, Release libraries, Debug host:

  • ./build.sh clr+libs+host -rc Checked -lc Release -hc Debug - baseline passed, zero warnings/errors.
  • ./build.sh clr.runtime -rc Checked -lc Release -hc Debug - final patched build passed, zero warnings/errors.
  • ./src/tests/build.sh -GenerateLayoutOnly x64 Checked /p:HostConfiguration=Debug - passed. The Core_Root runtime hash matched the freshly built runtime.
  • .dotnet/dotnet artifacts/bin/coreclr/linux.x64.Checked/R2RDump/R2RDump.dll --in artifacts/tests/coreclr/linux.x64.Checked/Tests/Core_Root/System.Private.CoreLib.dll --header | head -35 - verified CoreLib's ReadyToRun signature 0x00525452 and format version 31.0.
  • ./src/tests/build.sh -test:GC/API/GC/Finalize.csproj -test:GC/API/GC/ReRegisterForFinalize.csproj -test:GC/API/GC/SuppressFinalize.csproj x64 Checked -priority1 /p:HostConfiguration=Debug - passed; exactly three test projects built.
  • The following test matrix passed all 60 process-isolated runs, each returning 100:
CORE_ROOT="$PWD/artifacts/tests/coreclr/linux.x64.Checked/Tests/Core_Root"
export CORE_ROOT
for stress in 0 0x3; do
    for test in Finalize ReRegisterForFinalize SuppressFinalize; do
        for iteration in $(seq 1 10); do
            env -u COMPlus_GCStress DOTNET_GCStress="$stress" timeout 60 \
                "$CORE_ROOT/corerun" \
                "$PWD/artifacts/tests/coreclr/linux.x64.Checked/GC/API/GC/$test/$test.dll"
            result=$?
            test "$result" -eq 100 || exit 1
        done
    done
done
  • Isolated startup-failure check with only the freshly built corerun and libcoreclr.so, deliberately omitting CoreLib: passed. timeout 15 observed corerun exit 255 with 0x80070002; runtime logging confirmed that the finalizer skipped managed execution because EnsureEEStarted() failed. The temporary runtime fixture was removed afterward.
  • git diff --check - passed.

Windows ICorDebug validation

Locally tested on Windows 11 Enterprise x64, version 10.0.26300, with Checked CoreCLR, Release libraries, Debug host, and ReadyToRun CoreLib, using the complete public-API-only StartupLauncher.cpp and Startup.cs from #135448. No function evaluation was performed.

The comparison used a clean isolated worktree at the PR's immediate parent, d21d8d491d303fa65d75da14b09c8475d2a94bb5, followed by the exact PR head, 34a436b16fd32634beb24b5d1561331d16006d70. The only source difference is this PR's finalizerthread.cpp change. Separate Core_Root snapshots were frozen and their runtime, CoreLib, corerun, DBI, and DAC SHA256 hashes checked against the corresponding build outputs. CoreLib was identical across snapshots; its managed-native header had RVA 5272, size 220, ReadyToRun signature 0x00525452, version 31.0.

Scenario Without fix With PR
ICorDebug startup, launcher GCStress=0, target-only GCStress=0x3 9/10 runs failed before Main; 1/10 reached Main and Debugger.Break 30/30 reached Main and Debugger.Break, launcher exit 0, no contract assertions
ICorDebug startup, target GCStress=0 3/3 reached Main and Debugger.Break, exit 0 3/3 reached Main and Debugger.Break, exit 0
Direct corerun, no debugger, GCStress=0x3 3/3 reached Main, exit 0 3/3 reached Main, exit 0

The locally observed unpatched failure was an earlier native Checked assertion, not the exact managed 0x80131506 output in the issue: CrstBase::Enter rejected lock acquisition in a GC_NOTRIGGER + MODE_COOPERATIVE region, with GetTLSIndexForThreadStatic -> MethodTable::EnsureTlsIndexAllocated -> DynamicHelperFixup -> DynamicHelperWorker -> DelayLoad_Helper -> CoreLib -> FinalizerThread::FinalizeAllObjects on the finalizer thread. The launcher returned 2 after the target exited before its breakpoint. This establishes failure-before/pass-after for the Windows startup scenario without claiming that the issue's exact exception text was reproduced.

Build and execution commands (run from the isolated source root; $CR selects the corresponding frozen Core_Root):

# Immediate parent: passed, 0 warnings/errors.
.\build.cmd clr+libs+host -rc Checked -lc Release -hc Debug -a x64

# Exact PR head: passed, 0 warnings/errors.
# The first incremental attempt encountered stale MSBuild workers locking
# Crossgen2Tasks.dll; after stopping only this worktree's idle workers, this passed.
$env:MSBUILDDISABLENODEREUSE = '1'
.\build.cmd clr.runtime -rc Checked -lc Release -hc Debug -a x64

# Parent and PR: both passed, 0 warnings/errors.
.\src\tests\build.cmd -GenerateLayoutOnly x64 Checked /p:HostConfiguration=Debug

# Launcher build in an x64 VS developer shell: passed.
cl /nologo /EHsc /std:c++17 /W4 `
  "/I$R\src\coreclr\inc" `
  "/I$R\artifacts\obj\coreclr\windows.x64.Checked\inc\idls_out" `
  StartupLauncher.cpp /link ole32.lib /out:StartupLauncher.exe

# Managed repro compiled once against the built parent Core_Root: passed.
$SDKRoot = 'C:\git\runtime\.dotnet'
& "$SDKRoot\dotnet.exe" "$SDKRoot\sdk\11.0.100-rc.1.26420.103\Roslyn\bincore\csc.dll" `
  -nologo -noconfig -nostdlib -target:exe -debug:portable -optimize- `
  "-r:$CR\System.Private.CoreLib.dll" "-r:$CR\System.Runtime.dll" "-r:$CR\System.Console.dll" `
  -out:Startup.dll Startup.cs

# Repeated in fresh processes; outcomes and counts are in the table.
$env:DOTNET_GCStress = '0'
Remove-Item Env:COMPlus_GCStress -ErrorAction SilentlyContinue
.\StartupLauncher.exe $Shim "$CR\corerun.exe" "$PWD\Startup.dll" 0x3
.\StartupLauncher.exe $Shim "$CR\corerun.exe" "$PWD\Startup.dll" 0
$env:CORE_ROOT = $CR
$env:DOTNET_GCStress = '0x3'
& "$CR\corerun.exe" "$PWD\Startup.dll"
$env:DOTNET_GCStress = '0'

The same cached public Windows x64 Microsoft.Diagnostics.DbgShim.win-x64 package, version 8.0.0-preview.23527.1 (file version 8.0.9.2701, SHA256 7B7ADB0E5E06C650F3D1093DCF901A5F65B4C8A2ECBF1A3343546EEF4A391648), was used for both sides. This differs from the issue's recorded shim version. All 52 runs completed without timeouts or surviving target processes. Logs, source, hashes, and result matrices are preserved locally under C:\git\runtime\artifacts\tmp\pr135452-validation.

Scope and limitations

The Windows public-API startup repro now provides local failure-before/pass-after evidence. The Linux managed tests above remain smoke coverage.

The older startup ordering also allowed finalizer execution before TLS readiness; the introducing commit may have exposed a pre-existing race. This PR does not change the debugger retry path in ThreadSuspend::SuspendEE and does not claim to resolve the separately reported startup-thread CatchAtSafePoint GC-mode contract violation.

Resolves #135448

Note

This candidate fix and pull request description were generated with GitHub Copilot.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: c49ab1f9-7e7c-44a2-8f56-a17b7c1d2a70
@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 marked this pull request as ready for review October 9, 2026 01:08
@davidwrighton
davidwrighton merged commit 6ff62b1 into dotnet:main Oct 9, 2026
116 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 13, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 12, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Windows Checked CoreCLR fails before Main under ICorDebug + target-only GCStress=0x3

3 participants