From 126ed2d621d76f52915c65791c7cce953ca86014 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:39:24 +0100 Subject: [PATCH 01/11] startup: hold other threads while a hook steps over its byte Two threads entering the same hooked function could run through the step-over window untraced. The debugger now holds every other thread for the step, defers a hit that trapped before the hold, bounds each window with a deadline and always reports how many windows were unprotected. --- CMakeLists.txt | 7 ++ docs/experiments.md | 11 +++ docs/startup-runtime.md | 26 ++++++ tests/startup_hook_check.py | 152 +++++++++++++++++++++++++++++++++ tests/startup_launch_probe.cpp | 44 +++++++++- tools/startup/debug_launch.py | 53 +++++++++++- tools/startup/hook_window.py | 88 +++++++++++++++++++ 7 files changed, 379 insertions(+), 2 deletions(-) create mode 100644 tests/startup_hook_check.py create mode 100644 tools/startup/hook_window.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3dd1df9c96..8ea1e37c49 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2900,6 +2900,13 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_launch_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_launch_cli_check.py") set_tests_properties(startup_launch_cli_check PROPERTIES TIMEOUT 30) + # The debugger's function hooks and concurrent calls (#1281): the step window's bookkeeping, then two + # threads through one hooked function with the other thread held for each step, and without. + add_test(NAME startup_hook_window COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_hook_check.py") + add_test(NAME startup_hook_overlap COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_hook_check.py" "$") + set_tests_properties(startup_hook_window PROPERTIES TIMEOUT 30) + set_tests_properties(startup_hook_overlap PROPERTIES TIMEOUT 600) add_test(NAME startup_debug COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_debug_check.py" "$" "$") diff --git a/docs/experiments.md b/docs/experiments.md index 3d9a4194f7..a02628ebec 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12918,6 +12918,8 @@ The [MASM fixture](../tests/cpu/sse4a.asm) exports 24 translated `op_*` function Not covered by this experiment: non-temporal cache-bypass hints, runtime `offset + width > 64` hardware-undefined behavior in register-form `extrq`/`insertq`, control flow or nonvolatile prologues, and title CPU code execution. +Not covered by this experiment: host segment-base writes (`wrfsbase`/`wrgsbase`, which require an explicit isolation/restoration profile), cross-thread `FS_BASE`/`GS_BASE` migration, and title CPU code execution. + ## Host-CPU RDFSBASE, RDGSBASE, and RDPID lifting in cpu_switch_aot [The switch translator](../tools/cpu_switch_aot.py) adds an opt-in `--host-cpu` (`host_cpu=True`) mode lifting read-only `rdfsbase`, `rdgsbase` (32- and 64-bit register forms), and `rdpid` (64-bit register form) from `docs/coverage/x64_zen2.tsv` group `Integer` to the `` intrinsics (`_readfsbase_u32`, `_readfsbase_u64`, `_readgsbase_u32`, `_readgsbase_u64`, `_rdpid_u32`): @@ -13079,3 +13081,12 @@ ctest --preset dev --no-tests=error -R '^(cpu_aot_switch_sal|cpu_aot_switch_shif The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequences (because ML64 assembles the `sal` mnemonic as `/4` `SHL`) across 24 translated functions covering all 12 `SAL` `Code` encodings (`SAL_RM{8,16,32,64}_{1,CL,IMM8}`), register and memory destinations, count-`1` all-16 `SETcc` checks, count->1 10-condition `SETcc` checks, `Jcc`, `CMOVcc`, narrow returns, and nonvolatile/stack-frame operands, plus 11 negative exports. [The differential check](../tests/cpu/switch_sal_check.py) verifies 28,024 `dev` and 28,024 `/O2` comparisons against native execution and the Python reference, four `/O2` mutated-C++ controls (`shift_dir`, `cf_mask`, `of_mask`, `cl_mask`), 11 MASM, 4 unit, and 7 PE-patched rejection controls, and records decoded mnemonics via `iced_x86.Mnemonic` to `FORM_COVERAGE_RECORD`. Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. + +## Concurrent calls through a startup debugger hook + +The startup debugger holds every other thread while it steps one over a hooked function, so two threads entering the same hooked function are both traced ([#1281](https://github.com/R0Y00/Xbox2Windows/issues/1281)). A run ends with `hook windows: ... unprotected=U`, the windows in which another thread could not be held or the 2 s deadline passed; `--suspend-others 0` turns the holding off. See [Concurrent calls through a hooked function](startup-runtime.md#concurrent-calls-through-a-hooked-function). + +```powershell +cmake --build --preset dev --target startup_launch_probe +ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V +``` diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 3d67304546..8b3c3d72af 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1009,6 +1009,32 @@ cmake --build --preset dev --target startup_trap_header_check ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_precedence_control)?$' -V ``` +## Concurrent calls through a hooked function + +The debugger's file, socket and allocation hooks are one patched byte per function. To run the original +instruction it restores the byte, single-steps the thread that hit it and patches the byte again. A second thread that +entered the function inside that window ran untraced, so `files.txt` could miss opens and the +offline mode could miss a refused socket. Now every other thread is held for the step and resumes when the stepping +thread is done (`tools/startup/hook_window.py`). A thread that had already trapped when it was held goes back to the +hook address and traps again afterwards, so its call is traced once, not twice. Each window has a 2 s deadline, so a +thread is never held forever. Per-thread state of a call in flight (the return address and stack pointer it will come back to) is +keyed by thread id, not shared. + +Every run ends with `hook windows: entries=N windows=W unprotected=U deferred=D timeouts=T protection=on|off` in the +console output, `finished.txt` and `files.txt`, also when everything is 0. `unprotected` counts the windows in which another thread could +not be held, or the deadline passed, or protection was off with other threads alive: an upper bound on the calls a run may have +missed. `--suspend-others 0` turns the holding off, to measure what it costs or to see the loss. + +`tests/startup_hook_check.py` has two parts. `startup_hook_window` checks the bookkeeping with fake threads and needs no +Windows. `startup_hook_overlap` runs the source-built `startup_launch_probe` in its `overlap` mode under the debugger: two threads +enter `CreateFileW` together 32 times each on one file, and all 64 opens must show in `files.txt` with their result and +`unprotected=0`. The control, `--suspend-others 0`, must lose opens and report `unprotected` above 0. + +```powershell +cmake --build --preset dev --target startup_launch_probe +ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V +``` + ## Switches | Variable | Effect | diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py new file mode 100644 index 0000000000..3c903db2f7 --- /dev/null +++ b/tests/startup_hook_check.py @@ -0,0 +1,152 @@ +"""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 + +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, +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. +""" +from pathlib import Path +import os +import re +import subprocess +import sys +import tempfile + +TOOLS = Path(__file__).resolve().parents[1] / "tools/startup" +sys.path.insert(0, str(TOOLS)) +from hook_window import FAILED, GONE, HELD, StepWindow # noqa: E402 + +NAME = "x2w_hook_overlap.dat" +OPENS = 64 + + +def fakes(results=None): + log = {"held": [], "released": []} + results = results or {} + + def hold(tid): + result = results.get(tid, HELD) + if result == HELD: + log["held"].append(tid) + return result + + return log, hold, lambda tid: log["released"].append(tid) + + +def bookkeeping(): + # Every other thread is held before the step and resumed when the owner finishes; the owner never is. + log, hold, release = fakes() + window = StepWindow(hold, release) + window.open(1, [1, 2, 3], now=0) + assert log["held"] == [2, 3] and not window.defer(1) and window.defer(2) and window.deferred == 1 + assert not window.finish(2) and log["released"] == [], "only the owner closes a window" + assert window.finish(1) and sorted(log["released"]) == [2, 3] and not window.defer(2) + assert window.unprotected == 0 and window.timeouts == 0 + window.open(2, [1], now=1) # a closed window can be opened again + window.abandon() + + # A thread created during the step is held too; one that never joins the window is not. + log, hold, release = fakes() + window = StepWindow(hold, release) + window.hold(9) + assert log["held"] == [] + window.open(1, [2], now=0) + window.hold(9) + window.hold(9) + window.hold(1) + assert log["held"] == [2, 9] + window.finish(1) + assert sorted(log["released"]) == [2, 9] + + # A thread that is gone needs nothing; one that cannot be held leaves the window unprotected. + log, hold, release = fakes({2: GONE, 3: FAILED}) + window = StepWindow(hold, release) + window.open(1, [2, 3, 4], now=0) + assert log["held"] == [4] and window.unprotected == 1 + window.finish(1) + assert log["released"] == [4] + + # A window that outlives its limit is closed, resumed and counted, once. + log, hold, release = fakes() + window = StepWindow(hold, release, limit=2.0) + window.open(1, [2], now=10) + assert not window.expire(11.9) and log["released"] == [] + assert window.expire(12.0) and log["released"] == [2] + assert window.timeouts == 1 and window.unprotected == 1 + assert not window.expire(99) and not window.finish(1) and window.timeouts == 1 + + # With protection off nothing is held or deferred, and a window with company is reported. + log, hold, release = fakes() + window = StepWindow(hold, release, protect=False) + window.open(1, [2], now=0) + assert log["held"] == [] and not window.defer(2) and window.unprotected == 1 + window.finish(1) + window.open(1, [], now=0) + assert window.windows == 2 and window.unprotected == 1 + + # A second window while one is open is a bug in the caller, not a silent overwrite. + window = StepWindow(hold, release) + window.open(1, [], now=0) + try: + window.open(2, [], now=0) + except RuntimeError: + pass + else: + raise AssertionError("a second window was opened") + + # The summary is always there, with zeros. + line = StepWindow(hold, release).summary(0) + assert line == "hook windows: entries=0 windows=0 unprotected=0 deferred=0 timeouts=0 protection=on", line + + +def run(probe, scratch, name, options): + logdir = scratch / name + data = scratch / NAME + data.write_bytes(b"x2w") + env = {k: v for k, v in os.environ.items() if not k.startswith("X2W_")} + env.update(X2W_LAUNCH_PROBE_MODE="overlap", X2W_LAUNCH_PROBE_FILE=str(data)) + command = [sys.executable, "-B", str(TOOLS / "debug_launch.py"), str(probe), str(scratch), str(logdir), + "--timeout", "60", "--console", "0", "--trace-files", "1", "--continue-asserts", "0", *options] + result = subprocess.run(command, capture_output=True, text=True, timeout=180, env=env) + files = (logdir / "files.txt").read_text(encoding="utf-8", errors="replace") + traced = sum(1 for line in files.splitlines() + if " NtCreateFile " in line and NAME in line.lower() and line.endswith("-> 0x00000000")) + 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.stdout + return traced, stdout, [int(summary.group(i)) for i in (1, 2, 3)], summary.group(4) + + +def launcher(probe, scratch): + for attempt in range(3): + traced, stdout, (windows, unprotected, timeouts), protection = 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" + assert windows >= OPENS and unprotected == 0 and timeouts == 0 and protection == "on", (windows, unprotected, timeouts) + # 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"]) + assert "overlap opens 64 of 64" in stdout, stdout + assert protection == "off" + if traced < OPENS: + assert unprotected > 0, "opens were lost but the run reported no unprotected window" + return traced + raise AssertionError(f"the control never lost an open in 8 runs: the overlap was not exercised ({traced} of {OPENS})") + + +if __name__ == "__main__": + bookkeeping() + if len(sys.argv) == 1: + print("startup_hook_window: PASS (hold, defer, finish, new thread, gone/failed thread, deadline, protection off, summary)") + 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 traced {lost})") diff --git a/tests/startup_launch_probe.cpp b/tests/startup_launch_probe.cpp index 732092034d..5d1225f349 100644 --- a/tests/startup_launch_probe.cpp +++ b/tests/startup_launch_probe.cpp @@ -2,7 +2,8 @@ // executable in a kill-on-close job with a timeout, a commit cap and captured stdout/stderr, and // this fixture is the only executable the check needs: it writes known bytes to both streams and // the trap log, reports a known exit code, or holds memory, spawns a child or stays alive so the -// job limits have to stop it. Paths stay UTF-16 throughout: the launcher passes a Unicode trap-log +// job limits have to stop it. The "overlap" mode (from X2W_LAUNCH_PROBE_MODE, because the debugger passes no +// arguments) opens one file from two threads that enter CreateFileW together, for tests/startup_hook_check.py. Paths stay UTF-16 throughout: the launcher passes a Unicode trap-log // path, and its build or temp folder can hold characters the active ANSI code page cannot. #include @@ -45,11 +46,52 @@ void spawn_second_process(const wchar_t* self) CloseHandle(child.hProcess); std::printf("spawn ok\n"); } +constexpr int overlap_rounds = 32; + +struct Overlap { + const wchar_t* path; + volatile LONG arrived[overlap_rounds]; + volatile LONG opened; +}; + +// Both threads wait for each other before every open, so each round enters the same function at once. +DWORD WINAPI overlap_thread(LPVOID parameter) +{ + auto* shared = static_cast(parameter); + for (int round = 0; round < overlap_rounds; ++round) { + InterlockedIncrement(&shared->arrived[round]); + const ULONGLONG begin = GetTickCount64(); + while (shared->arrived[round] < 2 && GetTickCount64() - begin < 10000) SwitchToThread(); + const HANDLE file = CreateFileW(shared->path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) continue; + CloseHandle(file); + InterlockedIncrement(&shared->opened); + } + return 0; +} + +int overlapping_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; + static Overlap shared{}; + shared.path = path; + const HANDLE threads[2] = {CreateThread(nullptr, 0, overlap_thread, &shared, 0, nullptr), + CreateThread(nullptr, 0, overlap_thread, &shared, 0, nullptr)}; + if (!threads[0] || !threads[1]) return 65; + const DWORD waited = WaitForMultipleObjects(2, threads, TRUE, 60000); + std::printf("overlap opens %ld of %d\n", static_cast(shared.opened), 2 * overlap_rounds); + return waited == WAIT_OBJECT_0 && shared.opened == 2 * overlap_rounds ? 0 : 1; +} } // namespace int main(int argc, char** argv) { const char* mode = argc > 1 ? argv[1] : "report"; + 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, "report") == 0) { stream(stdout, "launch-probe stdout\n"); stream(stderr, "launch-probe stderr\n"); diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index f5f37bb0cb..53956370a1 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -1,6 +1,6 @@ """Run one EXE under a minimal debugger inside a kill-on-close job (startup diagnostics; see docs/startup-runtime.md). -usage: debug_launch.py [--timeout S] [--memory-gib N] [--stop-first-chance 1] +usage: debug_launch.py [--timeout S] [--memory-gib N] [--stop-first-chance 1] [--suspend-others 0] Records module loads, every exception (code, address as module+offset, first/second chance) and, for the stopping exception, the integer registers, the stack words and the code bytes around RIP. @@ -18,9 +18,11 @@ k32.OpenThread.restype = wt.HANDLE k32.CreateJobObjectW.restype = wt.HANDLE k32.CreateFileW.restype = wt.HANDLE +k32.SuspendThread.restype = wt.DWORD from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file # noqa: E402 import host_cpu # noqa: E402 +from hook_window import StepWindow, HELD, GONE, FAILED # noqa: E402 class MemoryBasicInformation(ctypes.Structure): @@ -426,6 +428,35 @@ def chunk(kind, payload): returns = {} # addr -> list of (tid, rsp after return, description) 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] + held_threads = {} # tid -> handle of a thread held for the current step window + sync_raw = (ctypes.c_ubyte * (1232 + 16))() + sync_addr = (ctypes.addressof(sync_raw) + 15) & ~15 + + def hold_thread(tid): + handle = k32.OpenThread(0x0002 | 0x0008, False, tid) # SUSPEND_RESUME | GET_CONTEXT + if not handle: + return GONE if ctypes.get_last_error() == 87 else FAILED # 87: no such thread + # SuspendThread returns before the thread has stopped; GetThreadContext waits until it has. + struct.pack_into(" {regs['Rax'] & 0xFFFFFFFF:#010x}\n") file_log.flush() + # Step over the original instruction, then re-arm. Everyone else is held until the step is done. + window.open(tid, [other for other in live_threads if other != tid], time.monotonic()) struct.pack_into("= watch_next: watch_next = time.time() + 1.0 poll_watches() + if window.expire(time.monotonic()): + log(f"{time.time() - start:7.3f} hook step window expired, held threads resumed") if not k32.WaitForDebugEvent(event, 200): continue code, pid, tid = struct.unpack_from(" HELD | GONE | FAILED; release(tid) + self.protect, self.limit = protect, limit + self.owner = None + self._held = [] + self._deadline = 0.0 + self._exposed = False + self.windows = self.unprotected = self.deferred = self.timeouts = 0 + + def open(self, owner, others, now): + """The owner is about to step over its hook: hold every other thread first.""" + if self.owner is not None: + raise RuntimeError("a step window is already open") + self.windows += 1 + if not self.protect: # measuring mode: nothing is held, every window with company is exposed + self.unprotected += 1 if others else 0 + return + self.owner, self._deadline, self._exposed = owner, now + self.limit, False + for tid in others: + self.hold(tid) + + def hold(self, tid): + """Holds one more thread while a window is open (a thread created during the step).""" + if self.owner is None or tid == self.owner or tid in self._held: + return + result = self._hold(tid) + if result == HELD: + self._held.append(tid) + elif result == FAILED: + self._expose() + + def defer(self, tid): + """True when a hook hit comes from a held thread: it trapped before it was held, so it + must go back to the hook address and trap again once the window is closed.""" + if self.owner is None or tid == self.owner: + return False + self.deferred += 1 + return True + + def finish(self, tid): + """The owner's step is done (or the owner is gone): the held threads resume.""" + if self.owner is None or tid != self.owner: + return False + self._close() + return True + + def expire(self, now): + """A window that is still open at its deadline is closed and counted as exposed.""" + if self.owner is None or now < self._deadline: + return False + self.timeouts += 1 + self._expose() + self._close() + return True + + def abandon(self): + """The run is over: resume whatever is held without counting a timeout.""" + self._close() + + def summary(self, entries): + return (f"hook windows: entries={entries} windows={self.windows} unprotected={self.unprotected} " + f"deferred={self.deferred} timeouts={self.timeouts} protection={'on' if self.protect else 'off'}") + + def _expose(self): + if not self._exposed: + self._exposed = True + self.unprotected += 1 + + def _close(self): + held, self._held, self.owner = self._held, [], None + for tid in held: + self._release(tid) From 8167fc2addba16fad2e4f42d33bfc9f1d432b3db Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:53:23 +0100 Subject: [PATCH 02/11] startup: keep a second stepping thread from taking over an open hook window A thread that was not held no longer raises when it steps at another hook: the open window stays with its owner and is reported as exposed. Only a held thread is deferred. --- tests/startup_hook_check.py | 16 ++++++++-------- tools/startup/hook_window.py | 11 +++++++---- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 3c903db2f7..5f8189f312 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -90,15 +90,15 @@ def bookkeeping(): window.open(1, [], now=0) assert window.windows == 2 and window.unprotected == 1 - # A second window while one is open is a bug in the caller, not a silent overwrite. + # A thread that was not held and steps while a window is open does not take the window over: the + # owner keeps it, the held threads stay held until the owner is done, and the window is exposed. + log, hold, release = fakes({3: FAILED}) window = StepWindow(hold, release) - window.open(1, [], now=0) - try: - window.open(2, [], now=0) - except RuntimeError: - pass - else: - raise AssertionError("a second window was opened") + window.open(1, [2, 3], now=0) + assert not window.defer(3), "a thread that is not held cannot be deferred" + window.open(3, [1, 2], now=0) + assert window.owner == 1 and window.unprotected == 1 and log["released"] == [] + assert not window.finish(3) and window.finish(1) and log["released"] == [2] # The summary is always there, with zeros. line = StepWindow(hold, release).summary(0) diff --git a/tools/startup/hook_window.py b/tools/startup/hook_window.py index c6dff7a1c0..4729f5022c 100644 --- a/tools/startup/hook_window.py +++ b/tools/startup/hook_window.py @@ -25,9 +25,12 @@ def __init__(self, hold, release, protect=True, limit=2.0): def open(self, owner, others, now): """The owner is about to step over its hook: hold every other thread first.""" - if self.owner is not None: - raise RuntimeError("a step window is already open") self.windows += 1 + if self.owner is not None: + # A thread that was not held (or reached another hook) steps while a window is open: the + # window stays with its owner and is reported as exposed. + self._expose() + return if not self.protect: # measuring mode: nothing is held, every window with company is exposed self.unprotected += 1 if others else 0 return @@ -46,9 +49,9 @@ def hold(self, tid): self._expose() def defer(self, tid): - """True when a hook hit comes from a held thread: it trapped before it was held, so it + """True when a hook hit comes from a thread held by the open window: it trapped before it was held, so it must go back to the hook address and trap again once the window is closed.""" - if self.owner is None or tid == self.owner: + if tid not in self._held: return False self.deferred += 1 return True From 389bf056b0423a3f5c0d8fbc3c11b6e195ec7bcc Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:54:39 +0100 Subject: [PATCH 03/11] startup: trace a hooked call once when its entry traps twice With the step window off, another thread can re-patch the hook byte before the stepping thread runs the original instruction, so the thread traps again at the same address and stack slot. The call was registered twice and its return wrote two lines (88 traces for 64 opens). Pending returns are now keyed by thread and slot, and the control counts lost opens as max(0, 64 - traced). The overlap probe uses four threads with a spin barrier. --- docs/startup-runtime.md | 4 ++-- tests/startup_hook_check.py | 41 +++++++++++++++++++++++++++++----- tests/startup_launch_probe.cpp | 24 +++++++++++--------- tools/startup/debug_launch.py | 14 +++++------- tools/startup/hook_window.py | 26 +++++++++++++++++++++ 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8b3c3d72af..8220beb1c7 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1026,8 +1026,8 @@ not be held, or the deadline passed, or protection was off with other threads al missed. `--suspend-others 0` turns the holding off, to measure what it costs or to see the loss. `tests/startup_hook_check.py` has two parts. `startup_hook_window` checks the bookkeeping with fake threads and needs no -Windows. `startup_hook_overlap` runs the source-built `startup_launch_probe` in its `overlap` mode under the debugger: two threads -enter `CreateFileW` together 32 times each on one file, and all 64 opens must show in `files.txt` with their result and +Windows. `startup_hook_overlap` runs the source-built `startup_launch_probe` in its `overlap` mode under the debugger: four threads +enter `CreateFileW` together 16 times each on one file, and all 64 opens must show in `files.txt` with their result and `unprotected=0`. The control, `--suspend-others 0`, must lose opens and report `unprotected` above 0. ```powershell diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 5f8189f312..76fabc3479 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -20,7 +20,7 @@ TOOLS = Path(__file__).resolve().parents[1] / "tools/startup" sys.path.insert(0, str(TOOLS)) -from hook_window import FAILED, GONE, HELD, StepWindow # noqa: E402 +from hook_window import FAILED, GONE, HELD, ReturnBook, StepWindow # noqa: E402 NAME = "x2w_hook_overlap.dat" OPENS = 64 @@ -100,11 +100,40 @@ def bookkeeping(): assert window.owner == 1 and window.unprotected == 1 and log["released"] == [] assert not window.finish(3) and window.finish(1) and log["released"] == [2] + returns_bookkeeping() + # The summary is always there, with zeros. line = StepWindow(hold, release).summary(0) assert line == "hook windows: entries=0 windows=0 unprotected=0 deferred=0 timeouts=0 protection=on", line +def traced_returns(retrapped): + """Two threads call from fixed stack slots, 32 calls each. A call in `retrapped` hits its entry + hook twice: another thread re-patched the byte before this one ran the original instruction, so + the same call is registered again. Returns how many lines the book writes for the 64 calls.""" + book, lines = ReturnBook(), 0 + for call in range(32): + for tid in (1, 2): + for _ in range(2 if (call, tid) in retrapped else 1): + book.add(0x7000, tid, 0x1000 * tid, f"NtCreateFile call {call}") + lines += len(book.take(0x7000, tid, 0x1000 * tid)) + return lines + + +def returns_bookkeeping(): + # One call is traced once however many times its entry trapped: a run showed "88 of 64". + retrapped = {(call, 1) for call in range(0, 32, 4)} | {(call, 2) for call in range(0, 32, 4)} \ + | {(call, 1) for call in range(1, 32, 4)} + assert len(retrapped) == 24 + assert traced_returns(set()) == 64 + assert traced_returns(retrapped) == 64, traced_returns(retrapped) + book = ReturnBook() + book.add(0x10, 1, 0x100, "a") + book.add(0x10, 2, 0x100, "b") # same slot value on another thread is another call + assert book.take(0x10, 1, 0x100) == ["a"] and book.take(0x10, 1, 0x100) == [] + assert book.take(0x10, 2, 0x100) == ["b"] and book.take(0x99, 2, 0x100) == [] + + def run(probe, scratch, name, options): logdir = scratch / name data = scratch / NAME @@ -128,7 +157,7 @@ def launcher(probe, scratch): for attempt in range(3): traced, stdout, (windows, unprotected, timeouts), protection = 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" + 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) # Control: without holding the other thread the same run loses opens, and the report says so. for attempt in range(8): @@ -136,9 +165,11 @@ def launcher(probe, scratch): ["--suspend-others", "0"]) assert "overlap opens 64 of 64" in stdout, stdout assert protection == "off" - if traced < OPENS: + assert traced <= OPENS, f"control attempt {attempt}: {traced} traces for {OPENS} opens: a call was counted twice" + lost = max(0, OPENS - traced) + if lost: assert unprotected > 0, "opens were lost but the run reported no unprotected window" - return traced + return lost raise AssertionError(f"the control never lost an open in 8 runs: the overlap was not exercised ({traced} of {OPENS})") @@ -149,4 +180,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 traced {lost})") + print(f"startup_hook_overlap: PASS ({OPENS} of {OPENS} opens traced with the window; control lost {lost})") diff --git a/tests/startup_launch_probe.cpp b/tests/startup_launch_probe.cpp index 5d1225f349..a8b77e688e 100644 --- a/tests/startup_launch_probe.cpp +++ b/tests/startup_launch_probe.cpp @@ -3,7 +3,7 @@ // this fixture is the only executable the check needs: it writes known bytes to both streams and // the trap log, reports a known exit code, or holds memory, spawns a child or stays alive so the // job limits have to stop it. The "overlap" mode (from X2W_LAUNCH_PROBE_MODE, because the debugger passes no -// arguments) opens one file from two threads that enter CreateFileW together, for tests/startup_hook_check.py. Paths stay UTF-16 throughout: the launcher passes a Unicode trap-log +// arguments) opens one file from four threads that enter CreateFileW together, for tests/startup_hook_check.py. Paths stay UTF-16 throughout: the launcher passes a Unicode trap-log // path, and its build or temp folder can hold characters the active ANSI code page cannot. #include @@ -46,7 +46,8 @@ void spawn_second_process(const wchar_t* self) CloseHandle(child.hProcess); std::printf("spawn ok\n"); } -constexpr int overlap_rounds = 32; +constexpr int overlap_threads = 4; +constexpr int overlap_rounds = 16; struct Overlap { const wchar_t* path; @@ -54,14 +55,14 @@ struct Overlap { volatile LONG opened; }; -// Both threads wait for each other before every open, so each round enters the same function at once. +// All threads spin for each other before every open, so each round enters the same function at once. DWORD WINAPI overlap_thread(LPVOID parameter) { auto* shared = static_cast(parameter); for (int round = 0; round < overlap_rounds; ++round) { InterlockedIncrement(&shared->arrived[round]); const ULONGLONG begin = GetTickCount64(); - while (shared->arrived[round] < 2 && GetTickCount64() - begin < 10000) SwitchToThread(); + while (shared->arrived[round] < overlap_threads && GetTickCount64() - begin < 10000) YieldProcessor(); const HANDLE file = CreateFileW(shared->path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (file == INVALID_HANDLE_VALUE) continue; CloseHandle(file); @@ -77,12 +78,15 @@ int overlapping_opens() if (length == 0 || length >= MAX_PATH) return 64; static Overlap shared{}; shared.path = path; - const HANDLE threads[2] = {CreateThread(nullptr, 0, overlap_thread, &shared, 0, nullptr), - CreateThread(nullptr, 0, overlap_thread, &shared, 0, nullptr)}; - if (!threads[0] || !threads[1]) return 65; - const DWORD waited = WaitForMultipleObjects(2, threads, TRUE, 60000); - std::printf("overlap opens %ld of %d\n", static_cast(shared.opened), 2 * overlap_rounds); - return waited == WAIT_OBJECT_0 && shared.opened == 2 * overlap_rounds ? 0 : 1; + HANDLE threads[overlap_threads]{}; + for (HANDLE& thread : threads) { + thread = CreateThread(nullptr, 0, overlap_thread, &shared, 0, nullptr); + if (!thread) return 65; + } + const DWORD waited = WaitForMultipleObjects(overlap_threads, threads, TRUE, 60000); + constexpr int total = overlap_threads * overlap_rounds; + std::printf("overlap opens %ld of %d\n", static_cast(shared.opened), total); + return waited == WAIT_OBJECT_0 && shared.opened == total ? 0 : 1; } } // namespace diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 53956370a1..94989074cd 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -22,7 +22,7 @@ from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file # noqa: E402 import host_cpu # noqa: E402 -from hook_window import StepWindow, HELD, GONE, FAILED # noqa: E402 +from hook_window import StepWindow, ReturnBook, HELD, GONE, FAILED # noqa: E402 class MemoryBasicInformation(ctypes.Structure): @@ -425,7 +425,7 @@ def chunk(kind, payload): breakpoints = {} # addr -> original byte retired = set() # X2W_LOG_AT breakpoints removed at their hit limit late_hits = {} # retired addr -> INT3 events that arrived after the removal - returns = {} # addr -> list of (tid, rsp after return, description) + returns = ReturnBook() 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] @@ -561,13 +561,11 @@ def guid(address): chain = [c for c in chain if not c.lower().startswith(("ntdll", "kernelbase", "kernel32"))] desc += " callers: " + " ".join(chain[:8]) if desc: - returns.setdefault(ret, []).append((tid, rsp + 8, desc)) + returns.add(ret, tid, rsp + 8, desc) arm(ret) - for item in list(returns.get(addr, [])): - if item[0] == tid and item[1] == rsp: - returns[addr].remove(item) - file_log.write(f"{time.time() - start:7.3f} {item[2]} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") - file_log.flush() + for description in returns.take(addr, tid, rsp): + file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") + file_log.flush() # Step over the original instruction, then re-arm. Everyone else is held until the step is done. window.open(tid, [other for other in live_threads if other != tid], time.monotonic()) struct.pack_into(" list of (tid, stack slot, description) + + def add(self, address, tid, slot, description): + kept = [item for item in self._pending.get(address, []) if (item[0], item[1]) != (tid, slot)] + kept.append((tid, slot, description)) + self._pending[address] = kept + + def take(self, address, tid, slot): + """Descriptions of the call that returns here on this thread and slot (at most one).""" + items = self._pending.get(address, []) + done = [item[2] for item in items if (item[0], item[1]) == (tid, slot)] + if done: + self._pending[address] = [item for item in items if (item[0], item[1]) != (tid, slot)] + return done + + class StepWindow: def __init__(self, hold, release, protect=True, limit=2.0): self._hold, self._release = hold, release # hold(tid) -> HELD | GONE | FAILED; release(tid) From 28267132d09a9be4c881cf4286a0a7236176d1fc Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:57:18 +0100 Subject: [PATCH 04/11] startup: count a thread that already exited as gone when holding the others A thread that has called ExitThread stays in the debugger's thread list until its exit event is read. OpenThread still works on it but SuspendThread and GetThreadContext fail with access denied, and the window counted that as an unprotected window although the thread runs no code. A hold that fails is now classified after the failure: GONE when GetExitCodeThread is not STILL_ACTIVE (or the handle is already signaled), FAILED when the thread is alive. The decision is a pure function in hook_window.py checked by startup_hook_window. Refs #1281 --- docs/startup-runtime.md | 2 +- tests/startup_hook_check.py | 22 +++++++++++++++++++++- tools/startup/debug_launch.py | 26 +++++++++++++++++--------- tools/startup/hook_window.py | 18 ++++++++++++++++++ 4 files changed, 57 insertions(+), 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8220beb1c7..39745077fb 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1022,7 +1022,7 @@ keyed by thread id, not shared. Every run ends with `hook windows: entries=N windows=W unprotected=U deferred=D timeouts=T protection=on|off` in the console output, `finished.txt` and `files.txt`, also when everything is 0. `unprotected` counts the windows in which another thread could -not be held, or the deadline passed, or protection was off with other threads alive: an upper bound on the calls a run may have +not be held (a thread that has already exited is not counted: it runs no code), or the deadline passed, or protection was off with other threads alive: an upper bound on the calls a run may have missed. `--suspend-others 0` turns the holding off, to measure what it costs or to see the loss. `tests/startup_hook_check.py` has two parts. `startup_hook_window` checks the bookkeeping with fake threads and needs no diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 76fabc3479..c9acfeeae7 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -20,7 +20,7 @@ TOOLS = Path(__file__).resolve().parents[1] / "tools/startup" sys.path.insert(0, str(TOOLS)) -from hook_window import FAILED, GONE, HELD, ReturnBook, StepWindow # noqa: E402 +from hook_window import FAILED, GONE, HELD, STILL_ACTIVE, ReturnBook, StepWindow, classify_hold # noqa: E402 NAME = "x2w_hook_overlap.dat" OPENS = 64 @@ -101,12 +101,32 @@ def bookkeeping(): assert not window.finish(3) and window.finish(1) and log["released"] == [2] returns_bookkeeping() + hold_outcomes() # The summary is always there, with zeros. line = StepWindow(hold, release).summary(0) assert line == "hook windows: entries=0 windows=0 unprotected=0 deferred=0 timeouts=0 protection=on", line +def hold_outcomes(): + """A thread that called ExitThread but whose EXIT_THREAD event is not read yet cannot be suspended + (access denied). It runs no code, so it is GONE; the same failure on a live thread is FAILED.""" + access_denied = 5 + assert classify_hold(0, signaled=False) == GONE, "exited with code 0" + assert classify_hold(STILL_ACTIVE + 1) == GONE + assert classify_hold(STILL_ACTIVE, signaled=True) == GONE, "exit code not stored yet, handle signaled" + assert classify_hold(None, error=87) == GONE, "no such thread" + assert classify_hold(STILL_ACTIVE) == FAILED, "alive and not suspendable: a real hole" + assert classify_hold(None, error=access_denied) == FAILED, "exit code unknown: not assumed gone" + # The window counts a gone thread as nothing and a live unsuspendable one as unprotected. + for outcome, unprotected in ((classify_hold(0), 0), (classify_hold(STILL_ACTIVE), 1)): + log, hold, release = fakes({2: outcome}) + window = StepWindow(hold, release) + window.open(1, [2, 3], now=0) + assert window.unprotected == unprotected and log["held"] == [3] + window.finish(1) + + def traced_returns(retrapped): """Two threads call from fixed stack slots, 32 calls each. A call in `retrapped` hits its entry hook twice: another thread re-patched the byte before this one ran the original instruction, so diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 94989074cd..4b86246a45 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -22,7 +22,7 @@ from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file # noqa: E402 import host_cpu # noqa: E402 -from hook_window import StepWindow, ReturnBook, HELD, GONE, FAILED # noqa: E402 +from hook_window import StepWindow, ReturnBook, classify_hold, HELD # noqa: E402 class MemoryBasicInformation(ctypes.Structure): @@ -434,18 +434,26 @@ def chunk(kind, payload): sync_addr = (ctypes.addressof(sync_raw) + 15) & ~15 def hold_thread(tid): - handle = k32.OpenThread(0x0002 | 0x0008, False, tid) # SUSPEND_RESUME | GET_CONTEXT + # SUSPEND_RESUME | GET_CONTEXT | QUERY_INFORMATION | SYNCHRONIZE + handle = k32.OpenThread(0x0002 | 0x0008 | 0x0040 | 0x00100000, False, tid) if not handle: - return GONE if ctypes.get_last_error() == 87 else FAILED # 87: no such thread + return classify_hold(None, ctypes.get_last_error()) # SuspendThread returns before the thread has stopped; GetThreadContext waits until it has. struct.pack_into(" Date: Tue, 24 Nov 2026 12:14:46 +0100 Subject: [PATCH 05/11] startup: preserve tail-called hook returns and clarify unprotected count --- docs/startup-runtime.md | 5 ++--- tests/startup_hook_check.py | 14 +++++++++++--- tools/startup/debug_launch.py | 2 +- tools/startup/hook_window.py | 23 +++++++++++++---------- 4 files changed, 27 insertions(+), 17 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 39745077fb..46a78ce963 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1021,9 +1021,8 @@ thread is never held forever. Per-thread state of a call in flight (the return a keyed by thread id, not shared. Every run ends with `hook windows: entries=N windows=W unprotected=U deferred=D timeouts=T protection=on|off` in the -console output, `finished.txt` and `files.txt`, also when everything is 0. `unprotected` counts the windows in which another thread could -not be held (a thread that has already exited is not counted: it runs no code), or the deadline passed, or protection was off with other threads alive: an upper bound on the calls a run may have -missed. `--suspend-others 0` turns the holding off, to measure what it costs or to see the loss. +console output, `finished.txt` and `files.txt`, also when everything is 0. `unprotected` (`U`) counts the exposed step windows in which another thread could +not be held (a thread that has already exited is not counted: it runs no code), or the deadline passed, or protection was off with other threads alive (one exposed window can miss multiple calls). `--suspend-others 0` turns the holding off, to measure what it costs or to see the loss. `tests/startup_hook_check.py` has two parts. `startup_hook_window` checks the bookkeeping with fake threads and needs no Windows. `startup_hook_overlap` runs the source-built `startup_launch_probe` in its `overlap` mode under the debugger: four threads diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index c9acfeeae7..1e01b3368a 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -135,7 +135,7 @@ def traced_returns(retrapped): for call in range(32): for tid in (1, 2): for _ in range(2 if (call, tid) in retrapped else 1): - book.add(0x7000, tid, 0x1000 * tid, f"NtCreateFile call {call}") + book.add(0x7000, tid, 0x1000 * tid, f"NtCreateFile call {call}", 0x5000) lines += len(book.take(0x7000, tid, 0x1000 * tid)) return lines @@ -148,11 +148,19 @@ def returns_bookkeeping(): assert traced_returns(set()) == 64 assert traced_returns(retrapped) == 64, traced_returns(retrapped) book = ReturnBook() - book.add(0x10, 1, 0x100, "a") - book.add(0x10, 2, 0x100, "b") # same slot value on another thread is another call + book.add(0x10, 1, 0x100, "a", 0x5000) + book.add(0x10, 2, 0x100, "b", 0x5000) # same slot value on another thread is another call assert book.take(0x10, 1, 0x100) == ["a"] and book.take(0x10, 1, 0x100) == [] assert book.take(0x10, 2, 0x100) == ["b"] and book.take(0x99, 2, 0x100) == [] + # Tail-calling another hooked function shares (tid, slot) with a different entry address: + # both return records stay, while a re-trap of the same entry replaces only that entry. + book.add(0x20, 1, 0x200, "CreateFileW", 0x5000) + book.add(0x20, 1, 0x200, "NtCreateFile first", 0x6000) + book.add(0x20, 1, 0x200, "NtCreateFile retrapped", 0x6000) + assert book.take(0x20, 1, 0x200) == ["CreateFileW", "NtCreateFile retrapped"] + assert book.take(0x20, 1, 0x200) == [] + def run(probe, scratch, name, options): logdir = scratch / name diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 4b86246a45..8f818bb7b7 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -569,7 +569,7 @@ def guid(address): chain = [c for c in chain if not c.lower().startswith(("ntdll", "kernelbase", "kernel32"))] desc += " callers: " + " ".join(chain[:8]) if desc: - returns.add(ret, tid, rsp + 8, desc) + returns.add(ret, tid, rsp + 8, desc, addr) arm(ret) for description in returns.take(addr, tid, rsp): file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") diff --git a/tools/startup/hook_window.py b/tools/startup/hook_window.py index 6c88babd5a..9f02f49271 100644 --- a/tools/startup/hook_window.py +++ b/tools/startup/hook_window.py @@ -34,22 +34,25 @@ def classify_hold(exit_code, error=0, signaled=False): class ReturnBook: """Pending hooked calls, keyed by return address; each is traced once, when its call returns. - A call is identified by its thread and the stack slot of its return address. The entry hook can - trap twice for one call when protection is off: another thread re-patches the byte before this - one has run the original instruction, so the thread traps again at the same address and slot. - That is the same call, so it replaces the first registration; two entries made the return write - two lines and a run counted 88 opens for 64 made.""" + A call is identified by its thread, the stack slot of its return address, and the hooked entry + address. The entry hook can trap twice for one call when protection is off: another thread + re-patches the byte before this one has run the original instruction, so the thread traps again + at the same entry, thread and slot. That is the same call, so it replaces the first + registration; two entries made the return write two lines and a run counted 88 opens for 64 + made. A hooked function that tail-calls another hooked function shares (tid, slot) with a + different entry address, so both registrations are kept.""" def __init__(self): - self._pending = {} # return address -> list of (tid, stack slot, description) + self._pending = {} # return address -> list of (tid, stack slot, description, entry) - def add(self, address, tid, slot, description): - kept = [item for item in self._pending.get(address, []) if (item[0], item[1]) != (tid, slot)] - kept.append((tid, slot, description)) + def add(self, address, tid, slot, description, entry=None): + kept = [item for item in self._pending.get(address, []) + if (item[0], item[1], item[3]) != (tid, slot, entry)] + kept.append((tid, slot, description, entry)) self._pending[address] = kept def take(self, address, tid, slot): - """Descriptions of the call that returns here on this thread and slot (at most one).""" + """Descriptions of the calls that return here on this thread and slot.""" items = self._pending.get(address, []) done = [item[2] for item in items if (item[0], item[1]) == (tid, slot)] if done: From 11c5fead6ce2974b7694df386a16113d15a34768 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:42:25 +0100 Subject: [PATCH 06/11] startup: treat STATUS_THREAD_IS_TERMINATING from NtSuspendThread as gone; reuse the debug event's thread handle Thanks @RenzoWit35 for the Win11 26300 finding. --- tests/startup_hook_check.py | 8 ++++-- tools/startup/debug_launch.py | 49 ++++++++++++++++++++++++++--------- tools/startup/hook_window.py | 7 +++++ 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 1e01b3368a..0ba06ad7d8 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -20,7 +20,7 @@ TOOLS = Path(__file__).resolve().parents[1] / "tools/startup" sys.path.insert(0, str(TOOLS)) -from hook_window import FAILED, GONE, HELD, STILL_ACTIVE, ReturnBook, StepWindow, classify_hold # noqa: E402 +from hook_window import FAILED, GONE, HELD, STILL_ACTIVE, STATUS_INVALID_HANDLE, STATUS_THREAD_IS_TERMINATING, ReturnBook, StepWindow, classify_hold, classify_status # noqa: E402 NAME = "x2w_hook_overlap.dat" OPENS = 64 @@ -118,8 +118,12 @@ def hold_outcomes(): assert classify_hold(None, error=87) == GONE, "no such thread" assert classify_hold(STILL_ACTIVE) == FAILED, "alive and not suspendable: a real hole" assert classify_hold(None, error=access_denied) == FAILED, "exit code unknown: not assumed gone" + assert classify_status(STATUS_THREAD_IS_TERMINATING) == GONE, "exiting thread, exit code still 259" + assert classify_status(STATUS_INVALID_HANDLE) == GONE + assert classify_status(0xC0000022) == FAILED, "access denied: not assumed gone" # The window counts a gone thread as nothing and a live unsuspendable one as unprotected. - for outcome, unprotected in ((classify_hold(0), 0), (classify_hold(STILL_ACTIVE), 1)): + for outcome, unprotected in ((classify_hold(0), 0), (classify_status(STATUS_THREAD_IS_TERMINATING), 0), + (classify_hold(STILL_ACTIVE), 1)): log, hold, release = fakes({2: outcome}) window = StepWindow(hold, release) window.open(1, [2, 3], now=0) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 8f818bb7b7..f1b6835438 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -19,10 +19,12 @@ k32.CreateJobObjectW.restype = wt.HANDLE k32.CreateFileW.restype = wt.HANDLE k32.SuspendThread.restype = wt.DWORD +ntdll = ctypes.WinDLL("ntdll") +ntdll.NtSuspendThread.restype = ctypes.c_ulong from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file # noqa: E402 import host_cpu # noqa: E402 -from hook_window import StepWindow, ReturnBook, classify_hold, HELD # noqa: E402 +from hook_window import StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 class MemoryBasicInformation(ctypes.Structure): @@ -430,36 +432,53 @@ def chunk(kind, payload): file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace or log_at else None hook_entries = [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))() sync_addr = (ctypes.addressof(sync_raw) + 15) & ~15 def hold_thread(tid): - # SUSPEND_RESUME | GET_CONTEXT | QUERY_INFORMATION | SYNCHRONIZE - handle = k32.OpenThread(0x0002 | 0x0008 | 0x0040 | 0x00100000, False, tid) - if not handle: - return classify_hold(None, ctypes.get_last_error()) + handle = os_handles.get(tid) + owned = handle is None + if owned: # SUSPEND_RESUME | GET_CONTEXT | QUERY_INFORMATION | SYNCHRONIZE + handle = k32.OpenThread(0x0002 | 0x0008 | 0x0040 | 0x00100000, False, tid) + if not handle: + return classify_hold(None, ctypes.get_last_error()) + + def drop(): + if owned: + k32.CloseHandle(wt.HANDLE(handle)) + # SuspendThread returns before the thread has stopped; GetThreadContext waits until it has. struct.pack_into(" Date: Tue, 24 Nov 2026 12:43:23 +0100 Subject: [PATCH 07/11] tests: show the debugger's exit code and stderr when the hook summary is missing --- tests/startup_hook_check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 0ba06ad7d8..544838fd35 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -181,7 +181,7 @@ 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.stdout + 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) From 4593de904fe98dede5133a7bee13f1f398788106 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:43:55 +0100 Subject: [PATCH 08/11] startup: do not shadow the ntdll module used for NtSuspendThread --- tools/startup/debug_launch.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index f1b6835438..6a21ce3d90 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -19,8 +19,8 @@ k32.CreateJobObjectW.restype = wt.HANDLE k32.CreateFileW.restype = wt.HANDLE k32.SuspendThread.restype = wt.DWORD -ntdll = ctypes.WinDLL("ntdll") -ntdll.NtSuspendThread.restype = ctypes.c_ulong +nt_dll = ctypes.WinDLL("ntdll") +nt_dll.NtSuspendThread.restype = ctypes.c_ulong from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file # noqa: E402 import host_cpu # noqa: E402 @@ -451,7 +451,7 @@ def drop(): # SuspendThread returns before the thread has stopped; GetThreadContext waits until it has. struct.pack_into(" Date: Thu, 26 Nov 2026 11:36:54 +0100 Subject: [PATCH 09/11] fix: ask the return book whether a call is pending instead of dict.get The hook window replaced the returns dict with ReturnBook; the hit-limit release still called returns.get(addr), which the class does not have. --- tests/startup_hook_check.py | 8 ++++++++ tools/startup/debug_launch.py | 2 +- tools/startup/hook_window.py | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 544838fd35..53b06a44a9 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -165,6 +165,14 @@ def returns_bookkeeping(): assert book.take(0x20, 1, 0x200) == ["CreateFileW", "NtCreateFile retrapped"] assert book.take(0x20, 1, 0x200) == [] + # The launcher asks whether any call still returns to an address before it lets a hit-limited + # breakpoint run free: a returned call must not keep it armed, a waiting one must. + assert not book.pending(0x20) and not book.pending(0x99) + book.add(0x30, 1, 0x300, "waiting", 0x5000) + assert book.pending(0x30) + book.take(0x30, 1, 0x300) + assert not book.pending(0x30) + def run(probe, scratch, name, options): logdir = scratch / name diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 6bd41ae462..2a7e3a7358 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -610,7 +610,7 @@ def guid(address): struct.pack_into(" Date: Thu, 26 Nov 2026 11:38:53 +0100 Subject: [PATCH 10/11] fix: keep one file_log so X2W_LOG_AT writes to files.txt The merge left a second file_log assignment that opened files.txt only when tracing, overriding the main definition that also opens it for X2W_LOG_AT. startup_debug_log then failed with a None log. --- tools/startup/debug_launch.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 2a7e3a7358..2930d0efdb 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -495,7 +495,6 @@ def release_thread(tid): # A hook step-over restores the original byte for one instruction. Every other thread is held # for that step (--suspend-others 0 turns this off to measure what the window costs). window = StepWindow(hold_thread, release_thread, protect=opts.get("--suspend-others", "1") != "0") - file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace else None def arm(addr, *, skip_int3=False): if addr not in breakpoints: From 08f0f4e9f52396d782815705d4299e7ac7d62e1d Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 11:47:08 +0100 Subject: [PATCH 11/11] ReturnBook: run a call's restore callback when it returns A hooked call may change its arguments for the call only (a mapped drive name). The book now keeps an optional restore per call and runs it once on the return, so the caller's state is back before anything else runs; a re-trap of the same call keeps the first restore. --- tests/startup_hook_check.py | 13 +++++++++++++ tools/startup/hook_window.py | 29 ++++++++++++++++++++--------- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index 53b06a44a9..aaf8a7446c 100644 --- a/tests/startup_hook_check.py +++ b/tests/startup_hook_check.py @@ -165,6 +165,19 @@ def returns_bookkeeping(): assert book.take(0x20, 1, 0x200) == ["CreateFileW", "NtCreateFile retrapped"] assert book.take(0x20, 1, 0x200) == [] + # A restore callback runs once, when its call returns, and only for that call. + undone = [] + book.add(0x40, 1, 0x400, "mapped", 0x5000, restore=lambda: undone.append("first")) + book.add(0x40, 2, 0x400, "other thread", 0x5000, restore=lambda: undone.append("second")) + assert book.take(0x40, 1, 0x400) == ["mapped"] and undone == ["first"] + assert book.take(0x40, 1, 0x400) == [] and undone == ["first"], "a restore must not run twice" + # A re-trap of the same call keeps the first restore (the caller's original state). + book.add(0x50, 1, 0x500, "x", 0x5000, restore=lambda: undone.append("original")) + book.add(0x50, 1, 0x500, "x", 0x5000, restore=lambda: undone.append("rewritten twice")) + book.take(0x50, 1, 0x500) + assert undone == ["first", "second"][:1] + ["original"], undone + assert book.take(0x40, 2, 0x400) == ["other thread"] and undone[-1] == "second" + # The launcher asks whether any call still returns to an address before it lets a hit-limited # breakpoint run free: a returned call must not keep it armed, a waiting one must. assert not book.pending(0x20) and not book.pending(0x99) diff --git a/tools/startup/hook_window.py b/tools/startup/hook_window.py index a8a1bf7d5e..61af3550fd 100644 --- a/tools/startup/hook_window.py +++ b/tools/startup/hook_window.py @@ -50,12 +50,19 @@ class ReturnBook: different entry address, so both registrations are kept.""" def __init__(self): - self._pending = {} # return address -> list of (tid, stack slot, description, entry) + # return address -> list of (tid, stack slot, description, entry, restore) + self._pending = {} - def add(self, address, tid, slot, description, entry=None): - kept = [item for item in self._pending.get(address, []) - if (item[0], item[1], item[3]) != (tid, slot, entry)] - kept.append((tid, slot, description, entry)) + def add(self, address, tid, slot, description, entry=None, restore=None): + """Registers a call. restore, if given, undoes a change made to the call's arguments; it runs + once, when the call returns. A re-trap of the same call keeps the first restore: it holds the + caller's original state, the second one would hold the already changed one.""" + items = self._pending.get(address, []) + for item in items: + if (item[0], item[1], item[3]) == (tid, slot, entry): + restore = item[4] or restore + kept = [item for item in items if (item[0], item[1], item[3]) != (tid, slot, entry)] + kept.append((tid, slot, description, entry, restore)) self._pending[address] = kept def pending(self, address): @@ -63,12 +70,16 @@ def pending(self, address): return bool(self._pending.get(address)) def take(self, address, tid, slot): - """Descriptions of the calls that return here on this thread and slot.""" + """Descriptions of the calls that return here on this thread and slot. Their restore callbacks + have run when this returns.""" items = self._pending.get(address, []) - done = [item[2] for item in items if (item[0], item[1]) == (tid, slot)] - if done: + taken = [item for item in items if (item[0], item[1]) == (tid, slot)] + if taken: self._pending[address] = [item for item in items if (item[0], item[1]) != (tid, slot)] - return done + for item in taken: + if item[4]: + item[4]() + return [item[2] for item in taken] class StepWindow: