Skip to content

Commit 128321e

Browse files
Fix race condition in cleanup of collectible thread static variables (#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]>
1 parent 22e39f9 commit 128321e

File tree

4 files changed

+120
-2
lines changed

4 files changed

+120
-2
lines changed

src/coreclr/vm/threadstatics.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ void FreeLoaderAllocatorHandlesForTLSData(Thread *pThread)
379379
#endif
380380
for (const auto& entry : g_pThreadStaticCollectibleTypeIndices->CollectibleEntries())
381381
{
382-
_ASSERTE((entry.TlsIndex.GetIndexOffset() <= pThread->cLoaderHandles) || allRemainingIndicesAreNotValid);
382+
_ASSERTE((entry.TlsIndex.GetIndexOffset() >= pThread->cLoaderHandles) || !allRemainingIndicesAreNotValid);
383383
if (entry.TlsIndex.GetIndexOffset() >= pThread->cLoaderHandles)
384384
{
385385
#ifndef _DEBUG
@@ -392,7 +392,9 @@ void FreeLoaderAllocatorHandlesForTLSData(Thread *pThread)
392392
{
393393
if (pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()] != (LOADERHANDLE)NULL)
394394
{
395-
entry.pMT->GetLoaderAllocator()->FreeHandle(pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()]);
395+
LoaderAllocator *pLoaderAllocator = entry.pMT->GetLoaderAllocator();
396+
if (pLoaderAllocator->IsExposedObjectLive())
397+
pLoaderAllocator->FreeHandle(pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()]);
396398
pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()] = (LOADERHANDLE)NULL;
397399
}
398400
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Reflection;
6+
using System.Reflection.Emit;
7+
using System.Runtime.CompilerServices;
8+
using System.Runtime.InteropServices;
9+
using System.Threading;
10+
using Xunit;
11+
12+
namespace CollectibleThreadStaticShutdownRace
13+
{
14+
public class CollectibleThreadStaticShutdownRace
15+
{
16+
Action? UseTLSStaticFromLoaderAllocator = null;
17+
GCHandle IsLoaderAllocatorLive;
18+
static ulong s_collectibleIndex;
19+
20+
[MethodImpl(MethodImplOptions.NoInlining)]
21+
void CallUseTLSStaticFromLoaderAllocator()
22+
{
23+
UseTLSStaticFromLoaderAllocator!();
24+
UseTLSStaticFromLoaderAllocator = null;
25+
}
26+
27+
[MethodImpl(MethodImplOptions.NoInlining)]
28+
bool CheckLALive()
29+
{
30+
return IsLoaderAllocatorLive.Target != null;
31+
}
32+
33+
34+
void ThreadThatWaitsForLoaderAllocatorToDisappear()
35+
{
36+
CallUseTLSStaticFromLoaderAllocator();
37+
while (CheckLALive())
38+
{
39+
GC.Collect(2);
40+
}
41+
}
42+
43+
void CreateLoaderAllocatorWithTLS()
44+
{
45+
ulong collectibleIndex = s_collectibleIndex++;
46+
47+
var ab =
48+
AssemblyBuilder.DefineDynamicAssembly(
49+
new AssemblyName($"CollectibleDerivedAssembly{collectibleIndex}"),
50+
AssemblyBuilderAccess.RunAndCollect);
51+
var mob = ab.DefineDynamicModule($"CollectibleDerivedModule{collectibleIndex}");
52+
var tb =
53+
mob.DefineType(
54+
$"CollectibleDerived{collectibleIndex}",
55+
TypeAttributes.Class | TypeAttributes.Public,
56+
typeof(object));
57+
58+
{
59+
var fb =
60+
tb.DefineField(
61+
"Field", typeof(int), FieldAttributes.Static);
62+
fb.SetCustomAttribute(typeof(ThreadStaticAttribute).GetConstructors()[0], new byte[0]);
63+
64+
var mb =
65+
tb.DefineMethod(
66+
"Method",
67+
MethodAttributes.Public | MethodAttributes.Static);
68+
var ilg = mb.GetILGenerator();
69+
ilg.Emit(OpCodes.Ldc_I4_1);
70+
ilg.Emit(OpCodes.Stsfld, fb);
71+
ilg.Emit(OpCodes.Ret);
72+
}
73+
74+
Type createdType = tb.CreateType();
75+
UseTLSStaticFromLoaderAllocator = (Action)createdType.GetMethods()[0].CreateDelegate(typeof(Action));
76+
IsLoaderAllocatorLive = GCHandle.Alloc(createdType, GCHandleType.WeakTrackResurrection);
77+
}
78+
79+
void ForceCollectibleTLSStaticToGoThroughThreadTermination()
80+
{
81+
int iteration = 0;
82+
for (int i = 0; i < 10; i++)
83+
{
84+
Console.WriteLine($"Iteration {iteration++}");
85+
var createLAThread = new Thread(CreateLoaderAllocatorWithTLS);
86+
createLAThread.Start();
87+
createLAThread.Join();
88+
89+
var crashThread = new Thread(ThreadThatWaitsForLoaderAllocatorToDisappear);
90+
crashThread.Start();
91+
crashThread.Join();
92+
}
93+
94+
}
95+
96+
[Fact]
97+
public static void TestEntryPoint()
98+
{
99+
new CollectibleThreadStaticShutdownRace().ForceCollectibleTLSStaticToGoThroughThreadTermination();
100+
}
101+
}
102+
}
103+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<!-- Needed for mechanical merging of all remaining tests, this particular project may not actually need process isolation -->
4+
<RequiresProcessIsolation>true</RequiresProcessIsolation>
5+
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
6+
</PropertyGroup>
7+
<ItemGroup>
8+
<Compile Include="CollectibleTLSStaticCollection.cs" />
9+
</ItemGroup>
10+
</Project>

src/tests/issues.targets

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,6 +1028,9 @@
10281028
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/ByRefLocals/*">
10291029
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
10301030
</ExcludeList>
1031+
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleTLSStaticCollection/*">
1032+
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
1033+
</ExcludeList>
10311034
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleStatics/*">
10321035
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
10331036
</ExcludeList>

0 commit comments

Comments
 (0)