diff --git a/docs/boot.md b/docs/boot.md index 7ec69f0314..b01578a89f 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -80,6 +80,12 @@ Useful switches: `int3_skipped` event, so a boot can be followed past soft asserts (an int3 followed by code that carries on). Diagnostic only: a correct run reaches none, so each skipped address is a finding, not a fix. A failed guest file open is always traced as `file_open_failed` (path, error, caller) when `--trace` is on. +* `LEONIDA_SKIP_ASSERTS=N` steps over up to N int3 in guest code, with or without `--trace`, and prints each one + as `[rt] LEONIDA_SKIP_ASSERTS: int3 at +0x... stepped over (k of N)`; the next one after N ends the run as + before. An int3 in a host module is never stepped over. The same caveat: each skipped address is a finding + ([runtime/README.md](../runtime/README.md), "Guest asserts"). +* The first call of each Xbox device slot that the device proxy forwards by number names its caller: + `[rt] d3d12_xs: device slot N (...) first call from +0x...`, the title's call site without a debugger. * `LEONIDA_VK_VALIDATION=1` enables the Khronos validation layer with the Vulkan backend (startup overhead; it is a diagnostic). * `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 5a214e3258..c4556577b3 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -751,7 +751,10 @@ today. That is an assumption, not a measurement: the Xbox device was measured at 1/14/15/16/18/19/27/38/62/76, and slots 8/9/12/36 are exactly the ones this page needs. If the Xbox slots differ, a generic forward-to-PC thunk calls the wrong method. The current proxy (`runtime/shims/d3d12_xs_device.h:1-18`) forwards every unshadowed slot in PC order and logs -first calls; a wrong slot would therefore be visible as a misnamed call, not a silent success. +first calls; a wrong slot would therefore be visible as a misnamed call, not a silent success. Under gta6rt +the first call of a slot the generic thunk takes by number also names its caller, the return address in the +title's code as `module+RVA` (`device slot 25 (GetResourceAllocationInfo) first call from +0x…`), so the +call site of a slot can be found without a debugger (`set_caller_describer`). Queues and fences are wrapped the same way. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f317958f12..705d9ba8b0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -279,6 +279,16 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8) target_link_options(int3_skip_test PRIVATE /OPT:NOREF) + # LEONIDA_SKIP_ASSERTS (src/assert_skip.h): int3 in a page no host module owns, stepped over up to a limit. + add_executable(assert_skip_test + test/assert_skip_test.cpp + shims/registry.cpp + ) + target_include_directories(assert_skip_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(assert_skip_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(assert_skip_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(assert_skip_test PRIVATE /OPT:NOREF) + # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. add_executable(winhttp_offline_test test/winhttp_offline_test.cpp @@ -1134,6 +1144,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET int3_skip_test) add_test(NAME int3_skip COMMAND int3_skip_test) endif() + if(WIN32 AND TARGET assert_skip_test) + add_test(NAME assert_skip COMMAND assert_skip_test) + endif() if(WIN32 AND TARGET winhttp_offline_test) add_test(NAME winhttp_offline COMMAND winhttp_offline_test) endif() @@ -1277,6 +1290,12 @@ if(BUILD_TESTING) "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) + # LEONIDA_SKIP_ASSERTS (src/assert_skip.h): two int3 in the mapped image, in no host module, are stepped over and + # the game carries on to its normal exit. Without the variable the first one would end the run. + add_test(NAME run_tiny_game_skip_asserts COMMAND gta6rt --run $ -- hello 42 int3) + set_tests_properties(run_tiny_game_skip_asserts PROPERTIES + ENVIRONMENT "LEONIDA_SKIP_ASSERTS=2" + FAIL_REGULAR_EXPRESSION "tiny_game: FAIL|LEONIDA_SKIP_ASSERTS: [^\n]* is not") # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" diff --git a/runtime/README.md b/runtime/README.md index 6803b78bdb..1a4948540d 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -101,6 +101,25 @@ The thunk keeps the Win64 argument registers and the return address intact (it i reaches a shared stub that saves them, so a floating-point caller still reads 0.0 from xmm0 and a debugger can unwind through it. +### Guest asserts: `LEONIDA_SKIP_ASSERTS` + +A title's assert ends in an `int3`. Without a debugger that breakpoint is unhandled and the run ends there. +`LEONIDA_SKIP_ASSERTS=N` (a decimal number, 1 to 1000000; diagnostic, off by default) makes `--init` and `--run` +install a vectored exception handler ([src/assert_skip.h](src/assert_skip.h)) before any image code runs. It steps +over up to N `int3` (the byte 0xCC) at addresses in no host module, the mapped images and code a title wrote +itself, and prints one line for each: + +``` +[rt] LEONIDA_SKIP_ASSERTS: int3 at game.exe+0x1234 stepped over (1 of 3) +``` + +After N it says so once (`3 int3 stepped over; the one at ... is not`) and the next `int3` ends the run as before. An +`int3` in a host module (gta6rt, its shims, a system DLL) is never stepped over. Unset, empty or `0` installs +nothing; any other value is reported and treated as `0`. No `--trace` is needed; with one, each skip is also an +`int3_skipped` event and the trace's own handler records the breakpoint and its stack first. `LEONIDA_SKIP_INT3` +(with `--trace`) is the older switch: it steps over every guest `int3` without a limit and logs each address once; +while a trace is open it runs first. Each skipped address is a finding, not a fix: a correct run reaches none. + ### Compat modules: `LEONIDA_COMPAT_DIR` Opt-in. When `LEONIDA_COMPAT_DIR` names a folder, an import whose DLL is a file in that folder (matched by file name, @@ -445,7 +464,7 @@ from the ANSI code page. | `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) | | `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` | | `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) | -| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) | +| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over; with `LEONIDA_SKIP_ASSERTS` (below): every int3 it steps over | `at` (module+RVA); `skip` (the count, `LEONIDA_SKIP_ASSERTS` only) | | `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | | `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | | `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | @@ -453,7 +472,7 @@ from the ANSI code page. Every line also has `seq` and `t` (seconds since the trace opened). Addresses are `module+0xRVA` for mapped images, `host:name.dll+0xRVA` for host modules. The exception handler only records: it returns `EXCEPTION_CONTINUE_SEARCH`, so the process behaves the same with or without the trace (except under the diagnostic `LEONIDA_SKIP_INT3`, which -steps over int3). It works with any `LEONIDA_UNIMPLEMENTED` policy. +steps over int3; `LEONIDA_SKIP_ASSERTS` steps over int3 with or without the trace). It works with any `LEONIDA_UNIMPLEMENTED` policy. The file can quote what the game prints, so it stays on your machine. In issues and pull requests, share counts or lines from synthetic fixtures only. diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 187406e3d8..8f110b62c3 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -28,6 +28,7 @@ #include #include +#include // _ReturnAddress #include #include @@ -39,6 +40,7 @@ #include #include #include +#include #include namespace rt::d3d12_xs { @@ -155,11 +157,34 @@ const char* slot_name(unsigned slot) { } } -void note_slot(unsigned slot) { +std::atomic g_caller_describer{nullptr}; +std::atomic g_first_caller[kMaxSlots]; + +// `caller` is the return address in the title's code for a slot the generic thunk forwards by number, and null for +// the slots the proxy handles itself. Its first call names the caller as module+RVA (set_caller_describer), so the +// title's call site of a slot is in the log without a debugger. +void note_slot(unsigned slot, const void* caller = nullptr) { if (slot >= kMaxSlots) return; count_hit(g_hits[slot]); const bool first = first_call(g_first[slot]); - if (first) { + if (first && caller) { + g_first_caller[slot].store(caller, std::memory_order_relaxed); + const CallerDescriber describe = g_caller_describer.load(std::memory_order_acquire); + const auto address = reinterpret_cast(caller); + std::string where; + try { + if (describe) where = describe(address); + } catch (...) { + where.clear(); // out of memory: the bare address below; nothing may unwind into the title's frame + } + if (where.empty()) { + char hex[24]; + std::snprintf(hex, sizeof hex, "0x%llx", static_cast(address)); + where = hex; + } + std::fprintf(stderr, "[rt] d3d12_xs: device slot %u (%s) first call from %s\n", slot, slot_name(slot), + where.c_str()); + } else if (first) { std::fprintf(stderr, "[rt] d3d12_xs: device slot %u (%s) first call\n", slot, slot_name(slot)); } else if (slot >= 3 && trace_enabled()) { std::fprintf(stderr, "[rt] d3d12_xs: device slot %u (%s) call\n", slot, slot_name(slot)); @@ -1865,7 +1890,7 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 reinterpret_cast(a5), reinterpret_cast(a6), reinterpret_cast(a7))); } else { - note_slot(Slot); + note_slot(Slot, _ReturnAddress()); // the title's call site, logged with the slot's first call // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. @@ -2041,6 +2066,10 @@ void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook) { g_placed_at_va_pages.store(hook, std::memory_order_release); } +void set_caller_describer(CallerDescriber describe) { + g_caller_describer.store(describe, std::memory_order_release); +} + ID3D12Device* device_proxy_real_device(const void* device) { if (!is_device_proxy(device)) return nullptr; return static_cast(device)->real; @@ -2162,6 +2191,10 @@ bool device_slot_first_call_seen(unsigned slot) { return slot < kMaxSlots && g_first[slot].load(std::memory_order_relaxed); } +const void* device_slot_first_caller(unsigned slot) { + return slot < kMaxSlots ? g_first_caller[slot].load(std::memory_order_relaxed) : nullptr; +} + unsigned long device_proxy_ref_count(const void* device) { if (!is_device_proxy(device)) return 0; return static_cast(device)->refs.load(std::memory_order_relaxed); @@ -2201,6 +2234,7 @@ void reset_device_proxy_stats() { for (unsigned slot = 0; slot < kMaxSlots; ++slot) { g_hits[slot].store(0, std::memory_order_relaxed); g_first[slot].store(false, std::memory_order_relaxed); + g_first_caller[slot].store(nullptr, std::memory_order_relaxed); g_beyond_warned[slot].store(false, std::memory_order_relaxed); } for (unsigned slot = 0; slot < kHeapSlots; ++slot) { diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index ac0437215d..0286d2f05a 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -51,6 +51,7 @@ #include #include +#include namespace rt::d3d12_xs { @@ -108,6 +109,18 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler); using PlacedAtVaPagesHook = bool (*)(const void* va, std::size_t bytes); void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook); +// The first call of each slot the generic thunk takes by number (the PC slots it passes through, the Xbox slots it +// routes, 48/73/78/79/80 at their configured indices, and the ones it refuses past the PC table; not 0-2, 8, 9, 12, +// 14, 31, 32, 34-36, 45, 46, 50, 62, 67, 75, 76 and 133, which have handlers of their own) is logged with its caller, the return address in the title's code: "device slot 25 (GetResourceAllocationInfo) first call +// from game.exe+0x1234". The describer turns that address into the text; gta6rt registers rt::shims::module_offset +// (module+RVA for a mapped image, host:name.dll+RVA for a host module). With none, or an empty answer, the bare +// address is logged. Called at most once per slot, from the title's thread. +using CallerDescriber = std::string (*)(std::uint64_t address); +void set_caller_describer(CallerDescriber describe); +// That caller (null before the slot's first forwarded call, and for the slots the proxy handles itself). Test helper; +// reset_device_proxy_stats clears it with the first-call flag. +const void* device_slot_first_caller(unsigned slot); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and // 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the diff --git a/runtime/src/assert_skip.h b/runtime/src/assert_skip.h new file mode 100644 index 0000000000..9565d8dbdf --- /dev/null +++ b/runtime/src/assert_skip.h @@ -0,0 +1,151 @@ +#pragma once + +// LEONIDA_SKIP_ASSERTS=N (diagnostic, off by default): step over up to N int3 breakpoints in guest code. +// +// A title's assert ends in an int3 (0xCC). With a debugger attached that is a stop to look at; without one it is an +// unhandled EXCEPTION_BREAKPOINT and the run ends there. gta6rt installs this vectored handler when the variable is a +// number above 0 (main.cpp, before any image code runs). For an EXCEPTION_BREAKPOINT whose address is in no host +// module (the Windows loader knows none at that address: the mapped game images, or code a title wrote itself) and +// whose byte there is 0xCC, it logs one line, moves RIP past the int3 and continues; after N of them it stops doing so, +// says so once, and the next int3 ends the run as before. An int3 in a host module (gta6rt, its shims, a system DLL, +// DbgBreakPoint) is never stepped over. +// +// RIP: on Windows x64 an int3's ExceptionAddress and the context's RIP both name the 0xCC (the kernel backs RIP up +// over it), and Wine reports the same; the handler also takes a RIP one past the 0xCC, which it leaves as it is. +// Any other RIP is not this int3's, and the exception is passed on. +// +// Unlike LEONIDA_SKIP_INT3 (startup_trace.h), it needs no --trace, counts every int3 rather than each address once, +// and stops after N, so a loop of asserts can't spin forever. With --trace each skip is also an `int3_skipped` event, +// and the trace's own handler, which runs first, records the exception and its stack. The handler is added last, so +// every other vectored handler sees the breakpoint first. Each skipped address is a finding, not a fix: a correct run +// reaches none. +// +// The log lines quote addresses as module+RVA only; they stay on the player's machine like the startup trace does. + +#include + +#include +#include +#include +#include +#include +#include + +#include "../shims/shims.h" +#include "../shims/startup_trace.h" + +namespace rt::assert_skip { + +inline constexpr wchar_t kVariable[] = L"LEONIDA_SKIP_ASSERTS"; +// Far above any useful count; it only keeps the number in an unsigned. +inline constexpr unsigned long kMaxLimit = 1000000; + +// The limit LEONIDA_SKIP_ASSERTS asks for: 0 when the text is null or empty, "0", or not a decimal number in +// 0..kMaxLimit (then `*valid`, when given, is false). +inline unsigned parse_limit(const wchar_t* text, bool* valid = nullptr) { + if (valid) *valid = true; + if (!text || !*text) return 0; + if (*text < L'0' || *text > L'9') { // no sign, no leading space: wcstoul would take "-1" as ULONG_MAX + if (valid) *valid = false; + return 0; + } + errno = 0; + wchar_t* end = nullptr; + const unsigned long n = std::wcstoul(text, &end, 10); + if (errno != 0 || !end || *end != L'\0' || n > kMaxLimit) { + if (valid) *valid = false; + return 0; + } + return static_cast(n); +} + +// LEONIDA_SKIP_ASSERTS as a limit; a value that is not one is reported on stderr and counts as 0 (off). +inline unsigned limit_from_environment() { + wchar_t value[32] = {}; + const DWORD length = GetEnvironmentVariableW(kVariable, value, 32); + if (length == 0) return 0; + bool valid = false; + const unsigned limit = length < 32 ? parse_limit(value, &valid) : 0; + if (length >= 32 || !valid) + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: expected a number of int3 to step over (0..%lu); off\n", + kMaxLimit); + return limit; +} + +namespace detail { +inline std::atomic limit{0}; +inline std::atomic claimed{0}; // skips handed out, may pass `limit` by the declined ones +inline std::atomic exhausted_logged{false}; +inline void* veh = nullptr; + +// True when the Windows loader knows a module at `address`: gta6rt, its DLLs, system DLLs. The Loader's mapped +// images are not among them. +inline bool in_host_module(const void* address) { + HMODULE module = nullptr; + return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module) && module; +} + +// The byte at `address`, read only when the page is committed and readable. +inline bool read_byte(const void* address, unsigned char& byte) { + MEMORY_BASIC_INFORMATION mbi{}; + if (!address || !VirtualQuery(address, &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) return false; + if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; + const DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + if (!(mbi.Protect & readable)) return false; + byte = *static_cast(address); + return true; +} + +inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { + if (!info || !info->ExceptionRecord || !info->ContextRecord) return EXCEPTION_CONTINUE_SEARCH; + const EXCEPTION_RECORD& r = *info->ExceptionRecord; + if (r.ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH; + const unsigned max = limit.load(std::memory_order_relaxed); + if (max == 0) return EXCEPTION_CONTINUE_SEARCH; + const void* at = r.ExceptionAddress; + const auto at_word = reinterpret_cast(at); + CONTEXT& c = *info->ContextRecord; + if (c.Rip != at_word && c.Rip != at_word + 1) return EXCEPTION_CONTINUE_SEARCH; // not this int3's RIP + unsigned char byte = 0; + if (in_host_module(at) || !read_byte(at, byte) || byte != 0xCC) return EXCEPTION_CONTINUE_SEARCH; + const unsigned n = claimed.fetch_add(1, std::memory_order_relaxed) + 1; + if (n > max) { + if (!exhausted_logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: %u int3 stepped over; the one at %s is not\n", max, + shims::module_offset(at_word).c_str()); + return EXCEPTION_CONTINUE_SEARCH; + } + const std::string where = shims::module_offset(at_word); + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: int3 at %s stepped over (%u of %u)\n", where.c_str(), n, max); + std::fflush(stderr); + startup_trace::event("int3_skipped", "\"at\":" + startup_trace::quote(where) + ",\"skip\":" + std::to_string(n)); + if (c.Rip == at_word) c.Rip = at_word + 1; + return EXCEPTION_CONTINUE_EXECUTION; +} +} // namespace detail + +// Steps over up to `limit` guest int3 from now on (0 removes the handler). Returns false only when the handler could +// not be added. Called once, from main.cpp; tests call it again to start over. +inline bool install(unsigned limit) { + detail::limit.store(0, std::memory_order_relaxed); + if (detail::veh) RemoveVectoredExceptionHandler(detail::veh); + detail::veh = nullptr; + detail::claimed.store(0, std::memory_order_relaxed); + detail::exhausted_logged.store(false, std::memory_order_relaxed); + if (limit == 0) return true; + detail::limit.store(limit, std::memory_order_relaxed); + detail::veh = AddVectoredExceptionHandler(0, &detail::handler); // last: the other handlers see it first + if (!detail::veh) detail::limit.store(0, std::memory_order_relaxed); + return detail::veh != nullptr; +} + +// int3 stepped over since install. +inline unsigned skipped() { + const unsigned claimed = detail::claimed.load(std::memory_order_relaxed); + const unsigned max = detail::limit.load(std::memory_order_relaxed); + return claimed < max ? claimed : max; +} + +} // namespace rt::assert_skip diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index fbb4b3043e..92c8d3801d 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -27,6 +27,7 @@ #include #include +#include "assert_skip.h" #include "base_reservation.h" #include "code_hooks.h" #include "host_cpu.h" @@ -167,11 +168,24 @@ int wmain(int argc, wchar_t** argv) { rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + // The first call of each device slot the proxy forwards by number names its caller as module+RVA. + rt::d3d12_xs::set_caller_describer(&rt::shims::module_offset); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); return 2; } + // LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h): up to N int3 in guest code are logged and stepped over. Off unless + // set; installed before the first TLS callback, the first image code that runs. + if (init || run) + if (const unsigned skip_asserts = rt::assert_skip::limit_from_environment()) { + if (rt::assert_skip::install(skip_asserts)) + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS=%u: up to %u int3 in guest code are stepped over " + "(diagnostic)\n", skip_asserts, skip_asserts); + else + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: AddVectoredExceptionHandler failed (error %lu); off\n", + GetLastError()); + } try { rt::Loader loader(game_dir); diff --git a/runtime/test/assert_skip_test.cpp b/runtime/test/assert_skip_test.cpp new file mode 100644 index 0000000000..6715fa2d79 --- /dev/null +++ b/runtime/test/assert_skip_test.cpp @@ -0,0 +1,135 @@ +// LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h), with synthetic code only: +// - the value: unset, empty and 0 are off; a decimal number up to 1000000 is the limit; anything else is off; +// - off, nothing is installed and an int3 reaches the next handler as before; +// - on, an int3 in memory no host module owns (a page this test writes, as the loader maps a game image) is +// stepped over, logged with its address, and the code after it runs; +// - only N of them: the next one is passed on, as are an int3 in a host module (this executable's own +// __debugbreak) and a breakpoint whose address holds no 0xCC (the two-byte `int 3`). +// A fallback vectored handler added after the one under test stands in for "the run ends": it counts what reaches it +// and steps over it, so the test keeps going. No game data, no mapped images. +#include + +#include +#include +#include + +#include "assert_skip.h" + +namespace { + +int g_failed = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "ok " : "FAIL ", what); + if (!ok) ++g_failed; +} + +// What the handler under test passed on. +volatile LONG g_passed_on = 0; +// What it saw for RIP in the first breakpoint (Windows and Wine report the 0xCC's own address). +volatile LONG g_rip_at_int3 = -1; + +LONG CALLBACK fallback(EXCEPTION_POINTERS* info) { + if (info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH; + const auto at = reinterpret_cast(info->ExceptionRecord->ExceptionAddress); + InterlockedIncrement(&g_passed_on); + if (g_rip_at_int3 < 0) InterlockedExchange(&g_rip_at_int3, info->ContextRecord->Rip == at ? 1 : 0); + if (info->ContextRecord->Rip == at) info->ContextRecord->Rip += 1; // over the one-byte int3 + return EXCEPTION_CONTINUE_EXECUTION; +} + +// int3; mov eax, imm32; ret. The value shows that the code after the int3 ran. +using Site = int (*)(); +Site write_site(unsigned char* at, std::uint32_t value) { + const unsigned char code[] = {0xCC, 0xB8, 0, 0, 0, 0, 0xC3}; + std::memcpy(at, code, sizeof code); + std::memcpy(at + 2, &value, sizeof value); + return reinterpret_cast(at); +} + +__declspec(noinline) int host_int3() { + __debugbreak(); + return 7; +} + +} // namespace + +int main() { + SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + std::setvbuf(stdout, nullptr, _IONBF, 0); + namespace as = rt::assert_skip; + + bool valid = false; + check(as::parse_limit(nullptr, &valid) == 0 && valid, "a null value is off"); + check(as::parse_limit(L"", &valid) == 0 && valid, "an empty value is off"); + check(as::parse_limit(L"0", &valid) == 0 && valid, "0 is off"); + check(as::parse_limit(L"3", &valid) == 3 && valid, "3 is a limit of 3"); + check(as::parse_limit(L"1000000", &valid) == 1000000 && valid, "1000000 is the largest limit"); + check(as::parse_limit(L"1000001", &valid) == 0 && !valid, "1000001 is refused"); + check(as::parse_limit(L"-1", &valid) == 0 && !valid, "a negative number is refused"); + check(as::parse_limit(L" 2", &valid) == 0 && !valid, "a leading space is refused"); + check(as::parse_limit(L"2x", &valid) == 0 && !valid, "trailing text is refused"); + check(as::parse_limit(L"yes", &valid) == 0 && !valid, "text is refused"); + SetEnvironmentVariableW(L"LEONIDA_SKIP_ASSERTS", nullptr); + check(as::limit_from_environment() == 0, "unset in the environment: off"); + SetEnvironmentVariableW(L"LEONIDA_SKIP_ASSERTS", L"2"); + check(as::limit_from_environment() == 2, "LEONIDA_SKIP_ASSERTS=2 in the environment: 2"); + SetEnvironmentVariableW(L"LEONIDA_SKIP_ASSERTS", L"many"); + check(as::limit_from_environment() == 0, "LEONIDA_SKIP_ASSERTS=many in the environment: off"); + + // Executable memory no host module owns, the way the loader maps a title's image. + auto* page = static_cast( + VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); + check(page != nullptr, "allocate an executable page"); + if (!page) return 1; + HMODULE owner = nullptr; + check(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(page), &owner), + "the page is in no host module"); + const Site a = write_site(page, 0x41); + const Site b = write_site(page + 16, 0x42); + const Site c = write_site(page + 32, 0x43); + FlushInstructionCache(GetCurrentProcess(), page, 4096); + + void* const fallback_handler = AddVectoredExceptionHandler(0, &fallback); + check(fallback_handler != nullptr, "add the fallback handler"); + + // Off: the int3 reaches the fallback, which stands in for the end of the run. + check(as::install(0) && as::skipped() == 0, "install(0) adds nothing"); + check(a() == 0x41 && g_passed_on == 1, "off: a guest int3 is passed on"); + check(g_rip_at_int3 == 1, "the breakpoint's RIP is the 0xCC's own address"); + + // On, limit 2. The handler is added last, so it must come before the fallback to see anything: remove the + // fallback and add it again behind it. + RemoveVectoredExceptionHandler(fallback_handler); + check(as::install(2), "install(2) adds the handler"); + void* const fallback_again = AddVectoredExceptionHandler(0, &fallback); + check(fallback_again != nullptr, "add the fallback handler behind it"); + check(a() == 0x41 && as::skipped() == 1 && g_passed_on == 1, "the first guest int3 is stepped over"); + check(b() == 0x42 && as::skipped() == 2 && g_passed_on == 1, "the second, at another address, too"); + check(host_int3() == 7 && as::skipped() == 2 && g_passed_on == 2, "an int3 in a host module is passed on"); + check(c() == 0x43 && as::skipped() == 2 && g_passed_on == 3, "past the limit, a guest int3 is passed on"); + check(a() == 0x41 && as::skipped() == 2 && g_passed_on == 4, "and so is every later one"); + + // A breakpoint whose reported address holds no 0xCC: the two-byte `int 3` (CD 03), for which Windows and Wine + // report the byte after the CD. It is passed on, whatever the budget. + check(as::install(5), "install(5) starts over"); + RemoveVectoredExceptionHandler(fallback_again); + void* const fallback_last = AddVectoredExceptionHandler(0, &fallback); + page[48] = 0xCD; // int 3, two bytes; then the site's mov eax, 0x44; ret + page[49] = 0x03; + const Site d = reinterpret_cast(page + 48); + write_site(page + 49, 0x44); + page[49] = 0x03; // write_site's 0xCC is the second byte of the int 3 + FlushInstructionCache(GetCurrentProcess(), page, 4096); + const LONG before = g_passed_on; + check(d() == 0x44 && as::skipped() == 0 && g_passed_on == before + 1, + "a breakpoint with no 0xCC at its address is passed on"); + check(b() == 0x42 && as::skipped() == 1 && g_passed_on == before + 1, "a guest int3 after a restart is stepped over"); + + as::install(0); + RemoveVectoredExceptionHandler(fallback_last); + VirtualFree(page, 0, MEM_RELEASE); + std::printf("%s\n", g_failed ? "FAILED" : "all checks passed"); + return g_failed ? 1 : 0; +} diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp index c0088eea40..a79946ab3c 100644 --- a/runtime/test/fixtures/tiny_game.cpp +++ b/runtime/test/fixtures/tiny_game.cpp @@ -1,6 +1,6 @@ // A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the // loader instead of the Windows one. Test code, not game content. Run as -// gta6rt --run tiny_game.exe -- hello 42 [tls] [eh] [stack] [game-file] [exit-code] [abort-mode] +// gta6rt --run tiny_game.exe -- hello 42 [tls] [eh] [stack] [game-file] [int3] [exit-code] [abort-mode] // It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the // xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then // calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's @@ -10,6 +10,8 @@ // A fourth, `stack` (run_tiny_game_stack), checks that the entry thread and a thread created with dwStackSize 0 // both have 8 MB of stack: a driver compiles shaders on the game's threads (BUILD-1457). Only under gta6rt: run // natively, the second thread gets this program's own 1 MB. +// `int3` (run_tiny_game_skip_asserts) runs two soft asserts, an int3 at each of two sites followed by code that +// carries on, as a title's assert does; it passes only under LEONIDA_SKIP_ASSERTS=2 or more, which steps over them. // An `abort-*` mode installs a SIGABRT disposition and calls abort(); tiny_game_abort_test compares the exact exit // codes with a native run of the same image. No game files. // On MSVC, `eh` needs more than the unwind tables #176 registers: _CxxThrowException finds the throwing image @@ -62,6 +64,16 @@ void abort_crt_exit_handler(int) { } void abort_return_handler(int) {} +// Two int3 sites: noinline, so the optimizer cannot fold them into one. +__declspec(noinline) void soft_assert_a(volatile int& reached) { + __debugbreak(); + reached = reached + 1; +} +__declspec(noinline) void soft_assert_b(volatile int& reached) { + __debugbreak(); + reached = reached + 1; +} + // The reserved stack of the calling thread, in bytes, written to *out (a size_t). DWORD WINAPI stack_reserve(void* out) { ULONG_PTR low = 0, high = 0; @@ -165,6 +177,15 @@ int main(int argc, char** argv) { std::printf("tiny_game: SKIP GAME: file (argument game-file)\n"); } + if (has_arg(argc, argv, "int3")) { + volatile int reached = 0; + soft_assert_a(reached); + soft_assert_b(reached); + check(reached == 2, "the code after each of two int3 ran (LEONIDA_SKIP_ASSERTS stepped over them)"); + } else { + std::printf("tiny_game: SKIP int3 (argument int3)\n"); + } + if (has_arg(argc, argv, "abort-handler")) { std::signal(SIGABRT, abort_exit_handler); std::abort(); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 6af7ad8046..e0e3e78998 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -7,6 +7,7 @@ // - OpenSharedHandle of a fence (as ID3D12Fence, IUnknown, Fence1), of a non-fence object, of an invalid handle, // and with a null output or IID, with the references of every object it touches; // - allocation failures in the proxy (operator new, the arrays it unwraps), injected in this executable only; +// - the first call of a device slot the generic thunk takes by number names its caller (set_caller_describer); // - --fail-virtualalloc / --fail-virtualprotect / --fail-veh: the guard region's setup failing, injected by // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. @@ -16,6 +17,7 @@ #include #include +#include // _dup/_dup2 for the stderr capture #include #include @@ -24,6 +26,7 @@ #include #include #include +#include #include namespace { @@ -967,6 +970,118 @@ int check_tail(bool want_guarded) { return 0; } +// ---- 10. The caller of a slot taken by number, logged with its first call ---- + +const void* g_described[8]; // the addresses the describer was given, in order +unsigned g_describe_calls = 0; + +// What gta6rt's rt::shims::module_offset answers for a host module, with this executable's own name. +std::string describe_caller(std::uint64_t address) { + if (g_describe_calls < std::size(g_described)) g_described[g_describe_calls] = reinterpret_cast(address); + ++g_describe_calls; + HMODULE module = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(address), &module)) + return {}; + char text[64]; + std::snprintf(text, sizeof text, "xs_proxy_mock_test.exe+0x%llx", + static_cast(address - reinterpret_cast(module))); + return text; +} + +bool in_this_executable(const void* address) { + HMODULE module = nullptr; + return address && + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module) && + module == GetModuleHandleW(nullptr); +} + +int count_of(const std::string& hay, const char* needle) { + int n = 0; + for (std::size_t at = hay.find(needle); at != std::string::npos; at = hay.find(needle, at + 1)) ++n; + return n; +} + +// stderr into a file for the length of the check, as d3d12_bundle_test captures its trace. +struct StderrCapture { + std::string path; + int saved = -1; + StderrCapture() { + char temp[MAX_PATH] = {}; + GetTempPathA(MAX_PATH, temp); + path = std::string(temp) + "xs_proxy_mock_callers_" + std::to_string(GetCurrentProcessId()) + ".txt"; + std::fflush(stderr); + std::FILE* out = nullptr; + if (fopen_s(&out, path.c_str(), "wb") != 0) out = nullptr; + saved = _dup(2); + if (out && saved >= 0) _dup2(_fileno(out), 2); + if (out) std::fclose(out); + } + std::string finish() { + std::fflush(stderr); + if (saved >= 0) { + _dup2(saved, 2); + _close(saved); + saved = -1; + } + std::string text; + std::FILE* in = nullptr; + if (fopen_s(&in, path.c_str(), "rb") == 0 && in) { + char buffer[4096]; + for (std::size_t n; (n = std::fread(buffer, 1, sizeof buffer, in)) > 0;) text.append(buffer, n); + std::fclose(in); + } + DeleteFileA(path.c_str()); + return text; + } + ~StderrCapture() { finish(); } +}; + +int check_slot_callers() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device && xs::device_proxy_slot_count(device) < 120); + xs::reset_device_proxy_stats(); + xs::set_caller_describer(&describe_caller); + std::string log; + { + StderrCapture capture; + // A PC slot passed through (25 GetResourceAllocationInfo): the first call names its caller, the second does not. + raw(device, 25, 0x11, 0x22); + raw(device, 25, 0x33, 0x44); + // A routed Xbox slot (78 SetFrameIntervalX) and a slot past the PC table (120, refused) are taken by number too. + const HRESULT routed = hr_of(raw(device, 78, 0, 16667, 1, 0)); + const HRESULT refused = hr_of(raw(device, 120)); + // A slot with a handler of its own (36 CreateFence) logs its first call without a caller. + void* fence = make_fence(device); + // With no describer the caller is the bare address. + xs::set_caller_describer(nullptr); + raw(device, 70); + log = capture.finish(); + EXPECT(routed == S_OK && refused == E_NOTIMPL && fence && release(fence) == 0); + } + EXPECT(mock->calls[25] == 2 && mock->args[25][0] == 0x33 && mock->calls[78] == 0 && mock->calls[70] == 1); + EXPECT(g_describe_calls == 3); // 25, 78 and 120; once each + EXPECT(g_described[0] == xs::device_slot_first_caller(25) && in_this_executable(g_described[0])); + EXPECT(g_described[1] == xs::device_slot_first_caller(78) && in_this_executable(g_described[1])); + EXPECT(g_described[2] == xs::device_slot_first_caller(120) && in_this_executable(g_described[2])); + EXPECT(in_this_executable(xs::device_slot_first_caller(70))); + EXPECT(xs::device_slot_first_caller(36) == nullptr && xs::device_slot_first_call_seen(36)); + EXPECT(count_of(log, "device slot 25 (GetResourceAllocationInfo) first call from xs_proxy_mock_test.exe+0x") == 1); + EXPECT(count_of(log, "device slot 25 ") == 1); + EXPECT(count_of(log, "device slot 78 (Xbox SetFrameIntervalX) first call from xs_proxy_mock_test.exe+0x") == 1); + EXPECT(count_of(log, "device slot 120 (forwarded) first call from xs_proxy_mock_test.exe+0x") == 1); + EXPECT(count_of(log, "device slot 36 (CreateFence -> fence proxy) first call\n") == 1); + EXPECT(count_of(log, "device slot 70 (forwarded) first call from 0x") == 1); + // The reset clears the caller with the first-call flag. + xs::reset_device_proxy_stats(); + EXPECT(xs::device_slot_first_caller(25) == nullptr && !xs::device_slot_first_call_seen(25)); + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: the first call of a slot taken by number names its caller; handled slots do not\n", g_label); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -1249,7 +1364,8 @@ int main(int argc, char** argv) { } if (argc != 1) return 2; if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list()) + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_slot_callers() || + check_console_command_list()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; diff --git a/tools/boot_trace.py b/tools/boot_trace.py index afca038be9..351c554e65 100644 --- a/tools/boot_trace.py +++ b/tools/boot_trace.py @@ -313,7 +313,8 @@ def format_text(summary: dict, limit: int) -> str: if startup["file_open_failed_count"] > limit: out.append(f" ... {startup['file_open_failed_count'] - limit} more") if startup["int3_skipped"]: - out.append(f" int3 skipped (LEONIDA_SKIP_INT3, one per address): {_tail(startup['int3_skipped'], limit)}") + out.append(" int3 skipped (LEONIDA_SKIP_INT3: one per address; LEONIDA_SKIP_ASSERTS: each one): " + f"{_tail(startup['int3_skipped'], limit)}") if startup["exception_count"]: out.append(f" exceptions: {startup['exception_count']}") for exc in startup["exceptions"][:limit]: