Skip to content

Commit

Permalink
Fix race condition in cleanup of collectible thread static variables (d…
Browse files Browse the repository at this point in the history
…otnet#111257)

* Fix issue 110837

There was a race condition where we could have collected all of the managed state of a LoaderAllocator, but not yet started cleaning up the actual LoaderAllocator object in native code. If a thread which had a TLS variable defined in a code associated with a collectible loader allocator was terminated at that point, then the runtime would crash.

The fix is to detect if the LoaderAllocator managed state is still alive, and if so, do not attempt to clean it up.

* Disable test on NativeAOT

* Update src/tests/Loader/CollectibleAssemblies/Statics/CollectibleTLSStaticCollection.cs

Co-authored-by: Copilot <[email protected]>

* Update src/tests/Loader/CollectibleAssemblies/Statics/CollectibleTLSStaticCollection.cs

Co-authored-by: Copilot <[email protected]>

* Fix missing adjustment missed by copilot

---------

Co-authored-by: Copilot <[email protected]>
  • Loading branch information
davidwrighton and Copilot authored Jan 10, 2025
1 parent 22e39f9 commit 128321e
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/coreclr/vm/threadstatics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ void FreeLoaderAllocatorHandlesForTLSData(Thread *pThread)
#endif
for (const auto& entry : g_pThreadStaticCollectibleTypeIndices->CollectibleEntries())
{
_ASSERTE((entry.TlsIndex.GetIndexOffset() <= pThread->cLoaderHandles) || allRemainingIndicesAreNotValid);
_ASSERTE((entry.TlsIndex.GetIndexOffset() >= pThread->cLoaderHandles) || !allRemainingIndicesAreNotValid);
if (entry.TlsIndex.GetIndexOffset() >= pThread->cLoaderHandles)
{
#ifndef _DEBUG
Expand All @@ -392,7 +392,9 @@ void FreeLoaderAllocatorHandlesForTLSData(Thread *pThread)
{
if (pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()] != (LOADERHANDLE)NULL)
{
entry.pMT->GetLoaderAllocator()->FreeHandle(pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()]);
LoaderAllocator *pLoaderAllocator = entry.pMT->GetLoaderAllocator();
if (pLoaderAllocator->IsExposedObjectLive())
pLoaderAllocator->FreeHandle(pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()]);
pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()] = (LOADERHANDLE)NULL;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// 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.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;

namespace CollectibleThreadStaticShutdownRace
{
public class CollectibleThreadStaticShutdownRace
{
Action? UseTLSStaticFromLoaderAllocator = null;
GCHandle IsLoaderAllocatorLive;
static ulong s_collectibleIndex;

[MethodImpl(MethodImplOptions.NoInlining)]
void CallUseTLSStaticFromLoaderAllocator()
{
UseTLSStaticFromLoaderAllocator!();
UseTLSStaticFromLoaderAllocator = null;
}

[MethodImpl(MethodImplOptions.NoInlining)]
bool CheckLALive()
{
return IsLoaderAllocatorLive.Target != null;
}


void ThreadThatWaitsForLoaderAllocatorToDisappear()
{
CallUseTLSStaticFromLoaderAllocator();
while (CheckLALive())
{
GC.Collect(2);
}
}

void CreateLoaderAllocatorWithTLS()
{
ulong collectibleIndex = s_collectibleIndex++;

var ab =
AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName($"CollectibleDerivedAssembly{collectibleIndex}"),
AssemblyBuilderAccess.RunAndCollect);
var mob = ab.DefineDynamicModule($"CollectibleDerivedModule{collectibleIndex}");
var tb =
mob.DefineType(
$"CollectibleDerived{collectibleIndex}",
TypeAttributes.Class | TypeAttributes.Public,
typeof(object));

{
var fb =
tb.DefineField(
"Field", typeof(int), FieldAttributes.Static);
fb.SetCustomAttribute(typeof(ThreadStaticAttribute).GetConstructors()[0], new byte[0]);

var mb =
tb.DefineMethod(
"Method",
MethodAttributes.Public | MethodAttributes.Static);
var ilg = mb.GetILGenerator();
ilg.Emit(OpCodes.Ldc_I4_1);
ilg.Emit(OpCodes.Stsfld, fb);
ilg.Emit(OpCodes.Ret);
}

Type createdType = tb.CreateType();
UseTLSStaticFromLoaderAllocator = (Action)createdType.GetMethods()[0].CreateDelegate(typeof(Action));
IsLoaderAllocatorLive = GCHandle.Alloc(createdType, GCHandleType.WeakTrackResurrection);
}

void ForceCollectibleTLSStaticToGoThroughThreadTermination()
{
int iteration = 0;
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"Iteration {iteration++}");
var createLAThread = new Thread(CreateLoaderAllocatorWithTLS);
createLAThread.Start();
createLAThread.Join();

var crashThread = new Thread(ThreadThatWaitsForLoaderAllocatorToDisappear);
crashThread.Start();
crashThread.Join();
}

}

[Fact]
public static void TestEntryPoint()
{
new CollectibleThreadStaticShutdownRace().ForceCollectibleTLSStaticToGoThroughThreadTermination();
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Needed for mechanical merging of all remaining tests, this particular project may not actually need process isolation -->
<RequiresProcessIsolation>true</RequiresProcessIsolation>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="CollectibleTLSStaticCollection.cs" />
</ItemGroup>
</Project>
3 changes: 3 additions & 0 deletions src/tests/issues.targets
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,9 @@
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/ByRefLocals/*">
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
</ExcludeList>
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleTLSStaticCollection/*">
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
</ExcludeList>
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleStatics/*">
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
</ExcludeList>
Expand Down

0 comments on commit 128321e

Please sign in to comment.