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/6] 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/6] 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/6] 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/6] 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/6] 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/6] 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)