diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 040ae3e4b2..0cfb65a914 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -867,6 +867,10 @@ that its fixture's module and export are in that list, that a source-built DLL l movie-player module name is not hooked by default, that each of its 7 export calls is counted with `--trace-calls 1`, and that `--trace-calls 1` with file tracing off counts nothing and says why. +Each traced call return in `files.txt` ends with `tid=` and `gap_ms=`. +The gap measures time since that thread's previous logged return. The first return has `gap_ms=n/a`, +including when a new thread reuses the ID of a thread that exited. + **Window pictures.** At the end of a run that is still going, `debug_launch.py` saves the client area of the title's window as `window.png`. `--capture-every ` (`run.ps1 -CaptureEvery`, `run.sh --capture-every`) also saves it every N seconds (N is at least 1; 0, the default, is off) as `window_s.png`, with the seconds @@ -916,7 +920,7 @@ It writes: | File | Content | |---|---| | `.out` | why the run stopped: exception, registers, stack, likely return addresses, raw stack | -| `/events.txt` | module loads and every exception with its time | +| `/events.txt` | module loads and exception times. Exception and debugger stop lines end with `tid=`. | | `/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) | | `/files.txt` | every file the process opened | | `/translate.txt` | with `-Translate`: one line per shader request translated during the run | diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index 299e407ff8..6a8e4989d5 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -21,14 +21,17 @@ export names must be among the ones the launcher hooks, so the check cannot pass with nothing hooked, and --trace-calls 1 without file tracing must count nothing and say why. """ +import ctypes import os from pathlib import Path import re import shutil +import struct import subprocess import sys import tempfile import time +from unittest.mock import Mock, patch REPO = Path(__file__).resolve().parents[1] DEBUG = REPO / "tools/startup/debug_launch.py" @@ -101,6 +104,86 @@ def require_hooked(module, export, hooked_module, hooked_exports): raise AssertionError(f"{module}!{export} is not hooked by debug_launch.py ({hooked_module}: {hooked_exports})") +def check_trace_gap_after_thread_exit(work): + """Replay two lifetimes of one numeric thread ID through the debugger's event loop.""" + import debug_launch as launcher + + pid, main_tid, worker_tid = 1, 10, 12 + image_base, movie_base, local_base = 0x140000000, 0x180000000, 0x10000000 + entry, return_site, stack = movie_base + 0x1000, image_base + 0x2000, 0x8000 + breakpoint, single_step = 0x80000003, 0x80000004 + + def exception(tid, code, address): + # The exception record ends at offset 152, followed by the first-chance flag. + return launcher.EXCEPTION, tid, struct.pack(" 1 else "n/a" + call = re.search(rf" -> {ordinal:#010x} tid=([1-9][0-9]*) gap_ms={gap}$", line) + assert call, line + if thread_id is None: + thread_id = call[1] + assert call[1] == thread_id, lines + if lines: + shown = [] + viewer = _LogViewer() + viewer.say = lambda tag, message: shown.append((tag, message)) + viewer.on_file(lines[0]) + expected = lines[0].split(None, 1)[1].split(" from ", 1)[0].strip() + assert shown == [("movie", expected)], shown print(f"startup_debug[{group}]: PASS (stop at a chosen assert, timed thread dump, large-allocation log, debug heap off, " "soft asserts NOP'd after the first hit when the core group runs, call hooks opt-in, bounded register and qword logging)") diff --git a/tests/startup_exit_report_check.py b/tests/startup_exit_report_check.py index e3135a62bc..56545c7d79 100644 --- a/tests/startup_exit_report_check.py +++ b/tests/startup_exit_report_check.py @@ -78,6 +78,16 @@ def main() -> int: for secret in ("alice", "game.exe", "KERNELBASE", "0x4da6341", "0x55", "0x9000"): assert secret not in stopped, f"exception stop leaked {secret!r}\n{stopped}" + for suffix in ("", " tid=42"): + from_events, from_events_summary = report({ + "events.txt": ( + f" 1.000 exception 0x80000003 breakpoint at app.exe+0x20 first-chance params=[]{suffix}\n" + f"debugger stop 0x80000003 first-chance{suffix}\n" + ), + }) + assert from_events_summary.confirmed_stop == ("0x80000003", "first"), from_events + assert from_events_summary.classification() == "exception stop", from_events + timed_out, timeout_summary = report({"finished.txt": "timeout after 300.00 s\n"}) expect(timed_out, timeout_summary, [ "| Classification | timeout |", "| End time | `300.0` s |", diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py index aaf8a7446c..99331082af 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. @@ -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, trace_call_suffix, +) NAME = "x2w_hook_overlap.dat" OPENS = 64 @@ -101,6 +104,8 @@ def bookkeeping(): assert not window.finish(3) and window.finish(1) and log["released"] == [2] returns_bookkeeping() + trace_call_gaps() + late_breakpoint_bookkeeping() hold_outcomes() # The summary is always there, with zeros. @@ -187,6 +192,42 @@ def returns_bookkeeping(): assert not book.pending(0x30) +def trace_call_gaps(): + previous_returns = {} + assert trace_call_suffix(previous_returns, 12, 0.0) == " tid=12 gap_ms=n/a" + assert trace_call_suffix(previous_returns, 34, 0.005) == " tid=34 gap_ms=n/a" + assert trace_call_suffix(previous_returns, 12, 0.0125) == " tid=12 gap_ms=12.500" + assert trace_call_suffix(previous_returns, 34, 0.020) == " tid=34 gap_ms=15.000" + assert trace_call_suffix(previous_returns, 12, 0.020) == " tid=12 gap_ms=7.500" + + +def late_breakpoint_bookkeeping(): + sites = LateBreakpoints() + base, other_base = 0x10000, 0x20000 + 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 @@ -202,22 +243,28 @@ 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, 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 >= OPENS and unprotected == 0 and timeouts == 0 and protection == "on", (windows, unprotected, timeouts) + 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, (windows, unprotected, timeouts), protection = run(probe, scratch, f"free{attempt}", - ["--suspend-others", "0"]) + 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" + 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: @@ -233,4 +280,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 +} diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 494d0f40be..68813d7344 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -413,9 +413,9 @@ def _check_endpoint_without_commit(failures: list[str]) -> None: def _check_endpoint_second_stop(failures: list[str]) -> None: events = ( - " 10.000 exception 0xC0000005 access violation at a.dll+0x1 first-chance params=[]\n" - " 11.000 exception 0xC0000005 access violation at a.dll+0x1 second-chance params=[]\n" - "debugger stop 0xc0000005 second-chance\n" + " 10.000 exception 0xC0000005 access violation at a.dll+0x1 first-chance params=[] tid=42\n" + " 11.000 exception 0xC0000005 access violation at a.dll+0x1 second-chance params=[] tid=42\n" + "debugger stop 0xc0000005 second-chance tid=42\n" ) report = _endpoint_report({"events.txt": events}) for want in [ diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index c5f794f77e..52f5f4ac8c 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -34,7 +34,9 @@ from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file, startup_for_create # noqa: E402 import host_cpu # noqa: E402 -from hook_window import StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 +from hook_window import ( # noqa: E402 + LateBreakpoints, StepWindow, ReturnBook, classify_hold, classify_status, trace_call_suffix, GONE, HELD, +) from window_capture import FILE_CAP, Series, png_bytes # noqa: E402 @@ -502,6 +504,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 = {} @@ -569,12 +572,16 @@ 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 + late_breakpoints = LateBreakpoints() late_hits = {} # retired addr -> INT3 events that arrived after the removal returns = ReturnBook() + last_call_returns = {} # tid -> monotonic time of its last --trace-calls return line stepping = {} # tid -> addr to re-arm file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace or log_at else None hook_entries = [0] + 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))() @@ -631,11 +638,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, disarmed_steps thread, ctx = get_ctx(tid) if not thread: return False @@ -758,19 +770,36 @@ def guid(address): if desc: # The name is temporary: take() puts the caller's own UNICODE_STRING back (restore) when the # call returns, before anything else runs, so a failure or a retry sees the name it built. - returns.add(ret, tid, rsp + 8, desc, addr, restore) + returns.add(ret, tid, rsp + 8, (desc, arg in ("runtime", "bink")), addr, restore) arm(ret) - for description in returns.take(addr, tid, rsp): - file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") + returned_calls = returns.take(addr, tid, rsp) + for description, traced_call in returned_calls: + suffix = trace_call_suffix(last_call_returns, tid, time.monotonic()) if traced_call else "" + file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}{suffix}\n") file_log.flush() struct.pack_into(" (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. @@ -82,6 +103,14 @@ def take(self, address, tid, slot): return [item[2] for item in taken] +def trace_call_suffix(last_returns, tid, now): + """Record a traced return and format the gap from this thread's previous trace line.""" + previous = last_returns.get(tid) + last_returns[tid] = now + gap_ms = "n/a" if previous is None else f"{(now - previous) * 1000:.3f}" + return f" tid={tid} gap_ms={gap_ms}" + + 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) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index d516728e8d..11683b2e5c 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -167,9 +167,9 @@ RE_COMMIT_PEAK = re.compile(r"x2w-dstorage heartbeat \d{1,10} s: .*?\bcommit peak=(\d{1,10}) MiB\b") RE_FAILURE_CAUSES = re.compile(r"x2w-dstorage heartbeat (\d{1,10}) s: failed requests by cause ((?:[a-z-]+=\d{1,10}(?:\s+|$))+)") RE_CAUSE_COUNT = re.compile(r"([a-z-]+)=(\d{1,10})") -# debug_launch.py events.txt: " exception at first|second-chance params=[...]". +# debug_launch.py events.txt: " exception at first|second-chance params=[...] tid=". RE_EXCEPTION = re.compile(r"^\s*\d+\.\d+\s+exception\s+(0x[0-9a-fA-F]{8})\b.*?\b(first|second)-chance\b") -RE_DEBUGGER_STOP = re.compile(r"^debugger stop (0x[0-9a-fA-F]{8}) (first|second)-chance$") +RE_DEBUGGER_STOP = re.compile(r"^debugger stop (0x[0-9a-fA-F]{8}) (first|second)-chance(?: tid=[0-9]{1,10})?$") RE_STOP_SUMMARY = re.compile( r"^stopped at [^(]+\((0x[0-9a-fA-F]{8})\) at .+ after \d+\.\d+ s \((first|second) chance\) params=\[" )