Repository navigation
Abort when there's an attempt to reinitialize a runtime thread object #132448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
eduardo-vp
merged 24 commits into
dotnet:main
from
eduardo-vp:abort-when-reinitializing-thread
Sep 17, 2026
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
44a9b6b
Adding test that checks attempt to reinitialize a runtime thread object
a8b74e8
Update test
571ed02
Fix
166744a
Fix osx
5d4d049
Abort instead of assert on unixes
ab39a8f
Merge branch 'main' into abort-when-reinitializing-thread
eduardo-vp 8ed1582
Directly abort, avoid going through PAL's abort
82ab932
Update comment
87e665c
Revert "Update comment"
eduardo-vp e707a2a
Revert "Directly abort, avoid going through PAL's abort"
eduardo-vp 647a2cb
Avoid abort, use kill/_exit
eduardo-vp c2d20ef
Merge branch 'main' into abort-when-reinitializing-thread
eduardo-vp 5dcbf4d
Update test
eduardo-vp 6b4c146
Update CMakeLists and ThreadStateDestroyed logic
eduardo-vp 46414b1
Make CallbackFn's calling convention explicit
eduardo-vp fc6c557
Make it NAOT incompatible, enable it in a separate PR
eduardo-vp 151f475
Use a pthread key on apple only
eduardo-vp 4d5272a
Use _ASSERTE_ALL_BUILDS instead of aborting. It did work on my arm64 …
eduardo-vp a2e339d
Enhance thread destruction test validation
eduardo-vp e5a4a22
Disable OS core dump, looks like it was causing the test to time out
eduardo-vp 62b25cb
Merge branch 'main' into abort-when-reinitializing-thread
eduardo-vp e124be9
Use _ASSERTE_ALL_BUILDS in SetThreadStateDestroyed
eduardo-vp b4751fb
Remove one ifdef
eduardo-vp 440db39
Remove second check in OsAttachThread, add an assertion
eduardo-vp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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
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
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
13 changes: 13 additions & 0 deletions
13
src/tests/baseservices/threading/ThreadStateDestroyed/CMakeLists.txt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| project (ThreadStateDestroyedNative) | ||
|
|
||
| include_directories(${INC_PLATFORM_DIR}) | ||
|
|
||
| set(SOURCES ThreadStateDestroyedNative.cpp) | ||
|
|
||
| if(NOT CLR_CMAKE_HOST_WIN32) | ||
| add_compile_options(-pthread) | ||
| endif() | ||
|
|
||
| add_library (ThreadStateDestroyedNative ${TEST_LIB_TYPE} ${SOURCES}) | ||
|
|
||
| install (TARGETS ThreadStateDestroyedNative DESTINATION bin) |
125 changes: 125 additions & 0 deletions
125
src/tests/baseservices/threading/ThreadStateDestroyed/ThreadStateDestroyed.cs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Diagnostics; | ||
| using System.Runtime.InteropServices; | ||
| using System.Threading; | ||
| using TestLibrary; | ||
|
|
||
| // A native library runs managed code on an OS thread, then runs managed code again from a | ||
| // thread-destruction callback that fires after the runtime has already torn down its per-thread | ||
| // state. The runtime should fail fast instead of attaching another managed thread. | ||
|
|
||
| public static unsafe class ThreadStateDestroyed | ||
| { | ||
| private const int Pass = 100; | ||
| private const int Fail = -1; | ||
|
|
||
| private const string NativeLib = "ThreadStateDestroyedNative"; | ||
| private const string RunScenarioArg = "--run-scenario"; | ||
|
|
||
| private static readonly TimeSpan s_subprocessTimeout = TimeSpan.FromSeconds(60); | ||
|
|
||
| // In non-Release builds, also check the message to distinguish this failure from other crashes. | ||
| private const string ExpectedMessage = | ||
| "Attempt to execute managed code after the .NET runtime thread state has been destroyed."; | ||
| private const string SecondCallbackMarker = "[managed] callback #2"; | ||
|
|
||
| [DllImport(NativeLib)] | ||
| private static extern void RunCallbackOnThreadAndDuringItsDestruction(delegate* unmanaged<void> callback); | ||
|
|
||
| private static int s_callbackCount; | ||
| private static Thread s_firstThread; | ||
|
|
||
| [UnmanagedCallersOnly] | ||
| private static void Callback() | ||
| { | ||
| int count = Interlocked.Increment(ref s_callbackCount); | ||
| Thread current = Thread.CurrentThread; | ||
|
|
||
| if (count == 1) | ||
| { | ||
| s_firstThread = current; | ||
| Console.WriteLine("[managed] callback #1 ran; the runtime attached a Thread to the OS thread."); | ||
| } | ||
| else | ||
| { | ||
| // Managed thread ids can be recycled, so compare the Thread objects themselves. | ||
| bool newThread = !ReferenceEquals(current, s_firstThread); | ||
| Console.WriteLine($"{SecondCallbackMarker} ran; attached to a new Thread: {newThread}."); | ||
| } | ||
| } | ||
|
|
||
| public static int Main(string[] args) | ||
| { | ||
| return args.Length > 0 && args[0] == RunScenarioArg | ||
| ? RunScenario() | ||
| : RunController(); | ||
| } | ||
|
|
||
| private static int RunScenario() | ||
| { | ||
| // Ensure that the OS doesn't generate core dump for this intentionally crashing process | ||
| Utilities.DisableOSCoreDump(); | ||
|
|
||
| RunCallbackOnThreadAndDuringItsDestruction(&Callback); | ||
|
|
||
| Console.WriteLine("[managed] The runtime did not fail fast."); | ||
| return Fail; | ||
| } | ||
|
|
||
| private static int RunController() | ||
| { | ||
| string[] arguments = TestLibrary.Utilities.IsNativeAot | ||
| ? [RunScenarioArg] | ||
| : [typeof(ThreadStateDestroyed).Assembly.Location, RunScenarioArg]; | ||
|
|
||
| ProcessStartInfo psi = new ProcessStartInfo(Environment.ProcessPath, arguments) | ||
| { | ||
| RedirectStandardOutput = true, | ||
| RedirectStandardError = true, | ||
| }; | ||
|
|
||
| psi.Environment["DOTNET_DbgEnableMiniDump"] = "0"; | ||
| psi.Environment["DOTNET_EnableCrashReport"] = "0"; | ||
|
|
||
| ProcessTextOutput subprocess; | ||
| try | ||
| { | ||
| subprocess = Process.RunAndCaptureText(psi, s_subprocessTimeout); | ||
| } | ||
| catch (TimeoutException) | ||
| { | ||
| Console.WriteLine($"Subprocess timed out after {s_subprocessTimeout}."); | ||
| return Fail; | ||
| } | ||
|
|
||
| string output = subprocess.StandardOutput + subprocess.StandardError; | ||
| int exitCode = subprocess.ExitStatus.ExitCode; | ||
|
eduardo-vp marked this conversation as resolved.
Resolved
|
||
|
|
||
| Console.WriteLine($"Subprocess exited with {exitCode}:"); | ||
| Console.WriteLine(output); | ||
|
|
||
| if (output.Contains(SecondCallbackMarker)) | ||
| { | ||
| Console.WriteLine("The runtime ran managed code on a thread whose runtime thread state was already destroyed."); | ||
| return Fail; | ||
| } | ||
|
|
||
| if (output.Contains("[managed] The runtime did not fail fast.") || | ||
| !output.Contains("[native] invoking managed callback from the thread destruction callback")) | ||
| { | ||
| Console.WriteLine("The test scenario did not reach the expected thread-destruction failure."); | ||
| return Fail; | ||
|
Copilot marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| if ((!OperatingSystem.IsWindows() || !TestLibrary.CoreClrConfigurationDetection.IsReleaseRuntime) && !output.Contains(ExpectedMessage)) | ||
| { | ||
| Console.WriteLine($"The subprocess terminated for some other reason. Expected to find: {ExpectedMessage}"); | ||
| return Fail; | ||
| } | ||
|
|
||
| return Pass; | ||
| } | ||
| } | ||
19 changes: 19 additions & 0 deletions
19
src/tests/baseservices/threading/ThreadStateDestroyed/ThreadStateDestroyed.csproj
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <RequiresProcessIsolation>true</RequiresProcessIsolation> | ||
| <ReferenceXUnitWrapperGenerator>false</ReferenceXUnitWrapperGenerator> | ||
| <AllowUnsafeBlocks>true</AllowUnsafeBlocks> | ||
| <GCStressIncompatible>true</GCStressIncompatible> | ||
| <NativeAotIncompatible>true</NativeAotIncompatible> | ||
| <CLRTestTargetUnsupported Condition="'$(TargetsAppleMobile)' == 'true' or '$(TargetsAndroid)' == 'true' or '$(TargetsBrowser)' == 'true' or '$(TargetsWasi)' == 'true'">true</CLRTestTargetUnsupported> | ||
| <CLRTestTargetUnsupported Condition="'$(RuntimeFlavor)' != 'coreclr'">true</CLRTestTargetUnsupported> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <Compile Include="ThreadStateDestroyed.cs" /> | ||
| <ProjectReference Include="$(TestLibraryProjectPath)" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <CMakeProjectReference Include="CMakeLists.txt" /> | ||
| </ItemGroup> | ||
| </Project> |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.