runtime: CoreCLR crash under heavy load when using custom host on Windows

Description

When using a custom host (nethost/hostfxr) on Windows, I experience intermittent crashes when my program is under heavy GC load (in my case, specifically in a code path that creates a lot of short-lived byte arrays). This was also independently observed at https://github.com/Reloaded-Project/Reloaded-II/issues/588.

Reproduction Steps

I don’t have exact reproduction steps available for this crash, as it’s not 100% consistent, but here’s what I’ve observed so far:

  1. This seems to only happen on custom hosts - I can’t get this to happen in a standard C# console application. In all cases I’ve observed this crash, it’s been from a C# library loaded in a C++ application using hostfxr.
  2. Applications seem to crash semi-consistently when making large amounts of allocations, which leads me to think it’s GC related. While I haven’t had much success trying to intentionally trigger the crash, @Sewer56 was able to reproduce a crash in their codebase fairly easily with this snippet:
for (int x = 0; x < 10000; x++)
{
    var buf = new byte[1337];
    GC.Collect();
}
  1. I was unable to get a MRE in a C++ console application using hostfxr, so there’s likely something more at play here.

I apologize for the vague reproduction steps, this bug is quite elusive and I hope to find a proper MRE soon. Hopefully there might be some ideas on how to reproduce this from a .NET team member?

Expected behavior

The runtime should not crash.

Actual behavior

The program displays the message Fatal error. Internal CLR error. (0x80131506) (COR_E_EXECUTIONENGINE) in standard output and then crashes with STATUS_ACCESS_VIOLATION dereferencing a null pointer. While I can’t upload the entire minidump here (it contains sensitive information), here’s a snippet from WinDbg (referenced source is the commit linked below):

FAULTING_SOURCE_LINE:  D:\code\csharp\crashrepro\runtime\src\coreclr\gc\gc.cpp

FAULTING_SOURCE_FILE:  D:\code\csharp\crashrepro\runtime\src\coreclr\gc\gc.cpp

FAULTING_SOURCE_LINE_NUMBER:  41333

FAULTING_SOURCE_CODE:  
 11606: inline size_t my_get_size (Object* ob)
 11607: {
 11608:     MethodTable* mT = header(ob)->GetMethodTable();
 11609: 
>11610:     return (mT->GetBaseSize() +
 11611:             (mT->HasComponentSize() ?
 11612:              ((size_t)((CObjectHeader*)ob)->GetNumComponents() * mT->RawGetComponentSize()) : 0));
 11613: }
 11614: 
 11615: #define size(i) my_get_size (header(i))


SYMBOL_NAME:  coreclr!WKS::gc_heap::find_first_object+e8

Regression?

This started happening with .NET 9.0.5 and previously worked on .NET 9.0.4.

Known Workarounds

None, beyond pinning to 9.0.4.

Configuration

  • Version: .NET 9.0.5, .NET 9.0.6, .NET 10 Preview 5
  • OS: Windows 11 23H2 (22631.5189)
  • Architecture: x64

Other information

A git bisect led me to https://github.com/dotnet/runtime/commit/0fb125acfb165229d55976349adf8f510b9fb3b0 as the first bad commit, which matches my testing (the commit before https://github.com/dotnet/runtime/commit/92262983b92920487bc819dcc4d6948b4e1e3b24 is good). I’ve also heard from a friend that this started with .NET 10 Preview 3, and while I haven’t tested the reproduction case myself, that lines up (https://github.com/dotnet/runtime/commit/fa3beb9521adb450863f3460d0e71bc0c5498d02).

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Reactions: 6
  • Comments: 17 (13 by maintainers)

Most upvoted comments

Reproduction: Start from official sample https://github.com/dotnet/samples/tree/main/core/hosting.

Change nativehost.cpp:

int __cdecl wmain(int argc, wchar_t *argv[])
{
    // Get the current executable's directory
    char_t host_path[MAX_PATH];
    auto size = ::GetFullPathNameW(argv[0], sizeof(host_path) / sizeof(char_t), host_path, nullptr);
    assert(size != 0);

    string_t root_path = host_path;
    auto pos = root_path.find_last_of(DIR_SEPARATOR);
    assert(pos != string_t::npos);
    root_path = root_path.substr(0, pos + 1);

    int result = EXIT_FAILURE;
    std::thread t([&]() {
        if (!load_hostfxr(nullptr)) {
            assert(false && "Failure: load_hostfxr()");
            return;
        }

        const string_t config_path = root_path + STR("DotNetLib.runtimeconfig.json");
        load_assembly_and_get_function_pointer_fn load_assembly_and_get_function_pointer = nullptr;
        load_assembly_and_get_function_pointer = get_dotnet_load_assembly(config_path.c_str());
        assert(load_assembly_and_get_function_pointer != nullptr && "Failure: get_dotnet_load_assembly()");
        // STEP 3: Load managed assembly and get function pointer to a managed method
        const string_t dotnetlib_path = root_path + STR("DotNetLib.dll");
        const char_t *dotnet_type = STR("DotNetLib.Lib, DotNetLib");
        const char_t *dotnet_type_method = STR("Hello");
        component_entry_point_fn hello = nullptr;
        int rc = load_assembly_and_get_function_pointer(
            dotnetlib_path.c_str(),
            dotnet_type,
            dotnet_type_method,
            nullptr,
            nullptr,
            (void**)&hello);
        assert(rc == 0 && hello != nullptr && "Failure: load_assembly_and_get_function_pointer()");

        struct lib_args {
            const char_t *message;
            int number;
        };
        lib_args args { STR("from host thread!"), 42 };
        hello(&args, sizeof(args));
        result = EXIT_SUCCESS;
    });
    t.join();

    system("pause");
    return result;
}

Change Lib.cs:

public static int Hello(IntPtr arg, int argLength)
{
    if (argLength < System.Runtime.InteropServices.Marshal.SizeOf(typeof(LibArgs)))
    {
        return 1;
    }

    LibArgs libArgs = Marshal.PtrToStructure<LibArgs>(arg);
    System.Threading.Tasks.Task.Run(() =>
    {
        while (true)
        {
            Console.WriteLine($"Hello, world! from {nameof(Lib)} {new byte[555]}");
            PrintLibArgs(libArgs);
        }
    });

    return 0;
}

This application crashes every time on .NET 9 with the following stack trace. It does not crash on .NET 8

Hello, world! from Lib System.Byte[]
-- message: from host thread!
-- number: 42
Hello, world! from Lib System.Byte[]
-- message: from host thread!
-- number: 42
Hello, world! from Lib System.Byte[]
-- message: from host thread!
-- number: 42
Fatal error. Internal CLR error. (0x80131506)
   at System.String.Ctor(System.ReadOnlySpan`1<Char>)
   at System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()
   at DotNetLib.Lib+<>c__DisplayClass2_0.<Hello>b__0()
   at System.Threading.Tasks.Task`1[[System.__Canon, System.Private.CoreLib, Version=9.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].InnerInvoke()
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread, System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef, System.Threading.Thread)
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()

Ok we will port https://github.com/dotnet/runtime/pull/115546 to 9. @NotNite, can you please confirm that your test doesnt fail on latest .NET 10 previews?

That actually makes a lot of sense in context, also regarding why it was hard to reproduce before.

In some of our projects which were affected, people loading the code were doing so via DLL Injection, i.e. using CreateRemoteThread under the hood. (inject a native bootstrapper which then loads .NET)

In that case, the spawned thread would exit after everything was loaded, triggering the bug; as opposed to say, something closer to apphost, where everything kicks off from the main thread.

Do you have tips on debugging where this happens?

If possible, the best way to debug this is using time-travel debugger built into windbg: https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-overview

Once you collect the time travel trace, set a write breakpoint on the thread allocation context that’s gone and run back to see where that allocation context got created.

The call stack leading up to the crash looks like this:

[0x23]   coreclr!EEPolicy::HandleFatalError+0x133   0xae7dba0   0x7ffb78805920   
[0x24]   coreclr!ProcessCLRExceptionNew+0x108   0xae7e1a0   0x7ffb7880508c   
[0x25]   coreclr!ProcessCLRException+0x3c   0xae7e1f0   0x7ffc0ee128bf   
[0x26]   ntdll!RtlpExecuteHandlerForException+0xf   0xae7e3c0   0x7ffc0edc2554   
[0x27]   ntdll!RtlDispatchException+0x244   0xae7e3f0   0x7ffc0ee113ce   
[0x28]   ntdll!KiUserExceptionDispatch+0x2e   0xae7eb00   0x7ffb7858fae1   
[0x29]   coreclr!WKS::CObjectHeader::SetFree+0xb   (Inline Function)   (Inline Function)   
[0x2a]   coreclr!WKS::gc_heap::make_unused_array+0x39   0xae7f210   0x7ffb78648ab7   
[0x2b]   coreclr!WKS::gc_heap::fix_allocation_context+0x5f   0xae7f250   0x7ffb78648a50   
[0x2c]   coreclr!WKS::GCHeap::FixAllocContext+0x20   0xae7f280   0x7ffb78655708   
[0x2d]   coreclr!WKS::fix_alloc_context+0x28   0xae7f2b0   0x7ffb785fea8d   
[0x2e]   coreclr!GCToEEInterface::GcEnumAllocContexts+0x51   0xae7f2f0   0x7ffb78585503   
[0x2f]   coreclr!WKS::gc_heap::fix_allocation_contexts+0x1f   0xae7f320   0x7ffb78584d5a   
[0x30]   coreclr!WKS::gc_heap::garbage_collect+0x36   0xae7f360   0x7ffb78587d36   
[0x31]   coreclr!WKS::GCHeap::GarbageCollectGeneration+0x13e   0xae7f3b0   0x7ffb78667622   
[0x32]   coreclr!WKS::gc_heap::trigger_gc_for_alloc+0x26   0xae7f410   0x7ffb786a1888   
[0x33]   coreclr!WKS::gc_heap::try_allocate_more_space+0x4df4c   0xae7f440   0x7ffb78653915   
[0x34]   coreclr!WKS::gc_heap::allocate_more_space+0x31   0xae7f4a0   0x7ffb7858fe47   
[0x35]   coreclr!WKS::gc_heap::allocate+0x64   (Inline Function)   (Inline Function)   
[0x36]   coreclr!WKS::GCHeap::Alloc+0x97   0xae7f4d0   0x7ffb7855f2f1   
[0x37]   coreclr!Alloc+0x7f   (Inline Function)   (Inline Function)   
[0x38]   coreclr!AllocateObject+0x101   0xae7f510   0x7ffb7855f14d   
[0x39]   coreclr!AllocateObject+0xd   (Inline Function)   (Inline Function)   
[0x3a]   coreclr!JIT_New+0xdd   0xae7f5a0   0x7ffb19bdec40   
[0x3b]   Ryo_Reloaded!Ryo.Reloaded.CRI.CriAtomEx.CriAtomEx.Player_Create+0x200   0xae7f700   0x7ffb1aa94243   
[0x3c]   Reloaded_Mod_Loader!ILStubClass.IL_STUB_ReversePInvoke(Ryo.Definitions.Structs.CriAtomExPlayerConfigTag*, System.Void*, Int32)+0x53   0xae7f7f0   0x147bfdcc0   

Given that https://github.com/dotnet/runtime/commit/0fb125acfb165229d55976349adf8f510b9fb3b0 is responsible for the change in behavior, and that the call stack is extremely similar to #110442, it suggests the cause is similar to https://github.com/dotnet/winforms/pull/12631: the thread exit notification is being lost, leaving invalid entries in the thread store.

Do you have tips on debugging where this happens? It’s still unclear to us whether the native application is using an FLS callback as in the COM scenario.

@Sewer56 was able to reproduce a crash in their codebase fairly easily with this snippet:

That was actually @nenkai , after I asked them to put some GC pressure, as the crash point around Windows Crash Dumps was around the GC in native parts of the runtime. It doesn’t cause the issue, but just increases probability; at least from what I’ve heard so far. Testing on my own end has been limited; after all, I needed to spend a full weekend getting thousands of users to an earlier runtime; writing a bunch of code to check, install, etc. for an emergency workaround.

It’s been hard to get a MRE for this; but essentially, from our observations so far it was:

nethost+hostfxr -> .NET Library -> Create Threads + ALCs -> Chance of Crash

That on itself seems fine, but once you get additional Threads and AssemblyLoadContext(s) involved; things just fall apart. Having another peek, it’s more likely thread related (edit: Seems like it’s an issue deallocating on the finalizer thread?), but we’ve not got around to finding out the details yet.