Skip to content

Issue with Thread Local Static On macOS Arm64 #132691

Closed

Description

@LeeHammerton

Description

I had claude investigate some CI failures we were seeing on Burst, while doing so, it discovered the following TLS issue. I have attached a reproduction program+csproj.

Reproduction Steps

Attached the reproduction and proj (proj settings may not be completely needed but the reproduction was created inside another workspace)

tlsRaceRepro.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <AssemblyName>TlsRaceRepro</AssemblyName>
    <RootNamespace>TlsRaceRepro</RootNamespace>

    <!-- Deliberately override the inherited Tools/Burst/Directory.Build.props settings.
         This is a standalone diagnostic, not part of the Burst build. -->
    <LangVersion>latest</LangVersion>
    <Nullable>disable</Nullable>
    <ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>
    <WarningsAsErrors></WarningsAsErrors>
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>

    <!-- Server GC + tiered compilation left at defaults on purpose: we want the same
         runtime configuration bcl.dll runs under. -->
    <InvariantGlobalization>true</InvariantGlobalization>
  </PropertyGroup>

</Project>

Program.cs

// Repro for the CoreCLR thread-statics race that crashes bcl.dll (UUM-149854).
//
// Observed in Burst: two SIGSEGVs out of 5000 bcl runs, both with an identical stack:
//
//     Burst.Compiler.IL.ILVisitor..ctor            (ILVisitor.cs:38, _tlsPendingFunctions.Value)
//       -> System.Threading.ThreadLocal`1.get_Value()
//         -> GetThreadStaticsByIndex / GetThreadLocalStaticBase   <-- null deref
//
// Both faults are a null MethodTable* returned by
// LookupMethodTableForThreadStaticKnownToBeAllocated(): it bounds-checks the index
// against m_maxIndex and then reads pMap[index], but TLSIndexToMethodTableMap::Set
// publishes m_maxIndex before it writes the map slot. A thread that first-touches a
// type's thread statics while another thread is allocating that type's TLS index can
// pass the bounds check and read a still-zero slot.
//
// The key detail that makes this reachable from ILVisitor: statics of a generic type
// are per-instantiation, not per-canonical-form. ThreadLocal<Queue<ILFunction>> and
// ThreadLocal<HashSet<ILFunction>> each get their own TLS index, allocated on first
// touch -- and bcl first touches them from several compilation worker threads at once.
//
// This program reproduces that shape directly: it manufactures a large number of fresh
// generic instantiations and, for each one, releases N threads simultaneously onto its
// very first thread-static access.
//
// Success == the process dies with SIGSEGV. Clean exit means "did not reproduce".

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Threading;

namespace TlsRaceRepro
{
    /// <summary>
    /// Stands in for ILVisitor's thread-static state. One TLS index per instantiation.
    /// Nothing touches _slot before the racing threads do.
    /// </summary>
    internal static class Holder<T> where T : class
    {
        [ThreadStatic] private static object _slot;

        public static object Touch()
        {
            var v = _slot;
            if (v == null)
            {
                v = new object();
                _slot = v;
            }
            return v;
        }
    }

    internal enum Mode
    {
        /// <summary>Plain [ThreadStatic] on a generic type. Fewest moving parts.</summary>
        Holder,
        /// <summary>ThreadLocal&lt;T&gt; -- literally what ILVisitor does.</summary>
        ThreadLocal,
        /// <summary>Alternate between the two.</summary>
        Both,
    }

    internal static class Program
    {
        private static int _threads;
        private static bool _gcPressure;
        private static volatile Func<object> _current;
        private static Barrier _barrier;
        private static long _racesRun;

        private static int Main(string[] args)
        {
            var mode = Mode.Both;
            _threads = Math.Max(4, Environment.ProcessorCount);
            var instantiations = 200_000;
            var batchSize = 2_000;
            var seconds = 120;
            var collectible = true;
            _gcPressure = true;

            for (var i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "--mode": mode = Enum.Parse<Mode>(args[++i], ignoreCase: true); break;
                    case "--threads": _threads = int.Parse(args[++i]); break;
                    case "--instantiations": instantiations = int.Parse(args[++i]); break;
                    case "--batch-size": batchSize = int.Parse(args[++i]); break;
                    case "--seconds": seconds = int.Parse(args[++i]); break;
                    case "--no-gc-pressure": _gcPressure = false; break;
                    case "--non-collectible": collectible = false; break;
                    case "--help":
                    case "-h":
                        PrintHelp();
                        return 0;
                    default:
                        Console.Error.WriteLine($"unknown argument: {args[i]}");
                        PrintHelp();
                        return 2;
                }
            }

            Console.WriteLine($"runtime      : {RuntimeInformation.FrameworkDescription}");
            Console.WriteLine($"os/arch      : {RuntimeInformation.OSDescription} {RuntimeInformation.ProcessArchitecture}");
            Console.WriteLine($"mode         : {mode}");
            Console.WriteLine($"racing thrds : {_threads}");
            Console.WriteLine($"instantiations: {instantiations} (batches of {batchSize})");
            Console.WriteLine($"gc pressure  : {_gcPressure}");
            Console.WriteLine($"collectible  : {collectible}");
            Console.WriteLine($"time limit   : {seconds}s");
            Console.WriteLine("If this reproduces, the process dies with SIGSEGV and prints nothing further.");
            Console.WriteLine();

            // Racing threads are dedicated OS threads, created once. Using the thread
            // pool here would be closer to bcl, but the pool's own thread statics warm
            // up as it grows, which pollutes the very first-touch window we care about.
            _barrier = new Barrier(_threads + 1);
            for (var i = 0; i < _threads; i++)
            {
                var t = new Thread(RaceWorker, 512 * 1024) { IsBackground = true, Name = $"race-{i}" };
                t.Start();
            }

            if (_gcPressure)
            {
                new Thread(GcPressure, 512 * 1024) { IsBackground = true, Name = "gc-pressure" }.Start();
            }

            var sw = Stopwatch.StartNew();
            var done = 0;
            var batchIndex = 0;

            while (done < instantiations && sw.Elapsed.TotalSeconds < seconds)
            {
                var count = Math.Min(batchSize, instantiations - done);

                // A collectible ALC per batch. Dropping it churns collectible TLS index
                // cleanup concurrently with the next batch's allocations, which is the
                // other half of the map's mutation traffic.
                // --non-collectible removes the unload traffic entirely, to show the
                // race does not depend on collectible thread-static cleanup.
                var alc = collectible
                    ? new AssemblyLoadContext($"markers-{batchIndex}", isCollectible: true)
                    : null;
                var markers = EmitMarkerTypes(alc, batchIndex, count, collectible);

                foreach (var marker in markers)
                {
                    var useThreadLocal = mode switch
                    {
                        Mode.Holder => false,
                        Mode.ThreadLocal => true,
                        _ => (done & 1) == 1,
                    };

                    // Built on this thread, deliberately: only the *access* must race,
                    // and we must not touch the thread statics before the barrier opens.
                    var touch = useThreadLocal ? MakeThreadLocalTouch(marker) : MakeHolderTouch(marker);

                    _current = touch;
                    _barrier.SignalAndWait();   // release all racing threads at once
                    _barrier.SignalAndWait();   // wait for them to come back

                    done++;
                }

                markers = null;
                alc?.Unload();
                batchIndex++;

                if (batchIndex % 5 == 0)
                {
                    GC.Collect();
                    Console.WriteLine($"  {done,8} instantiations raced, {sw.Elapsed.TotalSeconds,6:F1}s elapsed");
                }
            }

            Console.WriteLine();
            Console.WriteLine($"did NOT reproduce: {done} instantiations x {_threads} threads " +
                              $"= {Interlocked.Read(ref _racesRun)} first-touch races in {sw.Elapsed.TotalSeconds:F1}s");
            return 0;
        }

        private static void PrintHelp()
        {
            Console.WriteLine("usage: TlsRaceRepro [--mode holder|threadlocal|both] [--threads N]");
            Console.WriteLine("                    [--instantiations N] [--batch-size N] [--seconds N]");
            Console.WriteLine("                    [--no-gc-pressure] [--non-collectible]");
            Console.WriteLine();
            Console.WriteLine("Exit 0 = did not reproduce. A SIGSEGV = reproduced.");
        }

        private static void RaceWorker()
        {
            while (true)
            {
                _barrier.SignalAndWait();
                var f = _current;
                try
                {
                    f();
                }
                catch (Exception)
                {
                    // A managed exception is not what we are hunting; keep racing.
                }
                Interlocked.Increment(ref _racesRun);
                _barrier.SignalAndWait();
            }
        }

        private static void GcPressure()
        {
            // Both real crashes landed while a GC was in flight (SuspendAllThreads in one
            // core, background GC in the other), so keep the collector busy throughout.
            var sink = new object[64];
            var n = 0;
            while (true)
            {
                sink[n++ & 63] = new byte[8 * 1024];
                if ((n & 0xFFF) == 0)
                {
                    GC.Collect(0, GCCollectionMode.Forced, blocking: false);
                }
            }
        }

        /// <summary>
        /// Emits <paramref name="count"/> distinct, empty reference types. They exist only
        /// to give us distinct generic instantiations, each of which gets its own TLS index.
        /// </summary>
        private static Type[] EmitMarkerTypes(AssemblyLoadContext alc, int batchIndex, int count, bool collectible)
        {
            var name = new AssemblyName($"TlsRaceMarkers{batchIndex}");
            var access = collectible ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run;
            AssemblyBuilder ab;

            if (alc != null)
            {
                using (alc.EnterContextualReflection())
                {
                    ab = AssemblyBuilder.DefineDynamicAssembly(name, access);
                }
            }
            else
            {
                ab = AssemblyBuilder.DefineDynamicAssembly(name, access);
            }

            var mb = ab.DefineDynamicModule("m");
            var types = new Type[count];
            for (var i = 0; i < count; i++)
            {
                var tb = mb.DefineType($"M{i}", TypeAttributes.Public | TypeAttributes.Class);
                types[i] = tb.CreateType();
            }
            return types;
        }

        private static readonly MethodInfo HolderTouchFactory =
            typeof(Program).GetMethod(nameof(MakeHolderTouchCore), BindingFlags.NonPublic | BindingFlags.Static);

        private static readonly MethodInfo ThreadLocalTouchFactory =
            typeof(Program).GetMethod(nameof(MakeThreadLocalTouchCore), BindingFlags.NonPublic | BindingFlags.Static);

        private static Func<object> MakeHolderTouch(Type marker) =>
            (Func<object>)HolderTouchFactory.MakeGenericMethod(marker).Invoke(null, null);

        private static Func<object> MakeThreadLocalTouch(Type marker) =>
            (Func<object>)ThreadLocalTouchFactory.MakeGenericMethod(marker).Invoke(null, null);

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static Func<object> MakeHolderTouchCore<T>() where T : class => Holder<T>.Touch;

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static Func<object> MakeThreadLocalTouchCore<T>() where T : class
        {
            // Exactly ILVisitor's shape: a static ThreadLocal<T> over a reference type,
            // whose .Value is first read from several threads at once.
            var tl = new ThreadLocal<T>(() => null);
            return () => tl.Value;
        }
    }
}

Expected behavior

The program should complete successfully on both windows and macos - Output from successful run

runtime      : .NET 10.0.11
os/arch      : Microsoft Windows 10.0.26100 X64
mode         : Both
racing thrds : 64
instantiations: 200000 (batches of 2000)
gc pressure  : True
collectible  : True
time limit   : 120s
If this reproduces, the process dies with SIGSEGV and prints nothing further.

     10000 instantiations raced,   32.2s elapsed
     20000 instantiations raced,   66.6s elapsed
     30000 instantiations raced,  101.7s elapsed

did NOT reproduce: 36000 instantiations x 64 threads = 2304000 first-touch races in 124.8s

Actual behavior

From a Macos arm64 run :

Failure example :

runtime      : .NET 10.0.9
os/arch      : macOS 26.5.2 Arm64
mode         : Both
racing thrds : 16
instantiations: 200000 (batches of 2000)
gc pressure  : True
collectible  : True
time limit   : 120s
If this reproduces, the process dies with SIGSEGV and prints nothing further.

zsh: segmentation fault  ./bin/Release/net10.0/TlsRaceRepro

Looking in the macOS Console app, this is the stack for the crashing thread:

Thread 12 Crashed:: race-1
0   libcoreclr.dylib              	       0x1061fbb9c MethodTable::CheckRunClassInitThrowing() + 0
1   libcoreclr.dylib              	       0x1062b85f0 GetThreadStaticsByIndex + 100
2   ???                           	       0x1082e2668 ???
3   ???                           	       0x1082e47d4 ???
4   ???                           	       0x1082d82b4 ???
5   ???                           	       0x1073ea4b4 ???
6   libcoreclr.dylib              	       0x1063d458c CallDescrWorkerInternal + 132
7   libcoreclr.dylib              	       0x10626c510 DispatchCallSimple(unsigned long*, unsigned int, unsigned long, unsigned int) + 276
8   libcoreclr.dylib              	       0x10627fc04 KickOffThread_Worker(void*) + 144
9   libcoreclr.dylib              	       0x10623d8a0 ManagedThreadBase::KickOff(void (*)(void*), void*) + 236
10  libcoreclr.dylib              	       0x10627e040 KickOffThread(void*) + 212
11  libcoreclr.dylib              	       0x106413bf0 CorUnix::CPalThread::ThreadEntry(void*) + 352
12  libsystem_pthread.dylib       	       0x18c29dc58 _pthread_start + 136
13  libsystem_pthread.dylib       	       0x18c298c1c thread_start + 8

Regression?

Unknown

Known Workarounds

Worked around the race in Burst by initialising the TLS collections single threaded (via warmup)

Configuration

.NET 10
macOS Arm64 Tahoe 26.6.2
Unknown if it affects other platforms or architectures, so far i have not seen the failure on windows.

Other information

No response

Activity

  1. added
    untriaged
    on Aug 24, 2026
  2. added
    area-CodeGen-coreclr
    on Aug 24, 2026
  3. dotnet-policy-service commented on Aug 24, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. MihuBot commented on Aug 24, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  5. EgorBo commented on Aug 24, 2026

    @EgorBo
    Member

    Possibly fixed by #127843

    @LeeHammerton could you please try to repro with the latest .NET 10.0 ? (10.0.12)

  6. removed
    untriaged
    on Aug 24, 2026
  7. added this to the 10.0.x milestone on Aug 24, 2026
  8. LeeHammerton commented on Aug 26, 2026

    @LeeHammerton
    Author

    As far as I can tell, latest .net 10 no longer reproduces this, so it looks like #127776 fixes also fixed this instance.
    Thankyou

  9. JulieLeeMSFT commented on Aug 26, 2026

    @JulieLeeMSFT
    Member

    Closing as resolved.

  10. locked and limited conversation to collaborators on Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclr

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions