Skip to content

Commit ea5e814

Browse files
github-actions[bot]davidwrightonCopilot
authored
[release/9.0-staging] Fix race condition in cleanup of collectible thread static variables (#111275)
* 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: David Wrighton <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent db5ef46 commit ea5e814

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
@@ -377,7 +377,7 @@ void FreeLoaderAllocatorHandlesForTLSData(Thread *pThread)
377377
#endif
378378
for (const auto& entry : g_pThreadStaticCollectibleTypeIndices->CollectibleEntries())
379379
{
380-
_ASSERTE((entry.TlsIndex.GetIndexOffset() <= pThread->cLoaderHandles) || allRemainingIndicesAreNotValid);
380+
_ASSERTE((entry.TlsIndex.GetIndexOffset() >= pThread->cLoaderHandles) || !allRemainingIndicesAreNotValid);
381381
if (entry.TlsIndex.GetIndexOffset() >= pThread->cLoaderHandles)
382382
{
383383
#ifndef _DEBUG
@@ -390,7 +390,9 @@ void FreeLoaderAllocatorHandlesForTLSData(Thread *pThread)
390390
{
391391
if (pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()] != (LOADERHANDLE)NULL)
392392
{
393-
entry.pMT->GetLoaderAllocator()->FreeHandle(pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()]);
393+
LoaderAllocator *pLoaderAllocator = entry.pMT->GetLoaderAllocator();
394+
if (pLoaderAllocator->IsExposedObjectLive())
395+
pLoaderAllocator->FreeHandle(pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()]);
394396
pThread->pLoaderHandles[entry.TlsIndex.GetIndexOffset()] = (LOADERHANDLE)NULL;
395397
}
396398
}
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
@@ -1010,6 +1010,9 @@
10101010
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/ByRefLocals/*">
10111011
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
10121012
</ExcludeList>
1013+
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleTLSStaticCollection/*">
1014+
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
1015+
</ExcludeList>
10131016
<ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleStatics/*">
10141017
<Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue>
10151018
</ExcludeList>

0 commit comments

Comments
 (0)