Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 48 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,
)

NAME = "x2w_hook_overlap.dat"
OPENS = 64
Expand Down Expand Up @@ -101,6 +104,7 @@ def bookkeeping():
assert not window.finish(3) and window.finish(1) and log["released"] == [2]

returns_bookkeeping()
late_breakpoint_bookkeeping()
hold_outcomes()

# The summary is always there, with zeros.
Expand Down Expand Up @@ -187,6 +191,33 @@ def returns_bookkeeping():
assert not book.pending(0x30)


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 +233,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 +270,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})")
52 changes: 51 additions & 1 deletion tests/startup_launch_probe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,55 @@ int overlapping_opens()
std::printf("overlap opens %ld of %d\n", static_cast<long>(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<int>(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)
Expand All @@ -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");
Expand Down Expand Up @@ -144,4 +194,4 @@ int main(int argc, char** argv)
}
if (std::strcmp(mode, "noop") == 0) return 0;
return 64;
}
}
55 changes: 43 additions & 12 deletions tools/startup/debug_launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

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 LateBreakpoints, StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402
from window_capture import FILE_CAP, Series, png_bytes # noqa: E402


Expand Down Expand Up @@ -502,6 +502,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 = {}
Expand Down Expand Up @@ -569,12 +570,15 @@ 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()
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))()
Expand Down Expand Up @@ -631,11 +635,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
Expand Down Expand Up @@ -760,17 +769,33 @@ def guid(address):
# 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)
arm(ret)
for description in returns.take(addr, tid, rsp):
descriptions = returns.take(addr, tid, rsp)
for description in descriptions:
file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n")
file_log.flush()
struct.pack_into("<Q", ctx, 0xF8, addr)
# After the final logged hit, let the restored instruction run at full speed unless
# another hook still owns this breakpoint.
if (point and logged_hits[rva] == point[0] and addr not in hooks and not returns.pending(addr)
and write(addr, breakpoints[addr])):
del breakpoints[addr]
retired.add(addr)
log_at_done = point and logged_hits[rva] == point[0]
last_return = window.protect and descriptions and not point and breakpoints[addr] != b"\xcc"
if (log_at_done or last_return) and addr not in hooks and not returns.pending(addr):
if write(addr, breakpoints[addr]):
del breakpoints[addr]
region = query_region(addr)
# AllocationBase identifies the image even when the hook is in a later section. Without it the
# site is still kept (as before this change), only no unload can drop it.
late_breakpoints.add(addr, region.AllocationBase if region else None,
"X2W_LOG_AT" if log_at_done else "return")
if not log_at_done:
disarmed_steps += 1
set_ctx(thread)
return True
if addr in emulated_hooks and addr in hooks and arg not in ("count", "runtime", "bink"):
# The armed byte stays in place while this thread advances past mov r10, rcx.
struct.pack_into("<Q", ctx, 0xC8, regs["Rcx"])
struct.pack_into("<Q", ctx, 0xF8, addr + 3)
set_ctx(thread)
emulated_steps += 1
return True
# Hold other threads while stepping over the original instruction.
eflags = struct.unpack_from("<I", ctx, 0x44)[0]
Expand Down Expand Up @@ -984,6 +1009,9 @@ def capture_loop():
arm(base + (address - local))
if h_file:
k32.CloseHandle(wt.HANDLE(h_file))
elif code == UNLOAD_DLL:
base = struct.unpack_from("<Q", event, 16)[0]
late_breakpoints.forget_module(base)
elif code == CREATE_THREAD:
log(f"{time.time() - start:7.3f} thread {tid} created")
live_threads.add(tid)
Expand Down Expand Up @@ -1014,17 +1042,19 @@ def capture_loop():
handle_breakpoint(tid, ex_addr)
k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE)
continue
if ex_code == 0x80000003 and ex_addr in retired:
# Another thread executed this INT3 before the hit limit restored the original byte,
# and its event arrived after that. Rewind and run the restored instruction.
source = late_breakpoints.rewind_source(ex_addr, read) if ex_code == 0x80000003 else None
if source:
# A thread executed this INT3 before the original byte was restored, and its
# event arrived afterward. Rewind and run the restored instruction.
thread, ctx = get_ctx(tid)
if thread:
struct.pack_into("<Q", ctx, 0xF8, ex_addr)
set_ctx(thread)
late_hits[ex_addr] = late_hits.get(ex_addr, 0) + 1
if source == "X2W_LOG_AT":
late_hits[ex_addr] = late_hits.get(ex_addr, 0) + 1
k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE)
continue
log(f"{time.time() - start:7.3f} X2W_LOG_AT late hit at {where(ex_addr)} on thread {tid}: "
log(f"{time.time() - start:7.3f} {source} late hit at {where(ex_addr)} on thread {tid}: "
f"thread context unavailable (error {ctx_error[0]}), handled as a breakpoint")
if ex_code == 0x80000004 and tid in stepping:
addr = stepping.pop(tid)
Expand Down Expand Up @@ -1203,6 +1233,7 @@ def capture_loop():
", ".join(f"+{addr - main_base:x} x{n}" for addr, n in sorted(late_hits.items())))
report = window.summary(hook_entries[0])
print(" " + report)
print(f" hook emulated: {emulated_steps} disarmed: {disarmed_steps}")
if file_log:
file_log.write(report + "\n")
file_log.flush()
Expand Down
21 changes: 21 additions & 0 deletions tools/startup/hook_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,27 @@ def classify_hold(exit_code, error=0, signaled=False):
return FAILED


class LateBreakpoints:
"""Restored hook sites that can still deliver a queued INT3 event."""

def __init__(self):
self._sites = {} # address -> (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.

Expand Down
Loading