From 58352a682ef30e4a35895b4fd039bc968effa166 Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Mon, 30 Nov 2026 15:59:19 -0800 Subject: [PATCH] tools: dump threads when a run stops presenting (X2W_DUMP_ON_STALL) X2W_DUMP_AT needs the stall time in advance. X2W_DUMP_ON_STALL= has the startup debugger watch the stand-in's heartbeat frame count in trap.log and write every thread's stack once it has not changed for that long, at most three times. The decision is in stall_watch.py, with a device-free check and two controls that must fail. Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 1 + .../python-linux/startup_stall_watch.txt | 2 + tests/cmake/startup_stall_watch.cmake | 10 ++ tests/startup_stall_watch_check.py | 92 +++++++++++++++++++ tools/startup/debug_launch.py | 28 ++++++ tools/startup/stall_watch.py | 34 +++++++ 6 files changed, 167 insertions(+) create mode 100644 tests/checks/python-linux/startup_stall_watch.txt create mode 100644 tests/cmake/startup_stall_watch.cmake create mode 100644 tests/startup_stall_watch_check.py create mode 100644 tools/startup/stall_watch.py diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0c43bfaeb6..43c8815c67 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1889,6 +1889,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_LOG_AT=[@][:[;...]][,...]` | logs the elapsed time, thread ID, main-image instruction RVA, hit number and selected values to `files.txt`. RVAs and offsets are hexadecimal. The hit limit is decimal and defaults to 16 per RVA. Items are `rax`, `rcx`, `rdx`, `rbx`, `rsp`, `rbp`, `rsi`, `rdi`, `r8` through `r15`, or `[reg+hex]` / `[reg-hex]` for a qword read (`unreadable` on failure). Omit the item list to log all 16 registers. At the limit the debugger restores the original instruction unless another hook shares the breakpoint. INT3 events that other threads raised before the restore are resumed at the restored instruction, not logged, and counted on a separate `LOG_AT late hits resumed after the limit` summary line. Malformed entries (including a repeated item, compared by register and offset) and unusable breakpoints are reported in `events.txt`. The end summary lists logged hits per RVA. Fixture: `ctest --preset dev --no-tests=error -R '^startup_debug' -V`. | | `X2W_NOP_SOFT_ASSERTS=1` | after `-ContinueAsserts` steps over a main-image `int3` for the first time, the startup debugger replaces its `cc` byte with a `NOP`, so a routine that traps once per chunk runs at native speed. The patch lasts for the life of the process and only targets RVAs of the main image; `X2W_STOP_AT` sites are never patched. `DBG_CONTINUE` already bypasses the title's handler, so the visible behavior is unchanged. Once a site is patched it no longer raises an exception and `asserts_seen` stops counting it, so the `--continue-asserts N` budget no longer measures real hits at that site | | `X2W_DUMP_AT=[,...]` | the startup debugger writes every thread's stack to `threads_.txt` at those times, for a run that stalls before a watchdog or the timeout ends it | +| `X2W_DUMP_ON_STALL=` | the startup debugger writes every thread's stack to `threads_stall_.txt` once the stand-in's `x2w-d3d12 heartbeat:` frame count in `trap.log` has not changed for that long, then again after each further stall of that length, at most three times (`tools/startup/stall_watch.py`). For a stall whose start is not known in advance, such as a title watchdog that ends the run some time after presents stop. `ctest --preset dev --no-tests=error -R '^startup_stall_watch'` (both controls must fail) | | `X2W_VALLOC_MIN=` | the startup debugger logs each virtual-memory allocation of at least that size to `files.txt` (`VALLOC`), with the requested address (0 for any, unreadable for an incomplete read), size, type, protection and the main-image and stand-in return addresses on the caller's stack | | `X2W_HOST_CPU=1` (`run.ps1 -HostCpu`) | the startup debugger rewrites main-image instructions the host processor lacks at their first fault: see [Host processors without the console's instructions](#host-processors-without-the-consoles-instructions) | diff --git a/tests/checks/python-linux/startup_stall_watch.txt b/tests/checks/python-linux/startup_stall_watch.txt new file mode 100644 index 0000000000..69208fefca --- /dev/null +++ b/tests/checks/python-linux/startup_stall_watch.txt @@ -0,0 +1,2 @@ +# X2W_DUMP_ON_STALL decisions (tools/startup/stall_watch.py) +tests/startup_stall_watch_check.py diff --git a/tests/cmake/startup_stall_watch.cmake b/tests/cmake/startup_stall_watch.cmake new file mode 100644 index 0000000000..3994f16f0b --- /dev/null +++ b/tests/cmake/startup_stall_watch.cmake @@ -0,0 +1,10 @@ +# When tools/startup/debug_launch.py's X2W_DUMP_ON_STALL dumps threads (tools/startup/stall_watch.py). The two +# controls are wrong decisions the check must catch, so they must fail. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_stall_watch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_stall_watch_check.py") + add_test(NAME startup_stall_watch_no_reset_control COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_stall_watch_check.py" --mutate no-reset) + add_test(NAME startup_stall_watch_early_control COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_stall_watch_check.py" --mutate early) + set_tests_properties(startup_stall_watch_no_reset_control startup_stall_watch_early_control PROPERTIES WILL_FAIL TRUE) +endif() diff --git a/tests/startup_stall_watch_check.py b/tests/startup_stall_watch_check.py new file mode 100644 index 0000000000..6dff48cb30 --- /dev/null +++ b/tests/startup_stall_watch_check.py @@ -0,0 +1,92 @@ +"""tools/startup/stall_watch.py: when X2W_DUMP_ON_STALL dumps threads. + +No dump before the first heartbeat; a dump once the frame count has not changed for the given time; the next dump +only after a further stall of that length; at most three; a new frame count starts the wait again. The --mutate +controls are wrong decisions this check must catch: 'no-reset' keeps counting from the first heartbeat after frames +move on, and 'early' dumps before the first heartbeat. Each must make the check fail. + +usage: startup_stall_watch_check.py [--mutate no-reset|early] +""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup")) +import stall_watch # noqa: E402 +from stall_watch import StallWatch # noqa: E402 + + +def beat(frames: int) -> bytes: + return f"x2w-d3d12 heartbeat: {frames} frames presented in 1.0 s (60.0 fps overall)\n".encode() + + +def mutate(kind: str) -> None: + original = StallWatch.feed + + def no_reset(self, now, text): + found = stall_watch.HEARTBEAT.findall(text) + if found and self.frames is None: + self.frames, self.since = int(found[-1]), now + return False + if found: + self.frames = int(found[-1]) + if self.frames is None or self.dumps >= self.limit or now - self.since < self.after: + return False + self.dumps += 1 + self.since = now + return True + + def early(self, now, text): + if self.frames is None and not stall_watch.HEARTBEAT.findall(text) and now >= self.after: + return True + return original(self, now, text) + + StallWatch.feed = {"no-reset": no_reset, "early": early}[kind] + + +def main() -> int: + if len(sys.argv) == 3 and sys.argv[1] == "--mutate": + mutate(sys.argv[2]) + elif len(sys.argv) != 1: + print(__doc__) + return 2 + failures = [] + + def expect(ok: bool, what: str) -> None: + if not ok: + failures.append(what) + + w = StallWatch(15) + expect(not any(w.feed(t, b"x2w-render startup\n") for t in range(0, 60)), "no dump before the first heartbeat") + expect(not w.feed(60, beat(10)), "the first heartbeat starts the wait") + expect(not w.feed(74, b""), "14 s without a new frame is not a stall") + expect(w.feed(75, b""), "15 s without a new frame dumps") + expect(not w.feed(80, beat(10)), "the same frame count is still a stall") + expect(not w.feed(89, b""), "the next dump waits a further 15 s") + expect(w.feed(90, b""), "second dump after a further 15 s") + expect(not w.feed(91, beat(11) + b"other line\n"), "a new frame count starts the wait again") + expect(not w.feed(105, b""), "frames moved 14 s ago") + expect(w.feed(106, b""), "third dump") + expect(not w.feed(200, b""), "at most three dumps") + expect(w.dumps == 3 and w.frames == 11, "dump count and last frame count") + + m = StallWatch(5) + m.feed(0, beat(1) + beat(2) + beat(3)) + expect(m.frames == 3, "the last heartbeat in the text counts") + try: + StallWatch(0) + failures.append("a zero stall time is refused") + except ValueError: + pass + + for line in failures: + print("FAIL", line) + if failures: + return 1 + print("stall watch: all cases passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 30e8748e59..49b07d4415 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -34,6 +34,7 @@ from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file, startup_for_create # noqa: E402 import host_cpu # noqa: E402 +from stall_watch import StallWatch # noqa: E402 from hook_window import LateBreakpoints, StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 from window_capture import FILE_CAP, Series, png_bytes # noqa: E402 @@ -861,6 +862,31 @@ def dump_threads(path): # X2W_STOP_AT=[,...]: stop at a main-image breakpoint at one of these addresses even while # --continue-asserts would step over it, and write threads_stop.txt. stop_at = {int(r, 16) for r in filter(None, os.environ.get("X2W_STOP_AT", "").split(","))} + # X2W_DUMP_ON_STALL=: write every thread's stack to threads_stall_.txt when the + # stand-in's heartbeat frame count in trap.log has not changed for that long (stall_watch.py), at most three + # times. For a stall whose start is not known in advance. + stall_after = float(os.environ.get("X2W_DUMP_ON_STALL", "0") or 0) + stall_watch = StallWatch(stall_after) if stall_after > 0 else None + stall_read = {"offset": 0, "next": 0.0} + + def poll_stall(now): + if now < stall_read["next"]: + return + stall_read["next"] = now + 1.0 + try: + with open(trap_log, "rb") as handle: + handle.seek(0, os.SEEK_END) + end = handle.tell() + handle.seek(max(stall_read["offset"], end - (1 << 20))) + text = handle.read() + stall_read["offset"] = end + except OSError: + return + if stall_watch.feed(now, text): + elapsed = now - start + log(f"{elapsed:7.3f} no new frame for {stall_after:g} s (last heartbeat {stall_watch.frames} frames): " + "threads dumped") + dump_threads(os.path.join(logdir, f"threads_stall_{elapsed:.0f}.txt")) def poll_watches(): for rva, size in watches: @@ -954,6 +980,8 @@ def capture_loop(): break if dump_at and time.time() - start >= dump_at[0]: dump_threads(os.path.join(logdir, f"threads_{dump_at.pop(0):g}.txt")) + if stall_watch: + poll_stall(time.time()) if watches and time.time() >= watch_next: watch_next = time.time() + 1.0 poll_watches() diff --git a/tools/startup/stall_watch.py b/tools/startup/stall_watch.py new file mode 100644 index 0000000000..3057bbc3da --- /dev/null +++ b/tools/startup/stall_watch.py @@ -0,0 +1,34 @@ +"""When a run has stopped presenting: the decision behind X2W_DUMP_ON_STALL (tools/startup/debug_launch.py). + +The stand-in writes "x2w-d3d12 heartbeat: frames presented ..." to the run's log while frames are presented. A +run whose frame count has not changed for `after` seconds is stalled; the debugger then writes every thread's stack. +After a dump the next one needs a further stall of the same length, and at most `limit` dumps are written. Nothing is +reported before the first heartbeat (startup), and a new frame count starts the wait again. +""" +from __future__ import annotations + +import re + +HEARTBEAT = re.compile(rb"x2w-d3d12 heartbeat: (\d+) frames presented") + + +class StallWatch: + def __init__(self, after: float, limit: int = 3): + if not after > 0: + raise ValueError("expected a positive number of seconds") + self.after, self.limit = float(after), limit + self.frames: int | None = None + self.since = 0.0 + self.dumps = 0 + + def feed(self, now: float, text: bytes) -> bool: + """Takes the log text written since the last call; True when the threads should be dumped now.""" + found = HEARTBEAT.findall(text) + if found and int(found[-1]) != self.frames: + self.frames, self.since = int(found[-1]), now + return False + if self.frames is None or self.dumps >= self.limit or now - self.since < self.after: + return False + self.dumps += 1 + self.since = now + return True