1
0
Fork 0

Fallback pause using breakin thread

This commit is contained in:
Duncan Ogilvie 2026-07-15 15:38:14 +02:00
parent 4a61e42280
commit f2d57e2eeb
7 changed files with 106 additions and 2 deletions

View File

@ -416,6 +416,21 @@ bool cbDebugPause(int argc, char* argv[])
dputs(QT_TRANSLATE_NOOP("DBG", "Program is not running")); dputs(QT_TRANSLATE_NOOP("DBG", "Program is not running"));
return false; return false;
} }
// If the previous pause request could not break the debuggee and no debug
// events happened since, the debuggee is stuck in a wait that the code
// below cannot interrupt. Requesting a pause again after a few seconds
// falls back to a break-in thread. This is not done right away because the
// extra thread can be used by the debuggee to detect the debugger.
static ULONGLONG lastPauseRequestTime = 0;
static duint lastPauseRequestEventCount = 0;
auto now = GetTickCount64();
auto stuck = lastPauseRequestTime != 0
&& now - lastPauseRequestTime >= 2000
&& dbggetdbgeventcount() == lastPauseRequestEventCount;
lastPauseRequestTime = now;
lastPauseRequestEventCount = dbggetdbgeventcount();
if(stuck && dbgspawnbreakinthread())
return true;
// After attaching, the active thread is whatever thread reported the last // After attaching, the active thread is whatever thread reported the last
// attach event (usually an idle worker that never wakes up). Target the // attach event (usually an idle worker that never wakes up). Target the
// main thread instead until a real debug event selects an active thread. // main thread instead until a real debug event selects an active thread.

View File

@ -53,6 +53,8 @@ static duint stepRepeat = 0;
static bool bIsAttached = false; static bool bIsAttached = false;
static bool bPauseAtAttach = false; static bool bPauseAtAttach = false;
static DWORD dwAttachMainThread = 0; static DWORD dwAttachMainThread = 0;
static bool bBreakInExpected = false;
static volatile long DbgEventsTotal = 0;
static bool bSkipExceptions = false; static bool bSkipExceptions = false;
static duint skipExceptionCount = 0; static duint skipExceptionCount = 0;
static bool bFreezeStack = false; static bool bFreezeStack = false;
@ -355,6 +357,26 @@ void dbgclearattachmainthread()
dwAttachMainThread = 0; dwAttachMainThread = 0;
} }
duint dbggetdbgeventcount()
{
return (duint)DbgEventsTotal;
}
bool dbgspawnbreakinthread()
{
// Set the expectation before creating the thread, because the breakpoint
// event can arrive before DebugBreakProcess returns.
bBreakInExpected = true;
if(!DebugBreakProcess(fdProcessInfo->hProcess))
{
bBreakInExpected = false;
dputs(QT_TRANSLATE_NOOP("DBG", "Failed to create a break-in thread (DebugBreakProcess)"));
return false;
}
dputs(QT_TRANSLATE_NOOP("DBG", "Created a break-in thread to pause the debuggee"));
return true;
}
void dbgsetresumetid(duint tid) void dbgsetresumetid(duint tid)
{ {
tidToResume = tid; tidToResume = tid;
@ -2148,6 +2170,29 @@ static void cbException(EXCEPTION_DEBUG_INFO* ExceptionData)
GuiSetLastException(ExceptionCode); GuiSetLastException(ExceptionCode);
lastExceptionInfo = *ExceptionData; lastExceptionInfo = *ExceptionData;
if(bBreakInExpected && ExceptionCode == EXCEPTION_BREAKPOINT && ExceptionData->dwFirstChance)
{
// The pause command spawned a break-in thread, treat its breakpoint
// as a pause instead of a debuggee exception.
bBreakInExpected = false;
dbgsetcontinuestatus(DBG_CONTINUE);
dputs(QT_TRANSLATE_NOOP("DBG", "paused!"));
auto CIP = GetContextDataEx(hActiveThread, UE_CIP);
DebugUpdateGuiSetStateAsync(CIP, paused);
_dbg_animatestop(); // Stop animating when paused
// Trace record
dbgtraceexecute(CIP);
//lock
lock(WAITID_RUN);
// Plugin callback
PLUG_CB_PAUSEDEBUG pauseInfo = { nullptr };
plugincbcall(CB_PAUSEDEBUG, &pauseInfo);
dbgsetforeground();
dbgsetskipexceptions(false);
wait(WAITID_RUN);
return;
}
duint addr = (duint)ExceptionData->ExceptionRecord.ExceptionAddress; duint addr = (duint)ExceptionData->ExceptionRecord.ExceptionAddress;
{ {
BREAKPOINT bp; BREAKPOINT bp;
@ -2245,6 +2290,7 @@ static void cbDebugEvent(DEBUG_EVENT* DebugEvent)
if(DebugEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT) if(DebugEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
dwAttachMainThread = 0; //an exception makes the active thread meaningful, stop overriding the pause target dwAttachMainThread = 0; //an exception makes the active thread meaningful, stop overriding the pause target
InterlockedIncrement((volatile long*)&DbgEvents); InterlockedIncrement((volatile long*)&DbgEvents);
InterlockedIncrement(&DbgEventsTotal);
PLUG_CB_DEBUGEVENT debugEventInfo; PLUG_CB_DEBUGEVENT debugEventInfo;
debugEventInfo.DebugEvent = DebugEvent; debugEventInfo.DebugEvent = DebugEvent;
plugincbcall(CB_DEBUGEVENT, &debugEventInfo); plugincbcall(CB_DEBUGEVENT, &debugEventInfo);
@ -2951,6 +2997,7 @@ static void debugLoopFunction(INIT_STRUCT* init)
bIsAttached = init->attach; bIsAttached = init->attach;
bPauseAtAttach = init->attach && init->pauseAtAttach; bPauseAtAttach = init->attach && init->pauseAtAttach;
dwAttachMainThread = 0; dwAttachMainThread = 0;
bBreakInExpected = false;
dbgsetskipexceptions(false); dbgsetskipexceptions(false);
bFreezeStack = false; bFreezeStack = false;
@ -3163,6 +3210,7 @@ static void debugLoopFunction(INIT_STRUCT* init)
bIsDebugging = false; bIsDebugging = false;
bPauseAtAttach = false; bPauseAtAttach = false;
dwAttachMainThread = 0; dwAttachMainThread = 0;
bBreakInExpected = false;
GuiSetDebugState(stopped); GuiSetDebugState(stopped);
GuiUpdateAllViews(); GuiUpdateAllViews();
dputs(QT_TRANSLATE_NOOP("DBG", "Debugging stopped!")); dputs(QT_TRANSLATE_NOOP("DBG", "Debugging stopped!"));

View File

@ -80,6 +80,8 @@ bool dbgisdll();
void dbgsetattachevent(HANDLE handle); void dbgsetattachevent(HANDLE handle);
DWORD dbggetattachmainthread(); DWORD dbggetattachmainthread();
void dbgclearattachmainthread(); void dbgclearattachmainthread();
duint dbggetdbgeventcount();
bool dbgspawnbreakinthread();
void dbgsetresumetid(duint tid); void dbgsetresumetid(duint tid);
void DebugUpdateGui(duint disasm_addr, bool stack); void DebugUpdateGui(duint disasm_addr, bool stack);
void DebugUpdateGuiAsync(duint disasm_addr, bool stack); void DebugUpdateGuiAsync(duint disasm_addr, bool stack);

View File

@ -12,3 +12,8 @@ After the attach settles, the driver makes a worker thread emit
debugger's active thread. The `pause` command must interrupt the debuggee debugger's active thread. The `pause` command must interrupt the debuggee
anyway by targeting the main thread instead of the (parked) active thread. The anyway by targeting the main thread instead of the (parked) active thread. The
driver asserts that the debugger reaches the paused state within a timeout. driver asserts that the debugger reaches the paused state within a timeout.
The `breakin` variant runs the target in block mode, where every thread
(including the main thread) blocks forever. The first pause request must not
interrupt anything; a repeated pause request after a few seconds must fall
back to spawning a break-in thread and pause the debuggee.

View File

@ -134,9 +134,13 @@ def main() -> int:
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
pass pass
# test.txt drives the base test, test.breakin.txt the break-in fallback.
script_name = Path(args.script).name
breakin_mode = script_name == "test.breakin.txt"
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if args.no_console_window else 0 creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if args.no_console_window else 0
target = subprocess.Popen( target = subprocess.Popen(
[str(debuggee)], [str(debuggee)] + (["block"] if breakin_mode else []),
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stderr=subprocess.STDOUT,
text=True, text=True,
@ -173,6 +177,25 @@ def main() -> int:
# Let the attach event storm and symbol loading settle. # Let the attach event storm and symbol loading settle.
headless.wait_for_quiescence(idle=2, timeout=30) headless.wait_for_quiescence(idle=2, timeout=30)
if breakin_mode:
# Every thread of the target blocks forever, so the first pause
# request cannot interrupt anything.
headless.send("pause")
if headless.wait_for_line(lambda line: line == "[STATE] paused", 4) is not None:
return fail("unexpected_pause", "first pause request should not break a fully blocked debuggee")
# A repeated pause request after a few seconds must fall back to a
# break-in thread and interrupt the debuggee.
headless.send("pause")
if headless.wait_for_line(lambda line: line == "[STATE] paused", 10) is None:
return fail("breakin_no_effect", "repeated pause request did not break in")
shutdown_headless()
append_log(log_path, '[x64dbg-test] ASSERT PASS source=driver message="first pause request did not pause the blocked debuggee"')
append_log(log_path, '[x64dbg-test] ASSERT PASS source=driver message="repeated pause request paused via break-in thread"')
append_log(log_path, "[x64dbg-test] FINAL status=pass asserts=2")
return 0
# Make a worker thread produce a debug event (OutputDebugString) and # Make a worker thread produce a debug event (OutputDebugString) and
# then block forever, so the debugger's active thread is a thread that # then block forever, so the debugger's active thread is a thread that
# never executes again. # never executes again.

View File

@ -1,6 +1,7 @@
#include <windows.h> #include <windows.h>
#include <cstdio> #include <cstdio>
#include <cstring>
static HANDLE gParkSignal; static HANDLE gParkSignal;
@ -21,8 +22,12 @@ static DWORD WINAPI SignaledParkedThread(LPVOID)
return ParkedThread(nullptr); return ParkedThread(nullptr);
} }
int main() int main(int argc, char** argv)
{ {
// In block mode every thread (including the main thread) blocks forever,
// so a pause is only possible with a break-in thread.
bool blockMode = argc > 1 && std::strcmp(argv[1], "block") == 0;
// Create the message queue before signaling readiness. // Create the message queue before signaling readiness.
MSG msg; MSG msg;
PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE); PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE);
@ -35,6 +40,9 @@ int main()
std::printf("ready %lu %lu\n", GetCurrentProcessId(), GetCurrentThreadId()); std::printf("ready %lu %lu\n", GetCurrentProcessId(), GetCurrentThreadId());
std::fflush(stdout); std::fflush(stdout);
if(blockMode)
return (int)ParkedThread(nullptr); // the driver terminates the process
// Pump messages like the main thread of a GUI application. The pause // Pump messages like the main thread of a GUI application. The pause
// command wakes this loop up with WM_NULL; the driver stops it with WM_QUIT // command wakes this loop up with WM_NULL; the driver stops it with WM_QUIT
// and triggers the signaled thread with WM_APP. // and triggers the signaled thread with WM_APP.

View File

@ -0,0 +1,3 @@
// This variant is driven entirely by driver.py: the target blocks all of its
// threads, so a repeated pause request must fall back to a break-in thread.
// This script is not executed.