Repository navigation
Description
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.
-
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"); }
-
Wait for
READY, then 3 s more. Keep reading the app's stdout from here on, and note when eachHBline arrives. -
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
initializewithadapterID: "coreclr",linesStartAt1: trueandcolumnsStartAt1: true, and wait for the reply. - Send
attachwithtype: "coreclr",request: "attach", the app'sprocessIdandjustMyCode: false; do not wait for its reply. - On
initialized, sendsetExceptionBreakpointswithfilters: ["all"]and wait for the reply. - Send
configurationDoneand wait for the reply.
- Start netcoredbg with
-
Collect 30
stoppedevents, within 120 s of sendingattach. At each, take the event'sthreadId. SendstackTracewith thatthreadIdandlevels: 3, and wait for the reply. Then sendexceptionInfowith the samethreadId, and wait for the reply. Sendcontinuefor that thread after stops 1 to 29, without waiting for its reply; leave the process stopped at the 30th. -
At the 30th stop, send
setExceptionBreakpointswith no filters and wait for the reply. Then senddisconnectwithterminateDebuggee: falseand wait for the reply. -
Start the clock when the
disconnectreply arrives or its 30 s wait ends. Watch the app's stdout for 10 s, and ignoreHBlines from the first 2 s. Count the trial as a hang if no laterHBline arrived. -
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 = TRUEandm_isBlockedOnGarbageCollectionEvent = FALSE.- The exception-reporting thread was blocked in
WaitSuspendEventsduring a GC-mode transition after the first-chance send. - In one dump, a thread was still in
SendExceptionHelperAndBlockat~GCHolderEEInterfaceduringSENDIPCEVENT_END, after the trap call.TrapAllRuntimeThreadsitself 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
disconnectreply: 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
continueafter 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
dotnet-policy-service commentedon Nov 4, 2026
Tagging subscribers to this area: @steveisok, @tommcdon, @dotnet/dotnet-diag
See info in area-owners.md if you want to be subscribed.