Attempt to fix pausing after attaching
This commit is contained in:
parent
20edaeb5fd
commit
4a61e42280
|
|
@ -416,11 +416,20 @@ bool cbDebugPause(int argc, char* argv[])
|
|||
dputs(QT_TRANSLATE_NOOP("DBG", "Program is not running"));
|
||||
return false;
|
||||
}
|
||||
// NOTE: As soon as SetBPX plants the INT3, another thread can hit it and the
|
||||
// breakpoint callback will reassign the global hActiveThread. Operate on a local
|
||||
// copy so the SuspendThread/ResumeThread pair always targets the same thread.
|
||||
// After attaching, the active thread is whatever thread reported the last
|
||||
// attach event (usually an idle worker that never wakes up). Target the
|
||||
// main thread instead until a real debug event selects an active thread.
|
||||
HANDLE hPauseThread = hActiveThread;
|
||||
DWORD dwPauseThreadId = GetDebugData()->dwThreadId;
|
||||
if(auto mainThreadId = dbggetattachmainthread())
|
||||
{
|
||||
auto hMainThread = ThreadGetHandle(mainThreadId);
|
||||
if(hMainThread)
|
||||
hPauseThread = hMainThread;
|
||||
}
|
||||
// As soon as SetBPX plants the INT3, another thread can hit it and the
|
||||
// breakpoint callback can reassign hActiveThread. Keep using this local
|
||||
// handle so SuspendThread and ResumeThread target the same thread.
|
||||
DWORD dwPauseThreadId = GetThreadId(hPauseThread);
|
||||
// TODO: get suspend count instead, this can be detected
|
||||
// Interesting behavior found by JustMagic, if the active thread is suspended pause would fail
|
||||
auto previousSuspendCount = SuspendThread(hPauseThread);
|
||||
|
|
|
|||
|
|
@ -59,6 +59,7 @@ bool cbDebugSwitchthread(int argc, char* argv[])
|
|||
dprintf(QT_TRANSLATE_NOOP("DBG", "Invalid thread %s\n"), formatpidtid((DWORD)threadid).c_str());
|
||||
return false;
|
||||
}
|
||||
dbgclearattachmainthread(); //the pause command should respect this explicit choice
|
||||
//switch thread
|
||||
auto newThread = ThreadGetHandle((DWORD)threadid);
|
||||
if(hActiveThread != newThread)
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@
|
|||
#include "debugger_tracing.h"
|
||||
#include "handles.h"
|
||||
#include <shellapi.h>
|
||||
#include <tlhelp32.h>
|
||||
|
||||
// Debugging variables
|
||||
static PROCESS_INFORMATION g_pi = {0, 0, 0, 0};
|
||||
|
|
@ -51,6 +52,7 @@ static bool bRepeatIn = false;
|
|||
static duint stepRepeat = 0;
|
||||
static bool bIsAttached = false;
|
||||
static bool bPauseAtAttach = false;
|
||||
static DWORD dwAttachMainThread = 0;
|
||||
static bool bSkipExceptions = false;
|
||||
static duint skipExceptionCount = 0;
|
||||
static bool bFreezeStack = false;
|
||||
|
|
@ -343,6 +345,16 @@ void dbgsetattachevent(HANDLE handle)
|
|||
hEvent = handle;
|
||||
}
|
||||
|
||||
DWORD dbggetattachmainthread()
|
||||
{
|
||||
return dwAttachMainThread;
|
||||
}
|
||||
|
||||
void dbgclearattachmainthread()
|
||||
{
|
||||
dwAttachMainThread = 0;
|
||||
}
|
||||
|
||||
void dbgsetresumetid(duint tid)
|
||||
{
|
||||
tidToResume = tid;
|
||||
|
|
@ -2230,12 +2242,82 @@ static void cbDebugEvent(DEBUG_EVENT* DebugEvent)
|
|||
{
|
||||
nextContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
|
||||
hActiveThread = ThreadGetHandle(GetDebugData()->dwThreadId);
|
||||
if(DebugEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
|
||||
dwAttachMainThread = 0; //an exception makes the active thread meaningful, stop overriding the pause target
|
||||
InterlockedIncrement((volatile long*)&DbgEvents);
|
||||
PLUG_CB_DEBUGEVENT debugEventInfo;
|
||||
debugEventInfo.DebugEvent = DebugEvent;
|
||||
plugincbcall(CB_DEBUGEVENT, &debugEventInfo);
|
||||
}
|
||||
|
||||
struct MainThreadEnumContext
|
||||
{
|
||||
DWORD dwProcessId = 0;
|
||||
DWORD dwVisibleWindowThread = 0;
|
||||
DWORD dwAnyWindowThread = 0;
|
||||
};
|
||||
|
||||
static BOOL CALLBACK cbMainThreadEnumWindows(HWND hWnd, LPARAM lParam)
|
||||
{
|
||||
auto & context = *(MainThreadEnumContext*)lParam;
|
||||
DWORD dwWindowProcessId = 0;
|
||||
auto dwWindowThreadId = GetWindowThreadProcessId(hWnd, &dwWindowProcessId);
|
||||
if(dwWindowProcessId == context.dwProcessId)
|
||||
{
|
||||
if(!context.dwAnyWindowThread)
|
||||
context.dwAnyWindowThread = dwWindowThreadId;
|
||||
if(IsWindowVisible(hWnd))
|
||||
{
|
||||
context.dwVisibleWindowThread = dwWindowThreadId;
|
||||
return FALSE; //best candidate found, stop enumerating
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static DWORD getMainThreadId(DWORD dwProcessId)
|
||||
{
|
||||
// Prefer the thread that owns a top-level window, because it pumps
|
||||
// messages and can be woken up with WM_NULL by the pause command.
|
||||
MainThreadEnumContext context;
|
||||
context.dwProcessId = dwProcessId;
|
||||
EnumWindows(cbMainThreadEnumWindows, (LPARAM)&context);
|
||||
if(context.dwVisibleWindowThread)
|
||||
return context.dwVisibleWindowThread;
|
||||
if(context.dwAnyWindowThread)
|
||||
return context.dwAnyWindowThread;
|
||||
|
||||
// Fall back to the thread that was created first.
|
||||
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
if(hSnapshot == INVALID_HANDLE_VALUE)
|
||||
return 0;
|
||||
DWORD dwMainThreadId = 0;
|
||||
ULONGLONG earliestCreationTime = ~0ull;
|
||||
THREADENTRY32 entry = {};
|
||||
entry.dwSize = sizeof(entry);
|
||||
for(auto ok = Thread32First(hSnapshot, &entry); ok; ok = Thread32Next(hSnapshot, &entry))
|
||||
{
|
||||
if(entry.th32OwnerProcessID != dwProcessId)
|
||||
continue;
|
||||
HANDLE hThread = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ThreadID);
|
||||
if(!hThread)
|
||||
continue;
|
||||
FILETIME creationTime = {}, exitTime, kernelTime, userTime;
|
||||
if(GetThreadTimes(hThread, &creationTime, &exitTime, &kernelTime, &userTime))
|
||||
{
|
||||
ULONGLONG time = (ULONGLONG(creationTime.dwHighDateTime) << 32) | creationTime.dwLowDateTime;
|
||||
if(time != 0 && time < earliestCreationTime)
|
||||
{
|
||||
earliestCreationTime = time;
|
||||
dwMainThreadId = entry.th32ThreadID;
|
||||
}
|
||||
}
|
||||
CloseHandle(hThread);
|
||||
}
|
||||
CloseHandle(hSnapshot);
|
||||
return dwMainThreadId;
|
||||
}
|
||||
|
||||
static void cbAttachDebugger()
|
||||
{
|
||||
if(hEvent) //Signal the AeDebug event
|
||||
|
|
@ -2251,6 +2333,13 @@ static void cbAttachDebugger()
|
|||
}
|
||||
varset("$pid", fdProcessInfo->dwProcessId, true);
|
||||
|
||||
// The attach event storm reports an arbitrary thread last, which would
|
||||
// become the active thread. Remember the main (message pump) thread so
|
||||
// the pause command can target a thread that actually executes.
|
||||
dwAttachMainThread = getMainThreadId(fdProcessInfo->dwProcessId);
|
||||
if(dwAttachMainThread)
|
||||
fdProcessInfo->dwThreadId = dwAttachMainThread; //TitanEngine leaves this at zero when attaching
|
||||
|
||||
//Get on top of things
|
||||
SetForegroundWindow(GuiGetWindowHandle());
|
||||
|
||||
|
|
@ -2861,6 +2950,7 @@ static void debugLoopFunction(INIT_STRUCT* init)
|
|||
//initialize variables
|
||||
bIsAttached = init->attach;
|
||||
bPauseAtAttach = init->attach && init->pauseAtAttach;
|
||||
dwAttachMainThread = 0;
|
||||
dbgsetskipexceptions(false);
|
||||
bFreezeStack = false;
|
||||
|
||||
|
|
@ -3072,6 +3162,7 @@ static void debugLoopFunction(INIT_STRUCT* init)
|
|||
TraceRecord.enableTraceRecording(false, nullptr); // Stop trace recording
|
||||
bIsDebugging = false;
|
||||
bPauseAtAttach = false;
|
||||
dwAttachMainThread = 0;
|
||||
GuiSetDebugState(stopped);
|
||||
GuiUpdateAllViews();
|
||||
dputs(QT_TRANSLATE_NOOP("DBG", "Debugging stopped!"));
|
||||
|
|
|
|||
|
|
@ -78,6 +78,8 @@ bool dbgisrunning();
|
|||
bool dbgisdebugging();
|
||||
bool dbgisdll();
|
||||
void dbgsetattachevent(HANDLE handle);
|
||||
DWORD dbggetattachmainthread();
|
||||
void dbgclearattachmainthread();
|
||||
void dbgsetresumetid(duint tid);
|
||||
void DebugUpdateGui(duint disasm_addr, bool stack);
|
||||
void DebugUpdateGuiAsync(duint disasm_addr, bool stack);
|
||||
|
|
|
|||
|
|
@ -188,6 +188,11 @@ foreach(test_name IN LISTS X64DBG_STANDARD_TESTS)
|
|||
x64dbg_add_test(NAME "${test_name}")
|
||||
endforeach()
|
||||
|
||||
x64dbg_add_test(
|
||||
NAME attach_pause
|
||||
TARGET_LINK_LIBRARIES user32
|
||||
)
|
||||
|
||||
x64dbg_add_membp_test()
|
||||
|
||||
# random_dll intentionally remains excluded while its scaffold stays disabled.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,14 @@
|
|||
# attach_pause
|
||||
|
||||
Regression test for pausing an attached debuggee.
|
||||
|
||||
The Python driver starts `attach_pause.exe` (a message pump main thread plus
|
||||
parked worker threads), then sends `attach .<pid>` and `pause` through the
|
||||
headless interactive command handler. This uses `DbgCmdExec` like the GUI, so
|
||||
the attach does not pause the debuggee.
|
||||
|
||||
After the attach settles, the driver makes a worker thread emit
|
||||
`OutputDebugString` and block forever, which turns that worker into the
|
||||
debugger's active thread. The `pause` command must interrupt the debuggee
|
||||
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.
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ctypes
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
WM_QUIT = 0x0012
|
||||
WM_APP = 0x8000
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Drive the attach + pause regression test.")
|
||||
parser.add_argument("--headless", required=True)
|
||||
parser.add_argument("--debuggee", required=True)
|
||||
parser.add_argument("--script", required=True)
|
||||
parser.add_argument("--runtime-dir", required=True)
|
||||
parser.add_argument("--userdir", required=True)
|
||||
parser.add_argument("--log", required=True)
|
||||
parser.add_argument("--artifacts-dir", required=True)
|
||||
parser.add_argument("--engine", required=True)
|
||||
parser.add_argument("--timeout", type=int, required=True)
|
||||
parser.add_argument("--no-console-window", action="store_true")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def path_arg(path: Path, cwd: Path) -> str:
|
||||
try:
|
||||
return os.path.relpath(path, cwd)
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
|
||||
def append_log(log_path: Path, text: str) -> None:
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with log_path.open("a", encoding="utf-8", errors="replace") as log_file:
|
||||
log_file.write(text)
|
||||
if not text.endswith("\n"):
|
||||
log_file.write("\n")
|
||||
|
||||
|
||||
class Headless:
|
||||
def __init__(self, command: list[str], cwd: Path, creationflags: int) -> None:
|
||||
self.process = subprocess.Popen(
|
||||
command,
|
||||
cwd=cwd,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
creationflags=creationflags,
|
||||
)
|
||||
self.lines: list[str] = []
|
||||
self.lock = threading.Lock()
|
||||
threading.Thread(target=self._reader, daemon=True).start()
|
||||
|
||||
def _reader(self) -> None:
|
||||
assert self.process.stdout is not None
|
||||
for line in self.process.stdout:
|
||||
with self.lock:
|
||||
self.lines.append(line.rstrip())
|
||||
|
||||
def send(self, command: str) -> None:
|
||||
assert self.process.stdin is not None
|
||||
self.process.stdin.write(command + "\n")
|
||||
self.process.stdin.flush()
|
||||
|
||||
def wait_for_line(self, predicate, timeout: float) -> str | None:
|
||||
deadline = time.monotonic() + timeout
|
||||
seen = 0
|
||||
while time.monotonic() < deadline:
|
||||
with self.lock:
|
||||
new_lines = self.lines[seen:]
|
||||
seen = len(self.lines)
|
||||
for line in new_lines:
|
||||
if predicate(line):
|
||||
return line
|
||||
if self.process.poll() is not None:
|
||||
return None
|
||||
time.sleep(0.1)
|
||||
return None
|
||||
|
||||
def wait_for_quiescence(self, idle: float, timeout: float) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
with self.lock:
|
||||
count = len(self.lines)
|
||||
time.sleep(idle)
|
||||
with self.lock:
|
||||
if len(self.lines) == count:
|
||||
return
|
||||
|
||||
def dump(self, path: Path) -> None:
|
||||
with self.lock:
|
||||
path.write_text("\n".join(self.lines) + "\n", encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
headless_path = Path(args.headless).resolve()
|
||||
debuggee = Path(args.debuggee).resolve()
|
||||
userdir = Path(args.userdir).resolve()
|
||||
log_path = Path(args.log).resolve()
|
||||
artifacts_dir = Path(args.artifacts_dir).resolve()
|
||||
headless_dir = headless_path.parent
|
||||
artifacts_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# The log is written after headless shuts down, because RedirectLog keeps
|
||||
# the file locked while headless is running.
|
||||
def fail(reason: str, message: str) -> int:
|
||||
shutdown_headless()
|
||||
append_log(log_path, f'[x64dbg-test] ASSERT FAIL source=driver message="{message}"')
|
||||
append_log(log_path, f"[x64dbg-test] FINAL status=fail asserts=1 reason={reason}")
|
||||
return 1
|
||||
|
||||
def shutdown_headless() -> None:
|
||||
if headless is None or headless.process.poll() is not None:
|
||||
return
|
||||
try:
|
||||
headless.send("detach")
|
||||
headless.wait_for_line(lambda line: line == "[STATE] stopped", 10)
|
||||
headless.send("exit")
|
||||
headless.process.wait(timeout=10)
|
||||
except Exception:
|
||||
headless.process.kill()
|
||||
try:
|
||||
headless.process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
|
||||
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if args.no_console_window else 0
|
||||
target = subprocess.Popen(
|
||||
[str(debuggee)],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
creationflags=creationflags,
|
||||
)
|
||||
|
||||
headless: Headless | None = None
|
||||
main_tid = 0
|
||||
try:
|
||||
assert target.stdout is not None
|
||||
ready_line = target.stdout.readline().strip()
|
||||
if not ready_line.startswith("ready "):
|
||||
return fail("target_not_ready", f"target did not print a ready line: {ready_line!r}")
|
||||
pid, main_tid = (int(part) for part in ready_line.split()[1:3])
|
||||
|
||||
command = [
|
||||
str(headless_path),
|
||||
"-userdir",
|
||||
str(userdir),
|
||||
"-c",
|
||||
f'RedirectLog "{path_arg(log_path, headless_dir)}"',
|
||||
]
|
||||
print("[attach-pause-driver] " + " ".join(command), flush=True)
|
||||
headless = Headless(command, headless_dir, creationflags)
|
||||
|
||||
# Attach through the interactive command handler (DbgCmdExec), which is
|
||||
# the same code path as the GUI attach dialog. This does not pause.
|
||||
headless.send(f"attach .{pid}")
|
||||
if headless.wait_for_line(lambda line: "Attached to process!" in line, 30) is None:
|
||||
return fail("attach_failed", "attach command did not report success")
|
||||
|
||||
# Let the attach event storm and symbol loading settle.
|
||||
headless.wait_for_quiescence(idle=2, timeout=30)
|
||||
|
||||
# Make a worker thread produce a debug event (OutputDebugString) and
|
||||
# then block forever, so the debugger's active thread is a thread that
|
||||
# never executes again.
|
||||
ctypes.windll.user32.PostThreadMessageW(main_tid, WM_APP, 0, 0)
|
||||
if headless.wait_for_line(lambda line: "attach_pause: parking" in line, 10) is None:
|
||||
return fail("no_park_marker", "target did not report the parked worker thread")
|
||||
|
||||
# The pause command must interrupt the debuggee even though the active
|
||||
# thread is a parked worker thread that never executes.
|
||||
headless.send("pause")
|
||||
if headless.wait_for_line(lambda line: line == "[STATE] paused", 10) is None:
|
||||
return fail("pause_no_effect", "debugger did not pause after the pause command")
|
||||
|
||||
shutdown_headless()
|
||||
append_log(log_path, '[x64dbg-test] ASSERT PASS source=driver message="pause interrupted the attached debuggee"')
|
||||
append_log(log_path, "[x64dbg-test] FINAL status=pass asserts=1")
|
||||
return 0
|
||||
finally:
|
||||
if headless is not None:
|
||||
headless.dump(artifacts_dir / "headless.stdout.txt")
|
||||
if headless.process.poll() is None:
|
||||
headless.process.kill()
|
||||
if target.poll() is None:
|
||||
if main_tid:
|
||||
ctypes.windll.user32.PostThreadMessageW(main_tid, WM_QUIT, 0, 0)
|
||||
try:
|
||||
target.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
target.kill()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
#include <windows.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
static HANDLE gParkSignal;
|
||||
|
||||
static DWORD WINAPI ParkedThread(LPVOID)
|
||||
{
|
||||
// Block forever on a private event.
|
||||
HANDLE hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
WaitForSingleObject(hEvent, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static DWORD WINAPI SignaledParkedThread(LPVOID)
|
||||
{
|
||||
// After the driver signals (post-attach), produce a debug event so this
|
||||
// thread becomes the debugger's active thread, then block forever.
|
||||
WaitForSingleObject(gParkSignal, INFINITE);
|
||||
OutputDebugStringA("attach_pause: parking");
|
||||
return ParkedThread(nullptr);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// Create the message queue before signaling readiness.
|
||||
MSG msg;
|
||||
PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE);
|
||||
|
||||
gParkSignal = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
CloseHandle(CreateThread(nullptr, 0, SignaledParkedThread, nullptr, 0, nullptr));
|
||||
for(int i = 0; i < 4; i++)
|
||||
CloseHandle(CreateThread(nullptr, 0, ParkedThread, nullptr, 0, nullptr));
|
||||
|
||||
std::printf("ready %lu %lu\n", GetCurrentProcessId(), GetCurrentThreadId());
|
||||
std::fflush(stdout);
|
||||
|
||||
// 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
|
||||
// and triggers the signaled thread with WM_APP.
|
||||
while(GetMessageW(&msg, nullptr, 0, 0) > 0)
|
||||
{
|
||||
if(msg.message == WM_APP)
|
||||
SetEvent(gParkSignal);
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
// This test is driven entirely by driver.py (attach and pause are sent through
|
||||
// the interactive command handler to match the GUI code path). This script is
|
||||
// not executed.
|
||||
Loading…
Reference in New Issue