Skip to content
Merged
Show file tree
Hide file tree
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
Aug 18, 2026
a8b74e8
Update test
Aug 18, 2026
571ed02
Fix
Aug 19, 2026
166744a
Fix osx
Aug 20, 2026
5d4d049
Abort instead of assert on unixes
Aug 20, 2026
ab39a8f
Merge branch 'main' into abort-when-reinitializing-thread
eduardo-vp Aug 20, 2026
8ed1582
Directly abort, avoid going through PAL's abort
Aug 24, 2026
82ab932
Update comment
Aug 24, 2026
87e665c
Revert "Update comment"
eduardo-vp Sep 4, 2026
e707a2a
Revert "Directly abort, avoid going through PAL's abort"
eduardo-vp Sep 4, 2026
647a2cb
Avoid abort, use kill/_exit
eduardo-vp Sep 4, 2026
c2d20ef
Merge branch 'main' into abort-when-reinitializing-thread
eduardo-vp Sep 15, 2026
5dcbf4d
Update test
eduardo-vp Sep 15, 2026
6b4c146
Update CMakeLists and ThreadStateDestroyed logic
eduardo-vp Sep 15, 2026
46414b1
Make CallbackFn's calling convention explicit
eduardo-vp Sep 15, 2026
fc6c557
Make it NAOT incompatible, enable it in a separate PR
eduardo-vp Sep 15, 2026
151f475
Use a pthread key on apple only
eduardo-vp Sep 16, 2026
4d5272a
Use _ASSERTE_ALL_BUILDS instead of aborting. It did work on my arm64 …
eduardo-vp Sep 16, 2026
a2e339d
Enhance thread destruction test validation
eduardo-vp Sep 16, 2026
e5a4a22
Disable OS core dump, looks like it was causing the test to time out
eduardo-vp Sep 16, 2026
62b25cb
Merge branch 'main' into abort-when-reinitializing-thread
eduardo-vp Sep 16, 2026
e124be9
Use _ASSERTE_ALL_BUILDS in SetThreadStateDestroyed
eduardo-vp Sep 16, 2026
b4751fb
Remove one ifdef
eduardo-vp Sep 17, 2026
440db39
Remove second check in OsAttachThread, add an assertion
eduardo-vp Sep 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 84 additions & 16 deletions src/coreclr/vm/ceemain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@ HRESULT EEStartup();

static void InitializeGarbageCollector();

#ifdef TARGET_APPLE
static void InitThreadStateKey();
#endif

#ifdef DEBUGGING_SUPPORTED
static void InitializeDebugger(void);
static void TerminateDebugger(void);
Expand Down Expand Up @@ -710,6 +714,10 @@ void EEStartupHelper()
InitThreadManager();
STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "Returned successfully from InitThreadManager");

#ifdef TARGET_APPLE
InitThreadStateKey();
#endif

#ifdef FEATURE_PERFTRACING
// Initialize the event pipe.
EventPipeAdapter::Initialize();
Expand Down Expand Up @@ -1704,6 +1712,11 @@ static uint32_t g_flsIndex = FLS_OUT_OF_INDEXES;

static PLATFORM_THREAD_LOCAL byte t_flsState;

static bool HasThreadStateBeenDestroyed()
{
return t_flsState == FLS_STATE_INVOKED;
}

// This is called when each *fiber* is destroyed. When the home fiber of a thread is destroyed,
// it means that the thread itself is destroyed.
// Since we receive that notification outside of the Loader Lock, it allows us to safely acquire
Expand Down Expand Up @@ -1733,27 +1746,12 @@ void InitFlsSlot()
}

// Register the thread with OS to be notified when thread is about to be destroyed
// It fails fast if a different thread was already registered with the current fiber.
// Parameters:
// thread - thread to attach
static void OsAttachThread(void* thread)
{
_ASSERTE(g_flsIndex != FLS_OUT_OF_INDEXES);

if (t_flsState == FLS_STATE_INVOKED)
{
// Managed C++ may run managed code in DllMain (e.g. during DLL_PROCESS_DETACH to run global destructors). This is
// not supported and unreliable. Historically, it happened to work most of the time. For backward compatibility,
// suppress this assert in release builds if we have encountered any mixed mode binaries.
if (Module::HasAnyIJWBeenLoaded())
{
_ASSERTE(!"Attempt to execute managed code after the .NET runtime thread state has been destroyed.");
}
else
{
_ASSERTE_ALL_BUILDS(!"Attempt to execute managed code after the .NET runtime thread state has been destroyed.");
}
}
_ASSERTE(t_flsState == FLS_STATE_CLEAR);

t_flsState = FLS_STATE_ARMED;

Expand Down Expand Up @@ -1798,6 +1796,54 @@ void EnsureTlsDestructionMonitor()
}

#else
#ifdef TARGET_APPLE
static pthread_key_t g_threadStateKey;
static byte g_threadStateDestroyedMarker;

static void SetThreadStateDestroyed()
{
if (pthread_setspecific(g_threadStateKey, &g_threadStateDestroyedMarker) != 0)
{
_ASSERTE_ALL_BUILDS(!"Failed to preserve the destroyed runtime thread state.");
}
}

// POSIX clears a key before invoking its destructor, and key destructor order is unspecified.
// Restore the marker so managed re-entry from later destructors can observe the destroyed state.
static void ThreadStateKeyDestructor(void* state)
{
if (state == &g_threadStateDestroyedMarker)
{
SetThreadStateDestroyed();
}
}
Comment thread
jkotas marked this conversation as resolved.
Resolved

static void InitThreadStateKey()
{
if (pthread_key_create(&g_threadStateKey, ThreadStateKeyDestructor) != 0)
{
COMPlusThrowOM();
}
}

static bool HasThreadStateBeenDestroyed()
{
return pthread_getspecific(g_threadStateKey) == &g_threadStateDestroyedMarker;
}
#else
static PLATFORM_THREAD_LOCAL bool t_threadStateDestroyed;

static bool HasThreadStateBeenDestroyed()
{
return t_threadStateDestroyed;
}

static void SetThreadStateDestroyed()
{
t_threadStateDestroyed = true;
}
#endif

struct TlsDestructionMonitor
{
bool m_activated = false;
Expand All @@ -1813,6 +1859,8 @@ struct TlsDestructionMonitor
{
RuntimeThreadShutdown(GetThreadNULLOk());
}

SetThreadStateDestroyed();
}
};

Expand All @@ -1827,6 +1875,26 @@ void EnsureTlsDestructionMonitor()

#endif

void CheckThreadStateNotDestroyed()
{
if (!HasThreadStateBeenDestroyed())
{
return;
}

// Managed C++ may run managed code in DllMain (e.g. during DLL_PROCESS_DETACH to run global destructors). This is
// not supported and unreliable. Historically, it happened to work most of the time. For backward compatibility,
// suppress this assert in release builds if we have encountered any mixed mode binaries.
if (Module::HasAnyIJWBeenLoaded())
{
_ASSERTE(!"Attempt to execute managed code after the .NET runtime thread state has been destroyed.");
}
else
{
_ASSERTE_ALL_BUILDS(!"Attempt to execute managed code after the .NET runtime thread state has been destroyed.");
}
}

#ifdef DEBUGGING_SUPPORTED
//
// InitializeDebugger initialized the Runtime-side CLR Debugging Services
Expand Down
3 changes: 3 additions & 0 deletions src/coreclr/vm/ceemain.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ void ForceEEShutdown(ShutdownCompleteAction sca = SCA_ExitProcessWhenShutdownCom
void ThreadDetaching();

void EnsureTlsDestructionMonitor();

// Fails fast if the runtime thread state of the current thread has already been destroyed.
void CheckThreadStateNotDestroyed();
#ifdef TARGET_WINDOWS
void InitFlsSlot();
void OsDetachThread(void* thread);
Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/vm/threads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,8 @@ Thread* SetupThread()
if ((pThread = GetThreadNULLOk()) != NULL)
return pThread;

CheckThreadStateNotDestroyed();
Comment thread
eduardo-vp marked this conversation as resolved.
Resolved
Comment thread
jkotas marked this conversation as resolved.
Resolved

// For interop debugging, we must mark that we're in a can't-stop region
// b.c we may take Crsts here that may block the helper thread.
// We're especially fragile here b/c we don't have a Thread object yet
Expand Down
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)
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;
Comment thread
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;
Comment thread
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;
}
}
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>
Loading