From c955b4f61de6355dc7c5d489721d0289a1dd5aee Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:53:54 +0100 Subject: [PATCH 1/8] tools: emulate the ntdll mov r10, rcx stub instead of stepping it --- tools/startup/debug_launch.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index c5f794f77e..9af71fe955 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -502,6 +502,7 @@ def restore(): addr = k32.GetProcAddress(ntdll, name.encode()) if addr: hooks[addr] = (name, "valloc") + syscall_hooks = set(hooks) bink_counts, bink_state = {}, {} hit_counts = {} redirects = {} @@ -575,6 +576,8 @@ def chunk(kind, payload): stepping = {} # tid -> addr to re-arm file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace or log_at else None hook_entries = [0] + emulated_hooks = set() + emulated_steps = 0 held_threads = {} # tid -> handle of a thread held for the current step window os_handles = {} # tid -> hThread of CREATE_*_DEBUG_EVENT: valid until its EXIT_THREAD is continued; never closed here sync_raw = (ctypes.c_ubyte * (1232 + 16))() @@ -631,11 +634,16 @@ def release_thread(tid): def arm(addr, *, skip_int3=False): if addr not in breakpoints: original = read(addr, 1) + emulate = (window.protect and addr in syscall_hooks + and read(addr, 3) == b"\x4c\x8b\xd1") if original and (not skip_int3 or original != b"\xcc") and write(addr, b"\xcc"): breakpoints[addr] = original + if emulate: + emulated_hooks.add(addr) return addr in breakpoints and (not skip_int3 or breakpoints[addr] != b"\xcc") def handle_breakpoint(tid, addr): + nonlocal emulated_steps thread, ctx = get_ctx(tid) if not thread: return False @@ -772,6 +780,13 @@ def guid(address): retired.add(addr) set_ctx(thread) return True + if addr in emulated_hooks and arg not in ("count", "runtime", "bink"): + # The armed byte stays in place while this thread advances past mov r10, rcx. + struct.pack_into(" Date: Sun, 29 Nov 2026 15:53:54 +0100 Subject: [PATCH 2/8] tools: drop single-use return breakpoints without a step window --- tools/startup/debug_launch.py | 41 ++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 9af71fe955..e595b35c17 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -571,6 +571,7 @@ def chunk(kind, payload): breakpoints = {} # addr -> original byte retired = set() # X2W_LOG_AT breakpoints removed at their hit limit + disarmed_returns = set() # return sites that can still deliver a queued INT3 late_hits = {} # retired addr -> INT3 events that arrived after the removal returns = ReturnBook() stepping = {} # tid -> addr to re-arm @@ -578,6 +579,7 @@ def chunk(kind, payload): hook_entries = [0] emulated_hooks = set() emulated_steps = 0 + disarmed_steps = 0 held_threads = {} # tid -> handle of a thread held for the current step window os_handles = {} # tid -> hThread of CREATE_*_DEBUG_EVENT: valid until its EXIT_THREAD is continued; never closed here sync_raw = (ctypes.c_ubyte * (1232 + 16))() @@ -643,7 +645,7 @@ def arm(addr, *, skip_int3=False): return addr in breakpoints and (not skip_int3 or breakpoints[addr] != b"\xcc") def handle_breakpoint(tid, addr): - nonlocal emulated_steps + nonlocal emulated_steps, disarmed_steps thread, ctx = get_ctx(tid) if not thread: return False @@ -768,19 +770,26 @@ def guid(address): # call returns, before anything else runs, so a failure or a retry sees the name it built. returns.add(ret, tid, rsp + 8, desc, addr, restore) arm(ret) - for description in returns.take(addr, tid, rsp): + descriptions = returns.take(addr, tid, rsp) + for description in descriptions: file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") file_log.flush() struct.pack_into(" Date: Sun, 29 Nov 2026 15:53:55 +0100 Subject: [PATCH 3/8] tests: check startup hook coverage and measure idle-thread overhead --- tests/startup_hook_check.py | 25 +++++++++------- tests/startup_launch_probe.cpp | 52 +++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 12 deletions(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index aaf8a7446c..98c6abb836 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -1,12 +1,12 @@ """Check that the startup debugger's function hooks see every concurrent call (#1281). usage: startup_hook_check.py the step-window bookkeeping - startup_hook_check.py two threads through a hooked function + startup_hook_check.py concurrent calls through a hooked function A hook is one patched byte. While one thread steps over it the original byte is back, so a second thread entering the function at that moment ran untraced. tools/startup/hook_window.py holds the -other threads for the step. The first form checks that bookkeeping with fake threads and needs no -Windows. The second runs the source-built probe, whose two threads open one file 32 times each, +other threads when a step is needed. The first form checks that bookkeeping with fake threads and needs no +Windows. The second runs the source-built probe, whose four threads open one file 16 times each, entering CreateFileW together, under tools/startup/debug_launch.py: every one of the 64 opens must appear in files.txt with its result, and the run reports no unprotected window. Control: --suspend-others 0 must lose opens and say so. @@ -202,22 +202,25 @@ def run(probe, scratch, name, options): stdout = (logdir / "stdout.txt").read_text(encoding="utf-8", errors="replace") summary = re.search(r"hook windows: entries=\d+ windows=(\d+) unprotected=(\d+) deferred=\d+ timeouts=(\d+) " r"protection=(on|off)", result.stdout + files) - assert summary, (result.returncode, result.stdout, result.stderr[-2000:]) - return traced, stdout, [int(summary.group(i)) for i in (1, 2, 3)], summary.group(4) + avoided = re.search(r"hook emulated: (\d+) disarmed: (\d+)", result.stdout) + assert summary and avoided, (result.returncode, result.stdout, result.stderr[-2000:]) + return traced, stdout, [int(summary.group(i)) for i in (1, 2, 3)], summary.group(4), tuple(map(int, avoided.groups())) def launcher(probe, scratch): for attempt in range(3): - traced, stdout, (windows, unprotected, timeouts), protection = run(probe, scratch, f"held{attempt}", []) + traced, stdout, (windows, unprotected, timeouts), protection, (emulated, _) = run( + probe, scratch, f"held{attempt}", []) assert "overlap opens 64 of 64" in stdout, stdout assert traced == OPENS, f"attempt {attempt}: {traced} of {OPENS} opens traced (more than made means double counting)" - assert windows >= OPENS and unprotected == 0 and timeouts == 0 and protection == "on", (windows, unprotected, timeouts) + assert windows + emulated >= OPENS, (windows, emulated) + assert unprotected == 0 and timeouts == 0 and protection == "on", (unprotected, timeouts, protection) # Control: without holding the other thread the same run loses opens, and the report says so. for attempt in range(8): - traced, stdout, (windows, unprotected, timeouts), protection = run(probe, scratch, f"free{attempt}", - ["--suspend-others", "0"]) + traced, stdout, (_, unprotected, _), protection, avoided = run( + probe, scratch, f"free{attempt}", ["--suspend-others", "0"]) assert "overlap opens 64 of 64" in stdout, stdout - assert protection == "off" + assert protection == "off" and avoided == (0, 0) assert traced <= OPENS, f"control attempt {attempt}: {traced} traces for {OPENS} opens: a call was counted twice" lost = max(0, OPENS - traced) if lost: @@ -233,4 +236,4 @@ def launcher(probe, scratch): sys.exit(0) with tempfile.TemporaryDirectory() as temporary: lost = launcher(Path(sys.argv[1]).resolve(), Path(temporary)) - print(f"startup_hook_overlap: PASS ({OPENS} of {OPENS} opens traced with the window; control lost {lost})") + print(f"startup_hook_overlap: PASS ({OPENS} of {OPENS} opens traced with protection; control lost {lost})") diff --git a/tests/startup_launch_probe.cpp b/tests/startup_launch_probe.cpp index b71e889b99..afdbff45c2 100644 --- a/tests/startup_launch_probe.cpp +++ b/tests/startup_launch_probe.cpp @@ -90,6 +90,55 @@ int overlapping_opens() std::printf("overlap opens %ld of %d\n", static_cast(shared.opened), total); return waited == WAIT_OBJECT_0 && shared.opened == total ? 0 : 1; } + +DWORD WINAPI idle_thread(LPVOID stop) +{ + return WaitForSingleObject(stop, INFINITE); +} + +int idle_opens() +{ + wchar_t path[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_LAUNCH_PROBE_FILE", path, MAX_PATH); + if (length == 0 || length >= MAX_PATH) return 64; + const HANDLE stop = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop) return 65; + HANDLE threads[96]{}; + int started = 0; + for (HANDLE& thread : threads) { + thread = CreateThread(nullptr, 0, idle_thread, stop, 0, nullptr); + if (!thread) break; + ++started; + } + + int result = 65; + LARGE_INTEGER frequency{}, begin{}, end{}; + if (started == static_cast(std::size(threads)) && QueryPerformanceFrequency(&frequency) + && QueryPerformanceCounter(&begin)) { + constexpr int total = 500; + int opened = 0; + for (int i = 0; i < total; ++i) { + const HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) continue; + CloseHandle(file); + ++opened; + } + if (QueryPerformanceCounter(&end)) { + const double ms = 1000.0 * (end.QuadPart - begin.QuadPart) / frequency.QuadPart; + std::printf("idle opens %d of %d with %d idle threads: %.3f ms/open\n", + opened, total, started, ms / total); + result = opened == total ? 0 : 1; + } + } + + SetEvent(stop); + for (int i = 0; i < started; ++i) { + WaitForSingleObject(threads[i], INFINITE); + CloseHandle(threads[i]); + } + CloseHandle(stop); + return result; +} } // namespace int main(int argc, char** argv) @@ -98,6 +147,7 @@ int main(int argc, char** argv) char from_env[16]{}; if (argc == 1 && GetEnvironmentVariableA("X2W_LAUNCH_PROBE_MODE", from_env, sizeof(from_env))) mode = from_env; if (std::strcmp(mode, "overlap") == 0) return overlapping_opens(); + if (std::strcmp(mode, "idle_opens") == 0) return idle_opens(); if (std::strcmp(mode, "report") == 0) { stream(stdout, "launch-probe stdout\n"); stream(stderr, "launch-probe stderr\n"); @@ -144,4 +194,4 @@ int main(int argc, char** argv) } if (std::strcmp(mode, "noop") == 0) return 0; return 64; -} \ No newline at end of file +} From 1cd317dffecc49d3fc508810215a15293c6199e9 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:54:59 +0100 Subject: [PATCH 4/8] tests: require the hook step to emulate and disarm under the default --- tests/startup_hook_check.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 98c6abb836..3305e36a12 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -209,18 +209,21 @@ def run(probe, scratch, name, options): def launcher(probe, scratch): for attempt in range(3): - traced, stdout, (windows, unprotected, timeouts), protection, (emulated, _) = run( + traced, stdout, (windows, unprotected, timeouts), protection, (emulated, disarmed) = run( probe, scratch, f"held{attempt}", []) assert "overlap opens 64 of 64" in stdout, stdout assert traced == OPENS, f"attempt {attempt}: {traced} of {OPENS} opens traced (more than made means double counting)" assert windows + emulated >= OPENS, (windows, emulated) + assert emulated > 0, f"attempt {attempt}: no hook entries were emulated" + assert disarmed > 0, f"attempt {attempt}: no return breakpoints were disarmed" assert unprotected == 0 and timeouts == 0 and protection == "on", (unprotected, timeouts, protection) # Control: without holding the other thread the same run loses opens, and the report says so. for attempt in range(8): - traced, stdout, (_, unprotected, _), protection, avoided = run( + traced, stdout, (_, unprotected, _), protection, (emulated, disarmed) = run( probe, scratch, f"free{attempt}", ["--suspend-others", "0"]) assert "overlap opens 64 of 64" in stdout, stdout - assert protection == "off" and avoided == (0, 0) + assert protection == "off" + assert emulated == 0 and disarmed == 0, (emulated, disarmed) assert traced <= OPENS, f"control attempt {attempt}: {traced} traces for {OPENS} opens: a call was counted twice" lost = max(0, OPENS - traced) if lost: From 3b572f4afcf9565edd1d9f3fa785f40b8d0a21eb Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:41:00 +0100 Subject: [PATCH 5/8] tools: forget disarmed return sites when their module unloads --- tests/startup_hook_check.py | 33 ++++++++++++++++++++++++++++++++- tools/startup/debug_launch.py | 23 +++++++++++++---------- tools/startup/hook_window.py | 21 +++++++++++++++++++++ 3 files changed, 66 insertions(+), 11 deletions(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 3305e36a12..019a50bd85 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -20,7 +20,10 @@ TOOLS = Path(__file__).resolve().parents[1] / "tools/startup" sys.path.insert(0, str(TOOLS)) -from hook_window import FAILED, GONE, HELD, STILL_ACTIVE, STATUS_INVALID_HANDLE, STATUS_THREAD_IS_TERMINATING, ReturnBook, StepWindow, classify_hold, classify_status # noqa: E402 +from hook_window import ( # noqa: E402 + FAILED, GONE, HELD, STILL_ACTIVE, STATUS_INVALID_HANDLE, STATUS_THREAD_IS_TERMINATING, + LateBreakpoints, ReturnBook, StepWindow, classify_hold, classify_status, +) NAME = "x2w_hook_overlap.dat" OPENS = 64 @@ -101,6 +104,7 @@ def bookkeeping(): assert not window.finish(3) and window.finish(1) and log["released"] == [2] returns_bookkeeping() + late_breakpoint_bookkeeping() hold_outcomes() # The summary is always there, with zeros. @@ -187,6 +191,33 @@ def returns_bookkeeping(): assert not book.pending(0x30) +def late_breakpoint_bookkeeping(): + sites = LateBreakpoints() + base, other_base = 0x10000, 0x20000 + return_site, log_site, other_site = base + 0x2100, base + 0x3500, other_base + 0x2100 + sites.add(return_site, base, "return") + sites.add(log_site, base, "X2W_LOG_AT") + sites.add(other_site, other_base, "return") + + memory = {return_site: b"\xcc", log_site: b"\x90", other_site: b"\x90"} + + def read(address, size): + assert size == 1 + return memory.get(address, b"") + + assert sites.rewind_source(return_site, read) is None, "a live INT3 must reach normal exception handling" + del memory[return_site] + assert sites.rewind_source(return_site, read) is None, "an unreadable byte cannot justify a rewind" + memory[return_site] = b"\x90" + assert sites.rewind_source(return_site, read) == "return" + assert sites.rewind_source(log_site, read) == "X2W_LOG_AT" + + sites.forget_module(base) + assert sites.rewind_source(return_site, read) is None, "an unloaded return site must be forgotten" + assert sites.rewind_source(log_site, read) is None, "an unloaded single-use site must be forgotten" + assert sites.rewind_source(other_site, read) == "return", "another image's sites must survive" + + def run(probe, scratch, name, options): logdir = scratch / name data = scratch / NAME diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index e595b35c17..58e29cc2a3 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -34,7 +34,7 @@ from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file, startup_for_create # noqa: E402 import host_cpu # noqa: E402 -from hook_window import StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 +from hook_window import LateBreakpoints, StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 from window_capture import FILE_CAP, Series, png_bytes # noqa: E402 @@ -570,8 +570,7 @@ def chunk(kind, payload): print(f" bink luma plane -> bink_luma.png (pointer {pointer:#x}, pitch {pitch})") breakpoints = {} # addr -> original byte - retired = set() # X2W_LOG_AT breakpoints removed at their hit limit - disarmed_returns = set() # return sites that can still deliver a queued INT3 + late_breakpoints = LateBreakpoints() late_hits = {} # retired addr -> INT3 events that arrived after the removal returns = ReturnBook() stepping = {} # tid -> addr to re-arm @@ -782,10 +781,11 @@ def guid(address): if (log_at_done or last_return) and addr not in hooks and not returns.pending(addr): if write(addr, breakpoints[addr]): del breakpoints[addr] - if log_at_done: - retired.add(addr) - else: - disarmed_returns.add(addr) + region = query_region(addr) + if region: + # AllocationBase identifies the image even when the hook is in a later section. + late_breakpoints.add(addr, region.AllocationBase, "X2W_LOG_AT" if log_at_done else "return") + if not log_at_done: disarmed_steps += 1 set_ctx(thread) return True @@ -1008,6 +1008,9 @@ def capture_loop(): arm(base + (address - local)) if h_file: k32.CloseHandle(wt.HANDLE(h_file)) + elif code == UNLOAD_DLL: + base = struct.unpack_from(" (allocation base, source) + + def add(self, address, allocation_base, source): + self._sites[address] = (allocation_base, source) + + def forget_module(self, base): + self._sites = {address: site for address, site in self._sites.items() if site[0] != base} + + def rewind_source(self, address, read): + site = self._sites.get(address) + if site is not None: + byte = read(address, 1) + if byte and byte != b"\xcc": + return site[1] + return None + + class ReturnBook: """Pending hooked calls, keyed by return address; each is traced once, when its call returns. From bb207dbd81d0ec53329256b7f87428d7a7a14f4c Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:42:52 +0100 Subject: [PATCH 6/8] tools: keep a restored hook site when its region query fails --- tools/startup/debug_launch.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 58e29cc2a3..30e8748e59 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -782,9 +782,10 @@ def guid(address): if write(addr, breakpoints[addr]): del breakpoints[addr] region = query_region(addr) - if region: - # AllocationBase identifies the image even when the hook is in a later section. - late_breakpoints.add(addr, region.AllocationBase, "X2W_LOG_AT" if log_at_done else "return") + # AllocationBase identifies the image even when the hook is in a later section. Without it the + # site is still kept (as before this change), only no unload can drop it. + late_breakpoints.add(addr, region.AllocationBase if region else None, + "X2W_LOG_AT" if log_at_done else "return") if not log_at_done: disarmed_steps += 1 set_ctx(thread) From 23fa52f83ab19b2d2f9cf9c5739d787c508b9f7b Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:10:32 +0100 Subject: [PATCH 7/8] tools: log thread ids and per-thread gaps in traced calls --- tests/startup_debug_check.py | 25 ++++++++++++++++++++++++- tests/startup_exit_report_check.py | 10 ++++++++++ tests/startup_hook_check.py | 12 +++++++++++- tests/startup_triage_run_check.py | 6 +++--- tools/startup/debug_launch.py | 21 +++++++++++++-------- tools/startup/exit_report.py | 2 +- tools/startup/hook_window.py | 8 ++++++++ tools/startup/triage_run.py | 4 ++-- 8 files changed, 72 insertions(+), 16 deletions(-) diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index 299e407ff8..10e51f48ba 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -130,6 +130,8 @@ def main(probe, calls_dll, group='all'): sys.path.insert(0, str(DEBUG.parent)) from debug_launch import MOVIE_CALL_HOOKS, MOVIE_MODULE, read_qword, read_stack if 'hooks' in groups: + from live_view import _LogViewer + require_hooked(HOOKED_MODULE, HOOKED_EXPORT, MOVIE_MODULE, MOVIE_CALL_HOOKS) # Control: the guard rejects the fixture once its export is dropped from the hook list. try: @@ -188,7 +190,10 @@ def stack_read(address, size): out, logdir = run(probe, work, "stop", {"X2W_STOP_AT": f"{sites[1]:x}"}) assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out and "first chance" in out, out events = text(logdir / "events.txt") - assert events.splitlines().count("debugger stop 0x80000003 first-chance") == 1, events + stops = re.findall(r"^debugger stop 0x80000003 first-chance tid=([1-9][0-9]*)$", events, re.M) + assert len(stops) == 1, events + exception_prefix = re.escape(f"exception 0x80000003 breakpoint at {image}+{sites[1]:#x} first-chance") + assert re.search(rf"{exception_prefix} params=\[[^\n]*\] tid={stops[0]}$", events, re.M), events assert f"breakpoint at {image}+{sites[0]:#x}" in events, events stacks = text(logdir / "threads_stop.txt") assert image in stacks and "rip=" in stacks, stacks @@ -355,6 +360,24 @@ def stack_read(address, size): found = re.search(r"bink calls: (.*)", out) assert (found.group(1).strip() if found else None) == want, (name, out) assert banners[name] in out, (name, out) + lines = re.findall(rf"^\s*\d+\.\d+ {HOOKED_EXPORT} [^\n]*", text(logdir / "files.txt"), re.M) + # BinkNextFrame logs only its first three returns, while the summary counts all seven. + assert len(lines) == (3 if want else 0), (name, lines) + thread_id = None + for ordinal, line in enumerate(lines, 1): + gap = r"[0-9]+\.[0-9]{3}" if ordinal > 1 else "n/a" + call = re.search(rf" -> {ordinal:#010x} tid=([1-9][0-9]*) gap_ms={gap}$", line) + assert call, line + if thread_id is None: + thread_id = call[1] + assert call[1] == thread_id, lines + if lines: + shown = [] + viewer = _LogViewer() + viewer.say = lambda tag, message: shown.append((tag, message)) + viewer.on_file(lines[0]) + expected = lines[0].split(None, 1)[1].split(" from ", 1)[0].strip() + assert shown == [("movie", expected)], shown print(f"startup_debug[{group}]: PASS (stop at a chosen assert, timed thread dump, large-allocation log, debug heap off, " "soft asserts NOP'd after the first hit when the core group runs, call hooks opt-in, bounded register and qword logging)") diff --git a/tests/startup_exit_report_check.py b/tests/startup_exit_report_check.py index e3135a62bc..56545c7d79 100644 --- a/tests/startup_exit_report_check.py +++ b/tests/startup_exit_report_check.py @@ -78,6 +78,16 @@ def main() -> int: for secret in ("alice", "game.exe", "KERNELBASE", "0x4da6341", "0x55", "0x9000"): assert secret not in stopped, f"exception stop leaked {secret!r}\n{stopped}" + for suffix in ("", " tid=42"): + from_events, from_events_summary = report({ + "events.txt": ( + f" 1.000 exception 0x80000003 breakpoint at app.exe+0x20 first-chance params=[]{suffix}\n" + f"debugger stop 0x80000003 first-chance{suffix}\n" + ), + }) + assert from_events_summary.confirmed_stop == ("0x80000003", "first"), from_events + assert from_events_summary.classification() == "exception stop", from_events + timed_out, timeout_summary = report({"finished.txt": "timeout after 300.00 s\n"}) expect(timed_out, timeout_summary, [ "| Classification | timeout |", "| End time | `300.0` s |", diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 019a50bd85..99331082af 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -22,7 +22,7 @@ sys.path.insert(0, str(TOOLS)) from hook_window import ( # noqa: E402 FAILED, GONE, HELD, STILL_ACTIVE, STATUS_INVALID_HANDLE, STATUS_THREAD_IS_TERMINATING, - LateBreakpoints, ReturnBook, StepWindow, classify_hold, classify_status, + LateBreakpoints, ReturnBook, StepWindow, classify_hold, classify_status, trace_call_suffix, ) NAME = "x2w_hook_overlap.dat" @@ -104,6 +104,7 @@ def bookkeeping(): assert not window.finish(3) and window.finish(1) and log["released"] == [2] returns_bookkeeping() + trace_call_gaps() late_breakpoint_bookkeeping() hold_outcomes() @@ -191,6 +192,15 @@ def returns_bookkeeping(): assert not book.pending(0x30) +def trace_call_gaps(): + previous_returns = {} + assert trace_call_suffix(previous_returns, 12, 0.0) == " tid=12 gap_ms=n/a" + assert trace_call_suffix(previous_returns, 34, 0.005) == " tid=34 gap_ms=n/a" + assert trace_call_suffix(previous_returns, 12, 0.0125) == " tid=12 gap_ms=12.500" + assert trace_call_suffix(previous_returns, 34, 0.020) == " tid=34 gap_ms=15.000" + assert trace_call_suffix(previous_returns, 12, 0.020) == " tid=12 gap_ms=7.500" + + def late_breakpoint_bookkeeping(): sites = LateBreakpoints() base, other_base = 0x10000, 0x20000 diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 494d0f40be..68813d7344 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -413,9 +413,9 @@ def _check_endpoint_without_commit(failures: list[str]) -> None: def _check_endpoint_second_stop(failures: list[str]) -> None: events = ( - " 10.000 exception 0xC0000005 access violation at a.dll+0x1 first-chance params=[]\n" - " 11.000 exception 0xC0000005 access violation at a.dll+0x1 second-chance params=[]\n" - "debugger stop 0xc0000005 second-chance\n" + " 10.000 exception 0xC0000005 access violation at a.dll+0x1 first-chance params=[] tid=42\n" + " 11.000 exception 0xC0000005 access violation at a.dll+0x1 second-chance params=[] tid=42\n" + "debugger stop 0xc0000005 second-chance tid=42\n" ) report = _endpoint_report({"events.txt": events}) for want in [ diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 30e8748e59..52f5f4ac8c 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -34,7 +34,9 @@ from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file, startup_for_create # noqa: E402 import host_cpu # noqa: E402 -from hook_window import LateBreakpoints, StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 +from hook_window import ( # noqa: E402 + LateBreakpoints, StepWindow, ReturnBook, classify_hold, classify_status, trace_call_suffix, GONE, HELD, +) from window_capture import FILE_CAP, Series, png_bytes # noqa: E402 @@ -573,6 +575,7 @@ def chunk(kind, payload): late_breakpoints = LateBreakpoints() late_hits = {} # retired addr -> INT3 events that arrived after the removal returns = ReturnBook() + last_call_returns = {} # tid -> monotonic time of its last --trace-calls return line stepping = {} # tid -> addr to re-arm file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace or log_at else None hook_entries = [0] @@ -767,17 +770,18 @@ def guid(address): if desc: # The name is temporary: take() puts the caller's own UNICODE_STRING back (restore) when the # call returns, before anything else runs, so a failure or a retry sees the name it built. - returns.add(ret, tid, rsp + 8, desc, addr, restore) + returns.add(ret, tid, rsp + 8, (desc, arg in ("runtime", "bink")), addr, restore) arm(ret) - descriptions = returns.take(addr, tid, rsp) - for description in descriptions: - file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") + returned_calls = returns.take(addr, tid, rsp) + for description, traced_call in returned_calls: + suffix = trace_call_suffix(last_call_returns, tid, time.monotonic()) if traced_call else "" + file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}{suffix}\n") file_log.flush() struct.pack_into(" HELD | GONE | FAILED; release(tid) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index d516728e8d..11683b2e5c 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -167,9 +167,9 @@ RE_COMMIT_PEAK = re.compile(r"x2w-dstorage heartbeat \d{1,10} s: .*?\bcommit peak=(\d{1,10}) MiB\b") RE_FAILURE_CAUSES = re.compile(r"x2w-dstorage heartbeat (\d{1,10}) s: failed requests by cause ((?:[a-z-]+=\d{1,10}(?:\s+|$))+)") RE_CAUSE_COUNT = re.compile(r"([a-z-]+)=(\d{1,10})") -# debug_launch.py events.txt: " exception at first|second-chance params=[...]". +# debug_launch.py events.txt: " exception at first|second-chance params=[...] tid=". RE_EXCEPTION = re.compile(r"^\s*\d+\.\d+\s+exception\s+(0x[0-9a-fA-F]{8})\b.*?\b(first|second)-chance\b") -RE_DEBUGGER_STOP = re.compile(r"^debugger stop (0x[0-9a-fA-F]{8}) (first|second)-chance$") +RE_DEBUGGER_STOP = re.compile(r"^debugger stop (0x[0-9a-fA-F]{8}) (first|second)-chance(?: tid=[0-9]{1,10})?$") RE_STOP_SUMMARY = re.compile( r"^stopped at [^(]+\((0x[0-9a-fA-F]{8})\) at .+ after \d+\.\d+ s \((first|second) chance\) params=\[" ) From 9699aa4f1b5b11cd6ac5501e69ef77b1ff95a0a1 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:28:20 +0100 Subject: [PATCH 8/8] tools: test the per-thread gap reset and document trace thread ids --- docs/startup-runtime.md | 6 ++- tests/startup_debug_check.py | 84 ++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 040ae3e4b2..0cfb65a914 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -867,6 +867,10 @@ that its fixture's module and export are in that list, that a source-built DLL l movie-player module name is not hooked by default, that each of its 7 export calls is counted with `--trace-calls 1`, and that `--trace-calls 1` with file tracing off counts nothing and says why. +Each traced call return in `files.txt` ends with `tid=` and `gap_ms=`. +The gap measures time since that thread's previous logged return. The first return has `gap_ms=n/a`, +including when a new thread reuses the ID of a thread that exited. + **Window pictures.** At the end of a run that is still going, `debug_launch.py` saves the client area of the title's window as `window.png`. `--capture-every ` (`run.ps1 -CaptureEvery`, `run.sh --capture-every`) also saves it every N seconds (N is at least 1; 0, the default, is off) as `window_s.png`, with the seconds @@ -916,7 +920,7 @@ It writes: | File | Content | |---|---| | `.out` | why the run stopped: exception, registers, stack, likely return addresses, raw stack | -| `/events.txt` | module loads and every exception with its time | +| `/events.txt` | module loads and exception times. Exception and debugger stop lines end with `tid=`. | | `/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) | | `/files.txt` | every file the process opened | | `/translate.txt` | with `-Translate`: one line per shader request translated during the run | diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index 10e51f48ba..6a8e4989d5 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -21,14 +21,17 @@ export names must be among the ones the launcher hooks, so the check cannot pass with nothing hooked, and --trace-calls 1 without file tracing must count nothing and say why. """ +import ctypes import os from pathlib import Path import re import shutil +import struct import subprocess import sys import tempfile import time +from unittest.mock import Mock, patch REPO = Path(__file__).resolve().parents[1] DEBUG = REPO / "tools/startup/debug_launch.py" @@ -101,6 +104,86 @@ def require_hooked(module, export, hooked_module, hooked_exports): raise AssertionError(f"{module}!{export} is not hooked by debug_launch.py ({hooked_module}: {hooked_exports})") +def check_trace_gap_after_thread_exit(work): + """Replay two lifetimes of one numeric thread ID through the debugger's event loop.""" + import debug_launch as launcher + + pid, main_tid, worker_tid = 1, 10, 12 + image_base, movie_base, local_base = 0x140000000, 0x180000000, 0x10000000 + entry, return_site, stack = movie_base + 0x1000, image_base + 0x2000, 0x8000 + breakpoint, single_step = 0x80000003, 0x80000004 + + def exception(tid, code, address): + # The exception record ends at offset 152, followed by the first-chance flag. + return launcher.EXCEPTION, tid, struct.pack("