diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c838ba024..3a974af543 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4722,6 +4722,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) find_program(STARTUP_POWERSHELL NAMES powershell pwsh REQUIRED) add_test(NAME startup_stage_package COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stage_package_check.py" "${STARTUP_POWERSHELL}") diff --git a/docs/experiments.md b/docs/experiments.md index 13e4d28d40..052a7efc3b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16733,6 +16733,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`): @@ -17035,6 +17037,15 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc 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 +``` + ### Startup shader translator: `v_bfm_b32` `tools/startup/gfx2hlsl.py` now lowers the gfx1013 bit-field mask `v_bfm_b32` (a VOP3-only instruction: the bare and `_e64` spellings translate, `_e32` is refused) that it used to refuse. The result is a mask of S0[4:0] ones shifted left by S1[4:0], emitted as `(((1u << (a & 31)) - 1) << (b & 31))`, so a width of 0 gives 0 and a shift past the top drops the bits. `v_bfm_b32` is a row of `tests/startup_gfx2hlsl_bit_alu_check.py`: the emitted text runs on its integer evaluator over 1368 width/offset pairs against a plain-integer reference, a swapped width/offset mutation must read other words, and the `draw` mode renders the translated pixel stage on the adapter (FXC 5_1 and DXC 6_0) and reads the words back. Source modifiers, `clamp` and output modifiers are refused with `Unsupported`, as for the sibling integer operations. The WARP draw of the same formula is the existing `pixel_aot_bfm_` test. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976eb0a8a2..781c3fc7aa 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1538,6 +1538,31 @@ 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` (`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 +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 +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_debug_check.py b/tests/startup_debug_check.py index f0e78798a1..b0900a5922 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -254,6 +254,8 @@ def stack_read(address, size): {"X2W_LOG_AT": ",".join((*malformed, entry, *(f"{rva:x}:rax" for rva in unusable), entry))}, options=("--continue-asserts", "10", "--offline", "0")) assert "process exited with 0x00000000" in out and f"LOG_AT hit counts: +{log_rva:x} x2\n" in out, out + assert re.search(r"^ hook windows: entries=\d+ windows=\d+ unprotected=0 " + r"deferred=\d+ timeouts=0 protection=on$", out, re.M), out assert log_probe_state(logdir) == (log_rva, opcode), text(logdir / "stdout.txt") assert log_at_records(logdir, log_rva, 2) == [ f"rdx={LOG_TOKEN + i:#x} [rcx+8]=0x89abcdef01234567 " diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py new file mode 100644 index 0000000000..aaf8a7446c --- /dev/null +++ b/tests/startup_hook_check.py @@ -0,0 +1,236 @@ +"""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, STILL_ACTIVE, STATUS_INVALID_HANDLE, STATUS_THREAD_IS_TERMINATING, ReturnBook, StepWindow, classify_hold, classify_status # 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 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, [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] + + 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" + 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_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) + 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 + 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}", 0x5000) + 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", 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) == [] + + # 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) + 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 + 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.returncode, result.stdout, result.stderr[-2000:]) + 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 (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): + 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" + 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 lost + 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 lost {lost})") diff --git a/tests/startup_launch_probe.cpp b/tests/startup_launch_probe.cpp index ffd664853e..b71e889b99 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 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 @@ -47,11 +48,56 @@ void spawn_second_process(const wchar_t* self) CloseHandle(child.hProcess); std::printf("spawn ok\n"); } +constexpr int overlap_threads = 4; +constexpr int overlap_rounds = 16; + +struct Overlap { + const wchar_t* path; + volatile LONG arrived[overlap_rounds]; + volatile LONG opened; +}; + +// 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] < 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); + 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; + 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 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 e4ce8bf55b..b6972580ff 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -1,6 +1,7 @@ """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] [--capture-every S] +usage: debug_launch.py [--timeout S] [--memory-gib N] [--stop-first-chance 1] + [--suspend-others 0] [--capture-every S] 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. @@ -22,9 +23,13 @@ k32.OpenThread.restype = wt.HANDLE k32.CreateJobObjectW.restype = wt.HANDLE k32.CreateFileW.restype = wt.HANDLE +k32.SuspendThread.restype = wt.DWORD +nt_dll = ctypes.WinDLL("ntdll") +nt_dll.NtSuspendThread.restype = ctypes.c_ulong 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 window_capture import FILE_CAP, Series, png_bytes # noqa: E402 @@ -457,9 +462,62 @@ 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] + 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): + 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(" {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() 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(" list of (tid, stack slot, description, entry, restore) + self._pending = {} + + 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): + """Whether any call is still waiting to return to this address (any thread).""" + return bool(self._pending.get(address)) + + def take(self, address, tid, 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, []) + 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)] + for item in taken: + if item[4]: + item[4]() + return [item[2] for item in taken] + + +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) + 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.""" + 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 + 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 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 tid not in self._held: + 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)