Skip to content

Debugger: an exception thrown during detach can suspend the runtime with no debugger attached #136954

Description

@pcshrosbree

TL;DR: Detaching a debugger while threads are throwing exceptions can leave managed execution stopped after the debugger has exited, with nothing to resume it. A one-line attachment check at each of two sites reduced hangs from 16 of 49 detaches to 0 of 48 in my tests. I can open a PR with this check: should it also skip sending the exception events after a detach?

Description

Debugger::SendException checks CORDebuggerAttached() and then calls SendExceptionEventsWorker. For a first-chance or unhandled exception, the worker sends the events through SendExceptionHelperAndBlock. That function enters SENDIPCEVENT_BEGIN, sends two events and, if the last send succeeded, calls TrapAllRuntimeThreads(). There is no attachment check under the event-sending lock before the trap. The DEBUG_EXCEPTION_USER_FIRST_CHANCE block in SendExceptionEventsWorker has the same shape.

A thread can pass the attachment check and then block on the locks in SENDIPCEVENT_BEGIN. That macro takes the thread-store lock, then LockForEventSending takes the debugger lock. When the process is stopped, the detach handler holds the thread-store lock until it resumes the threads. The detach (DB_IPCE_DETACH_FROM_PROCESS → MarkDebuggerUnattachedInternal) clears DBCF_ATTACHED. If the detach completes before the sender gets the locks, the sender still sends the events and, if the send succeeded, calls TrapAllRuntimeThreads(). When that sync completes, SendSyncCompleteIPCEvent calls MarkDebuggerAttachedInternal, which sets DBCF_ATTACHED again. No debugger is connected to send the continue. The source and the dump state below are consistent with this interleaving.

Debugger::AppDomainCreated already guards against this case:

    SENDIPCEVENT_BEGIN(this, pThread);

    // We may have detached while waiting in LockForEventSending,
    // in which case we can't send the event.
    if (CORDebuggerAttached())

SendCatchHandlerFound and the unwind path also check CORDebuggerAttached() inside their SENDIPCEVENT_BEGIN blocks. The two exception sites above do not.

Reproduction steps

Environment: Linux x64, Microsoft.NETCore.App 10.0.13. The debugger was an unmodified netcoredbg build that reports NET Core debugger 3.2.0-1 (refs/heads/main, Release); its binary's SHA-256 was 72d26ad64394ef0df77222c18957f6dd58d5b65368fc39f9547b7a13122ac965. No profiler was loaded.

  1. Build this app as a .NET 10 console project with implicit usings, in Debug, and run the built DLL:

    using System.Runtime.CompilerServices;
    
    long caught = 0;
    for (int i = 0; i < 32; i++)
    {
        new Thread(() =>
        {
            while (true)
            {
                try { Thrower.Throw(); }
                catch (InvalidOperationException) { Interlocked.Increment(ref caught); }
                Thread.Sleep(2);
            }
        }) { IsBackground = true }.Start();
    }
    Console.WriteLine("READY " + Environment.ProcessId);
    var sw = System.Diagnostics.Stopwatch.StartNew();
    while (true)
    {
        Console.WriteLine("HB " + sw.ElapsedMilliseconds + " " + Interlocked.Read(ref caught));
        Thread.Sleep(250);
    }
    
    static class Thrower
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void Throw() => throw new InvalidOperationException("boom");
    }
  2. Wait for READY, then 3 s more. Keep reading the app's stdout from here on, and note when each HB line arrives.

  3. In the steps below, "wait for the reply" means wait until a response arrives or 30 s pass, then go on either way, even if the response is not a success.

    • Start netcoredbg with --interpreter=vscode.
    • Send initialize with adapterID: "coreclr", linesStartAt1: true and columnsStartAt1: true, and wait for the reply.
    • Send attach with type: "coreclr", request: "attach", the app's processId and justMyCode: false; do not wait for its reply.
    • On initialized, send setExceptionBreakpoints with filters: ["all"] and wait for the reply.
    • Send configurationDone and wait for the reply.
  4. Collect 30 stopped events, within 120 s of sending attach. At each, take the event's threadId. Send stackTrace with that threadId and levels: 3, and wait for the reply. Then send exceptionInfo with the same threadId, and wait for the reply. Send continue for that thread after stops 1 to 29, without waiting for its reply; leave the process stopped at the 30th.

  5. At the 30th stop, send setExceptionBreakpoints with no filters and wait for the reply. Then send disconnect with terminateDebuggee: false and wait for the reply.

  6. Start the clock when the disconnect reply arrives or its 30 s wait ends. Watch the app's stdout for 10 s, and ignore HB lines from the first 2 s. Count the trial as a hang if no later HB line arrived.

  7. End the app and the debugger if either is still running. Repeat with a fresh app and debugger each time; the race is intermittent.

Expected behavior

The app keeps printing HB lines after the detach.

Actual behavior

In the test below, 16 of 49 unpatched trials met the hang criterion in step 6.

Four earlier dumps of hung processes, on the stock runtime, showed the following after netcoredbg had detached and exited:

  • g_CORDebuggerControlFlags = 0x200 (DBCF_ATTACHED), m_stopped = TRUE, m_trappingRuntimeThreads = TRUE and m_isBlockedOnGarbageCollectionEvent = FALSE.
  • The exception-reporting thread was blocked in WaitSuspendEvents during a GC-mode transition after the first-chance send.
  • In one dump, a thread was still in SendExceptionHelperAndBlock at ~GCHolderEEInterface during SENDIPCEVENT_END, after the trap call. TrapAllRuntimeThreads itself was not on the stack.
  • Other threads were waiting for the thread-store lock in SendCatchHandlerFound.

Test results

I built two runtimes locally from v10.0.13. They differ only in the change below: the DAC and DBI were byte-identical, and each trial recorded the libcoreclr.so it loaded. The test had 50 rounds, each running one unpatched trial and then one patched trial. The table counts trials that reached the 30th stop.

Runtime Hung
unpatched 16 of 49
with the check below 0 of 48

One-sided Fisher exact p = 4.2 × 10⁻⁶.

  • Five of these trials got no successful disconnect reply: two unpatched hangs and three patched trials that did not hang. Counting only successful replies gives 14 of 47 against 0 of 45 (p = 2.7 × 10⁻⁵).
  • Three trials ended event collection with fewer than 30 stops. The driver had sent continue after the last stop it saw in each trial, so these trials did not detach at the 30th stop as the steps describe. They are excluded above. All three hung, two of them on the patched runtime. The driver did not record whether the process was running or stopped when they detached, so I can't say why they hung.
  • In a separate control setup on the stock runtime, I cleared the exception filters, stopped the app's throwing, continued, waited 1.5 s, paused on a thread, then detached. None of 12 trials hung. The app above has no way to stop its throwing; the control used a variant that does.

Possible fix

In SendExceptionHelperAndBlock, and in the DEBUG_EXCEPTION_USER_FIRST_CHANCE block of SendExceptionEventsWorker, check CORDebuggerAttached() again under the event-sending lock before trapping:

-    if (SUCCEEDED(hr))
+    if (SUCCEEDED(hr) && CORDebuggerAttached())
     {
         // Stop all Runtime threads
         TrapAllRuntimeThreads();
     }

The first site covers both the first-chance and the unhandled callers of the helper. This change does not stop the event sends after a detach. Skipping the whole event block, as AppDomainCreated does, may be the cleaner form. My tests used the all-exceptions filter with justMyCode: false, so they do not exercise the Just My Code or unhandled-exception paths separately.

Note

This issue was prepared with AI assistance (Anthropic Claude, checked by OpenAI Codex) at my request. I reviewed it and the test results before filing.

Activity

  1. added
    untriaged
    on Nov 4, 2026
  2. dotnet-policy-service commented on Nov 4, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @steveisok, @tommcdon, @dotnet/dotnet-diag
    See info in area-owners.md if you want to be subscribed.

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-Diagnostics-coreclruntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions