Skip to content
6 changes: 5 additions & 1 deletion docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<thread ID>` and `gap_ms=<milliseconds>`.
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 <seconds>` (`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_<sss>s.png`, with the seconds
Expand Down Expand Up @@ -916,7 +920,7 @@ It writes:
| File | Content |
|---|---|
| `<log>.out` | why the run stopped: exception, registers, stack, likely return addresses, raw stack |
| `<log>/events.txt` | module loads and every exception with its time |
| `<log>/events.txt` | module loads and exception times. Exception and debugger stop lines end with `tid=<thread ID>`. |
| `<log>/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) |
| `<log>/files.txt` | every file the process opened |
| `<log>/translate.txt` | with `-Translate`: one line per shader request translated during the run |
Expand Down
109 changes: 108 additions & 1 deletion tests/startup_debug_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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("<IIQQI124xI", code, 0, 0, address, 0, 1)

call = (exception(worker_tid, breakpoint, entry), exception(worker_tid, single_step, entry + 1),
exception(worker_tid, breakpoint, return_site))
create_worker = (launcher.CREATE_THREAD, worker_tid, struct.pack("<Q", worker_tid))
events = iter([
(launcher.CREATE_PROCESS, main_tid, struct.pack("<QQQQ", 0, 0, main_tid, image_base)),
(launcher.LOAD_DLL, main_tid, struct.pack("<QQ", 1, movie_base)),
exception(main_tid, breakpoint, 0x7ff00000),
create_worker, *call, *call,
(launcher.EXIT_THREAD, worker_tid, b""),
create_worker, *call,
(launcher.EXIT_PROCESS, main_tid, b""),
])
rsp = stack

def wait_for_event(event, _timeout):
nonlocal rsp
code, tid, payload = next(events)
struct.pack_into("<III", event, 0, code, pid, tid)
event[16:] = payload.ljust(len(event) - 16, b"\0")
if code == launcher.EXCEPTION:
address = struct.unpack_from("<Q", payload, 16)[0]
rsp = stack + 8 if address == return_site else stack
return True

def read_memory(_process, address, buffer, size, count):
data = struct.pack("<Q", return_site) if address.value == stack else b"\x90"
assert len(data) == size, (address.value, size)
buffer[:] = data
count._obj.value = len(data)
return True

def get_context(_thread, context):
ctypes.c_uint64.from_address(context.value + 0x98).value = rsp
return True

kernel = Mock()
kernel.CreateJobObjectW.return_value = 1
kernel.CreateProcessW.return_value = True
kernel.GetModuleHandleW.return_value = 1
kernel.LoadLibraryExW.return_value = local_base
kernel.GetProcAddress.side_effect = (
lambda module, name: module + (entry - movie_base)
if module == local_base and name == HOOKED_EXPORT.encode() else 0
)
kernel.WaitForDebugEvent.side_effect = wait_for_event
kernel.OpenThread.side_effect = lambda _access, _inherit, tid: tid
kernel.GetThreadContext.side_effect = get_context
kernel.ReadProcessMemory.side_effect = read_memory
kernel.WriteProcessMemory.return_value = True
kernel.VirtualQueryEx.return_value = 0
ntdll = Mock()
ntdll.NtSuspendThread.return_value = 0
logdir = work / "trace-gap-thread-exit"
argv = [str(DEBUG), str(work / "fake.exe"), str(work), str(logdir), "--timeout", "0", "--console", "0",
"--offline", "0", "--trace-files", "1", "--trace-calls", "1"]
with (patch.object(sys, "argv", argv), patch.dict(os.environ, clear=True),
patch.multiple(launcher, k32=kernel, nt_dll=ntdll, final_path=lambda _: HOOKED_MODULE,
inheritable_file=lambda _: 1, startup_for_create=lambda si, _: (si, 0, None, ""))):
assert launcher.main() == 0

lines = [line for line in text(logdir / "files.txt").splitlines() if f" {HOOKED_EXPORT} " in line]
assert len(lines) == 3, lines
assert lines[0].endswith(f" tid={worker_tid} gap_ms=n/a"), lines[0]
assert re.search(rf" tid={worker_tid} gap_ms=\d+\.\d{{3}}$", lines[1]), lines[1]
assert lines[2].endswith(f" tid={worker_tid} gap_ms=n/a"), lines[2]


def log_probe_state(logdir):
stdout = text(logdir / "stdout.txt")
found = re.search(r"^debug-probe log site (0x[0-9a-f]+) byte (0x[0-9a-f]+) calls (\d+)$", stdout, re.M)
Expand Down Expand Up @@ -130,6 +213,8 @@ def main(probe, calls_dll, group='all'):
sys.path.insert(0, str(DEBUG.parent))
from debug_launch import MOVIE_CALL_HOOKS, MOVIE_MODULE, read_qword, read_stack
if 'hooks' in groups:
from live_view import _LogViewer

require_hooked(HOOKED_MODULE, HOOKED_EXPORT, MOVIE_MODULE, MOVIE_CALL_HOOKS)
# Control: the guard rejects the fixture once its export is dropped from the hook list.
try:
Expand Down Expand Up @@ -188,7 +273,10 @@ def stack_read(address, size):
out, logdir = run(probe, work, "stop", {"X2W_STOP_AT": f"{sites[1]:x}"})
assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out and "first chance" in out, out
events = text(logdir / "events.txt")
assert events.splitlines().count("debugger stop 0x80000003 first-chance") == 1, events
stops = re.findall(r"^debugger stop 0x80000003 first-chance tid=([1-9][0-9]*)$", events, re.M)
assert len(stops) == 1, events
exception_prefix = re.escape(f"exception 0x80000003 breakpoint at {image}+{sites[1]:#x} first-chance")
assert re.search(rf"{exception_prefix} params=\[[^\n]*\] tid={stops[0]}$", events, re.M), events
assert f"breakpoint at {image}+{sites[0]:#x}" in events, events
stacks = text(logdir / "threads_stop.txt")
assert image in stacks and "rip=" in stacks, stacks
Expand Down Expand Up @@ -334,6 +422,7 @@ def stack_read(address, size):
assert f"breakpoint at {image}+{threaded_rva:#x}" not in text(logdir / "events.txt"), text(logdir / "events.txt")
assert len([line for line in text(logdir / "files.txt").splitlines() if " LOG_AT " in line]) == 1
if 'hooks' in groups:
check_trace_gap_after_thread_exit(work)
# Call hooks: off by default, so the 7 export calls stop nothing; with --trace-calls 1 the
# launcher counts each of them (the positive control that the probe reaches the hook).
folder = work / "calls-bin"
Expand All @@ -355,6 +444,24 @@ def stack_read(address, size):
found = re.search(r"bink calls: (.*)", out)
assert (found.group(1).strip() if found else None) == want, (name, out)
assert banners[name] in out, (name, out)
lines = re.findall(rf"^\s*\d+\.\d+ {HOOKED_EXPORT} [^\n]*", text(logdir / "files.txt"), re.M)
# BinkNextFrame logs only its first three returns, while the summary counts all seven.
assert len(lines) == (3 if want else 0), (name, lines)
thread_id = None
for ordinal, line in enumerate(lines, 1):
gap = r"[0-9]+\.[0-9]{3}" if ordinal > 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)")
Expand Down
10 changes: 10 additions & 0 deletions tests/startup_exit_report_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 |",
Expand Down
69 changes: 58 additions & 11 deletions tests/startup_hook_check.py
Original file line number Diff line number Diff line change
@@ -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 <startup_launch_probe.exe> two threads through a hooked function
startup_hook_check.py <startup_launch_probe.exe> 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.
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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})")
Loading
Loading