diff --git a/docs/boot.md b/docs/boot.md index 4bc580c750..8d47a80b5d 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -98,7 +98,8 @@ Useful switches: `ROSETTA_ADVERTISE_AVX=1` instead). The game itself still needs AVX, so this is for the #UD emulation work (see [cpu_features.md](cpu_features.md#hosts-without-avx) for what works on a host without AVX). * `LEONIDA_SKIP_INT3=1` (with `--trace`) steps over each int3 in guest code and logs it once per address as an - `int3_skipped` event, so a boot can be followed past soft asserts (an int3 followed by code that carries on). + `int3_skipped` event, so a boot can be followed past soft asserts (an int3 followed by code that carries on). It is + read when the trace opens. 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_STUB_PIPELINES=1` creates a pipeline whose translated shader is missing (no shader library, or no entry diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 390529c415..b8fe304be3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -439,7 +439,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_link_options(file_system_test PRIVATE /OPT:NOREF) target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check - # LEONIDA_SKIP_INT3 (shims/startup_trace.h): its own executable, the variable is read once per process. + # LEONIDA_SKIP_INT3 (shims/startup_trace.h): each case runs in a child process with its own environment. add_executable(int3_skip_test test/int3_skip_test.cpp shims/registry.cpp diff --git a/runtime/README.md b/runtime/README.md index b89a82a711..be621b7d75 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -604,7 +604,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 when the trace opens: first int3 at each address, which is then stepped over (after 4096 distinct addresses, a new one is logged each time it is hit) | `at` (module+RVA) | | `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` | diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 6be16118be..c2f3ee9f56 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -23,7 +23,6 @@ #pragma once #include -#include #include #include @@ -31,6 +30,7 @@ #include #include #include +#include #include #include @@ -39,13 +39,25 @@ namespace rt::startup_trace { namespace detail { -inline std::atomic on{false}; -// Intentionally immortal: vectored exception handlers or late teardown paths can still run after normal statics would -// have been destroyed. -inline std::mutex& mutex() { - static auto* m = new std::mutex; - return *m; -} +// What the exception handler touches lives at namespace scope and is constant-initialized: it exists before any code +// runs, on every thread, and is never destroyed. A block-scope static is initialized on its first use, and that can be +// on a title thread, where under Wine the MSVC thread-safe-static guard has been seen to pass while the object was +// still zero (old upstream 7599): LEONIDA_SKIP_INT3 stayed off and the int3 set and the trace lock were never +// constructed. +inline constinit std::atomic on{false}; + +// The trace lock. An SRW lock needs no constructor or destructor, so vectored exception handlers and late teardown +// paths can take it at any time, also after normal statics have been destroyed. +class Lock { +public: + void lock() noexcept { AcquireSRWLockExclusive(&srw_); } + void unlock() noexcept { ReleaseSRWLockExclusive(&srw_); } + +private: + SRWLOCK srw_ = SRWLOCK_INIT; +}; +inline constinit Lock trace_lock{}; +inline Lock& mutex() noexcept { return trace_lock; } inline FILE* file = nullptr; inline unsigned long long seq = 0; inline std::chrono::steady_clock::time_point start; @@ -269,20 +281,57 @@ inline void log_exception(const EXCEPTION_POINTERS& info) { // LEONIDA_SKIP_INT3 (diagnostic, with --trace): an int3 in guest code is logged once per address and stepped over, // so a boot can be followed past the title's soft asserts (an int3 followed by code that carries on). Off by default: // a console title never reaches one in a correct run, so each skipped address is a finding, not a fix. -inline bool skip_int3(EXCEPTION_POINTERS* info) { - static const bool skip = GetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr, 0) != 0; - if (!skip || info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT || !info->ContextRecord) return false; - const auto* at = static_cast(info->ExceptionRecord->ExceptionAddress); - if (!at || *at != 0xCC || info->ContextRecord->Rip != reinterpret_cast(at)) return false; - static std::mutex m; - static std::set seen; - bool first = false; - { - const std::lock_guard lock(m); - first = seen.insert(at).second; +// +// open() reads the variable, on the thread that opens the trace and before any guest code runs. +inline constinit std::atomic skip_int3_on{false}; +inline bool skip_int3_requested() { return GetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr, 0) != 0; } + +// The addresses already logged: an open-addressing table of atomics, so the handler needs no constructor, lock or +// allocation for it. When it is full, a site is logged again rather than lost. +constexpr size_t kInt3Sites = 4096; // a power of two: 12 bits of the hash below +inline constinit std::atomic int3_sites[kInt3Sites]{}; + +inline bool first_int3_at(const void* at) { + const auto key = static_cast(reinterpret_cast(at)); + size_t i = static_cast((key * 0x9E3779B97F4A7C15ull) >> 52); + for (size_t probe = 0; probe < kInt3Sites; ++probe, i = (i + 1) & (kInt3Sites - 1)) { + const void* seen = int3_sites[i].load(std::memory_order_acquire); + if (!seen && int3_sites[i].compare_exchange_strong(seen, at, std::memory_order_acq_rel)) return true; + if (seen == at) return false; // also when another thread has just claimed this slot for the same site } - if (first) event("int3_skipped", "\"at\":" + quote(where(reinterpret_cast(at)))); - info->ContextRecord->Rip += 1; + return true; +} + +inline bool readable_byte(const unsigned char* p) { + MEMORY_BASIC_INFORMATION m{}; + if (!p || VirtualQuery(p, &m, sizeof m) != sizeof m || m.State != MEM_COMMIT) return false; + return (m.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; +} + +// The int3 (0xCC) a breakpoint stopped at, or null. Windows reports Rip and ExceptionAddress on the 0xCC byte, and so +// did Wine 11.22 (Staging) in a probe here; Spacecer2's Wine 11.22 boot reported both one byte past it (old upstream +// 7599). The candidate taken is the one ExceptionAddress agrees with (on it, or one byte before it), the byte at Rip +// first, so the Windows form is handled as before. With Rip one past the 0xCC and ExceptionAddress on it, a run of +// 0xCC bytes still gives the int3 ExceptionAddress names, not the one at Rip. When both name the byte after the int3 +// (the second form) and that byte is another 0xCC, the next int3 is taken, and stepped over with this one. +inline const unsigned char* int3_from(const EXCEPTION_RECORD& r, const CONTEXT& c) { + const auto* rip = reinterpret_cast(c.Rip); + const auto* address = static_cast(r.ExceptionAddress); + if (!rip) return nullptr; + for (const unsigned char* at : {rip, rip - 1}) + if ((address == at || address == at + 1) && readable_byte(at) && *at == 0xCC) return at; + return nullptr; +} + +// With LEONIDA_SKIP_INT3, steps over an int3: Rip ends one byte past the 0xCC in either form. +inline bool skip_int3(EXCEPTION_POINTERS* info) { + if (!skip_int3_on.load(std::memory_order_relaxed)) return false; + if (!info || !info->ExceptionRecord || !info->ContextRecord) return false; + if (info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT) return false; + const unsigned char* at = int3_from(*info->ExceptionRecord, *info->ContextRecord); + if (!at) return false; + if (first_int3_at(at)) event("int3_skipped", "\"at\":" + quote(where(reinterpret_cast(at)))); + info->ContextRecord->Rip = reinterpret_cast(at) + 1; return true; } @@ -325,6 +374,7 @@ inline bool open(const wchar_t* path, int* error = nullptr) { } detail::start = std::chrono::steady_clock::now(); detail::seq = 0; + detail::skip_int3_on.store(detail::skip_int3_requested(), std::memory_order_relaxed); static const int atexit_registered = std::atexit(&close); (void)atexit_registered; } diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index 3a5be55209..1a59d42128 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -107,15 +107,23 @@ constexpr char kEventName[] = "XGameEventImpl"; constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}}; std::atomic g_events{0}; -bool log_every_event() { - static const bool on = [] { +// "=1" exactly. Read on the first call, which is on a title thread: the answer is kept in a namespace-scope atomic, not +// a block-scope static, whose guard has been seen to skip the initializer on such a thread under Wine (old upstream +// 7599). +bool env_is_one(const char* name, std::atomic& cached) { + int on = cached.load(std::memory_order_relaxed); + if (on < 0) { char value[4] = {}; size_t length = 0; - return getenv_s(&length, value, "LEONIDA_LOG_GAME_EVENTS") == 0 && length == 2 && value[0] == '1'; - }(); - return on; + on = getenv_s(&length, value, name) == 0 && length == 2 && value[0] == '1'; + cached.store(on, std::memory_order_relaxed); + } + return on != 0; } +std::atomic g_log_every_event{-1}; +bool log_every_event() { return env_is_one("LEONIDA_LOG_GAME_EVENTS", g_log_every_event); } + // 3: HRESULT XGameEventWrite(XUserHandle user, const char* serviceConfigId, const char* playSessionId, // const char* eventName, const char* dimensionsJson, const char* measurementsJson) HRESULT STDMETHODCALLTYPE event_write(void*, XUserHandle, const char*, const char*, const char* name, @@ -399,14 +407,8 @@ struct XDisplayHdrModeInfo { float maxFullFrameToneMapLuminance; }; -bool hdr_requested() { - static const bool on = [] { - char value[4] = {}; - size_t length = 0; - return getenv_s(&length, value, "LEONIDA_HDR") == 0 && length == 2 && value[0] == '1'; - }(); - return on; -} +std::atomic g_hdr_requested{-1}; +bool hdr_requested() { return env_is_one("LEONIDA_HDR", g_hdr_requested); } // 4: XDisplayHdrModeResult XDisplayTryEnableHdrMode(XDisplayHdrModePreference preference, XDisplayHdrModeInfo* info) // The host swapchain is SDR, so HDR stays off unless LEONIDA_HDR=1; then it is "enabled" with the documented diff --git a/runtime/test/int3_skip_test.cpp b/runtime/test/int3_skip_test.cpp index 3c06302ebd..9fa05386eb 100644 --- a/runtime/test/int3_skip_test.cpp +++ b/runtime/test/int3_skip_test.cpp @@ -1,9 +1,21 @@ // LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per -// address and stepped over, so execution continues. A separate executable because the variable is read once. +// address and stepped over, so execution continues. +// +// Each case runs in a child process of its own (`int3_skip_test --case NAME`), so a case that crashes fails alone and +// each one opens the trace with its own environment: +// real a real int3 at two sites, one of them hit twice: execution continues, one event per address +// windows a synthetic breakpoint with Rip on the 0xCC (Windows): Rip ends one past it, one event +// wine Rip one byte past the 0xCC (Wine, old upstream 7599): the same result +// null null EXCEPTION_POINTERS, ExceptionRecord or ContextRecord: no skip and no crash +// init the variable is read when the trace opens: removed after open(), int3s are still skipped +// off without the variable, nothing is skipped #include #include +#include +#include #include +#include #include #include @@ -35,31 +47,195 @@ __declspec(noinline) void site_b(int& reached) { ++reached; } -} // namespace +// A trace file of this process; the text is read back after close(). +struct Trace { + std::wstring path; + Trace() { + wchar_t temp[MAX_PATH]; + GetTempPathW(MAX_PATH, temp); + path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl"; + DeleteFileW(path.c_str()); + check(rt::startup_trace::open(path.c_str()), "open the startup trace file"); + } + std::string close_and_read() { + rt::startup_trace::close(); + std::string log; + { + std::ifstream in{std::filesystem::path(path)}; + std::stringstream text; + text << in.rdbuf(); + log = text.str(); + } + DeleteFileW(path.c_str()); + return log; + } +}; + +// A synthetic EXCEPTION_BREAKPOINT for skip_int3, as the vectored handler receives it. +struct Breakpoint { + EXCEPTION_RECORD record{}; + std::unique_ptr context = std::make_unique(); // heap: a 16-byte-aligned member pads the struct + EXCEPTION_POINTERS pointers{}; + Breakpoint(const unsigned char* address, const unsigned char* rip) { + record.ExceptionCode = EXCEPTION_BREAKPOINT; + record.ExceptionAddress = const_cast(address); + record.NumberParameters = 1; + context->ContextFlags = CONTEXT_CONTROL; + context->Rip = reinterpret_cast(rip); + pointers.ExceptionRecord = &record; + pointers.ContextRecord = context.get(); + } + bool skip() { return rt::startup_trace::detail::skip_int3(&pointers); } + bool rip_is(const unsigned char* p) const { return context->Rip == reinterpret_cast(p); } +}; + +// nop, int3, nop: the int3 at code + 1, with a byte on each side that is not one. +alignas(16) unsigned char g_code[4] = {0x90, 0xCC, 0x90, 0x90}; -int main() { - SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); // before the first exception: the flag is read once - wchar_t temp[MAX_PATH]; - GetTempPathW(MAX_PATH, temp); - const std::wstring path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl"; - DeleteFileW(path.c_str()); - check(rt::startup_trace::open(path.c_str()), "open the startup trace file"); +std::string event_at(const unsigned char* at) { + const std::string where = rt::startup_trace::where(reinterpret_cast(at)); + return "\"kind\":\"int3_skipped\",\"at\":" + rt::startup_trace::quote(where); +} +void case_real() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); + Trace trace; int reached = 0; for (int i = 0; i < 2; ++i) site_a(reached); // the same site twice: one event site_b(reached); // another site check(reached == 3, "execution continues past every int3"); - rt::startup_trace::close(); - - std::ifstream in(path); - std::stringstream text; - text << in.rdbuf(); - const std::string log = text.str(); - in.close(); - DeleteFileW(path.c_str()); + const std::string log = trace.close_and_read(); check(count(log, "\"kind\":\"int3_skipped\"") == 2, "exactly two int3_skipped events (one per address)"); check(count(log, "\"kind\":\"exception\"") == 0, "a skipped int3 is not also logged as an exception"); check(log.find("\"at\":\"host:") != std::string::npos, "the event names the address"); +} + +void case_windows() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); + Trace trace; + const unsigned char* at = g_code + 1; + Breakpoint first(at, at); + check(first.skip(), "Rip on the 0xCC: skipped"); + check(first.rip_is(at + 1), "Rip on the 0xCC: Rip ends one byte past it"); + Breakpoint again(at, at); + check(again.skip() && again.rip_is(at + 1), "the same site again: skipped the same way"); + Breakpoint no_int3(g_code + 3, g_code + 3); + check(!no_int3.skip() && no_int3.rip_is(g_code + 3), "no 0xCC at or before Rip: not skipped, Rip unchanged"); + Breakpoint elsewhere(g_code, at); + check(!elsewhere.skip() && elsewhere.rip_is(at), "ExceptionAddress not at the int3 or past it: not skipped"); + const std::string log = trace.close_and_read(); + check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event for the site"); + check(log.find(event_at(at)) != std::string::npos, "the event names the 0xCC byte"); +} + +void case_wine() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); + Trace trace; + const unsigned char* at = g_code + 1; + Breakpoint past(at + 1, at + 1); // ExceptionAddress and Rip one byte past the 0xCC + check(past.skip(), "Rip one byte past the 0xCC: skipped"); + check(past.rip_is(at + 1), "Rip one byte past the 0xCC: Rip ends one byte past it"); + Breakpoint mixed(at, at + 1); // ExceptionAddress on the 0xCC, Rip past it + check(mixed.skip() && mixed.rip_is(at + 1), "ExceptionAddress on the 0xCC, Rip past it: skipped"); + const std::string log = trace.close_and_read(); + check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event for the site"); + check(log.find(event_at(at)) != std::string::npos, "the event names the 0xCC byte, not the byte after it"); +} + +// nop, int3, int3, nop: a run of int3 padding. +alignas(16) unsigned char g_padding[4] = {0x90, 0xCC, 0xCC, 0x90}; + +void case_padding() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); + Trace trace; + const unsigned char* at = g_padding + 1; + Breakpoint mixed(at, at + 1); // ExceptionAddress on the first 0xCC, Rip on the second + check(mixed.skip() && mixed.rip_is(at + 1), + "ExceptionAddress on an int3 followed by another, Rip past it: the int3 ExceptionAddress names is skipped"); + const std::string log = trace.close_and_read(); + check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event"); + check(log.find(event_at(at)) != std::string::npos, "the event names the int3 ExceptionAddress names"); +} + +void case_null() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); + Trace trace; + check(!rt::startup_trace::detail::skip_int3(nullptr), "null EXCEPTION_POINTERS: not skipped"); + Breakpoint no_record(g_code + 1, g_code + 1); + no_record.pointers.ExceptionRecord = nullptr; + check(!no_record.skip() && no_record.rip_is(g_code + 1), "null ExceptionRecord: not skipped"); + Breakpoint no_context(g_code + 1, g_code + 1); + no_context.pointers.ContextRecord = nullptr; + check(!no_context.skip(), "null ContextRecord: not skipped"); + const std::string log = trace.close_and_read(); + check(count(log, "\"kind\":\"int3_skipped\"") == 0, "no int3_skipped event"); +} + +void case_init() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); + Trace trace; + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr); // read when the trace opened, not at the first int3 + check(rt::startup_trace::detail::skip_int3_on.load(), "the flag holds the value read when the trace opened"); + Breakpoint bp(g_code + 1, g_code + 1); + check(bp.skip() && bp.rip_is(g_code + 2), "an int3 after the variable is removed is still skipped"); + trace.close_and_read(); +} + +void case_off() { + SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr); + Trace trace; + check(!rt::startup_trace::detail::skip_int3_on.load(), "without the variable the flag is off"); + Breakpoint bp(g_code + 1, g_code + 1); + check(!bp.skip() && bp.rip_is(g_code + 1), "without the variable an int3 is not skipped"); + trace.close_and_read(); +} + +struct Case { + const char* name; + void (*run)(); +}; +constexpr Case kCases[] = {{"real", case_real}, {"windows", case_windows}, {"wine", case_wine}, + {"padding", case_padding}, {"null", case_null}, {"init", case_init}, + {"off", case_off}}; + +// Runs `this-exe --case NAME` and returns its exit code. +DWORD run_child(const char* name) { + wchar_t exe[MAX_PATH]; + GetModuleFileNameW(nullptr, exe, MAX_PATH); + std::wstring command = L"\"" + std::wstring(exe) + L"\" --case "; + for (const char* c = name; *c; ++c) command += static_cast(*c); + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(exe, command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFF; + WaitForSingleObject(pi.hProcess, INFINITE); + DWORD code = 0xFFFFFFFF; + GetExitCodeProcess(pi.hProcess, &code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return code; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc == 3 && std::strcmp(argv[1], "--case") == 0) { + for (const Case& c : kCases) + if (std::strcmp(argv[2], c.name) == 0) { + c.run(); + std::fflush(stdout); + return g_failed ? 1 : 0; + } + std::printf("unknown case %s\n", argv[2]); + return 2; + } + for (const Case& c : kCases) { + std::printf("-- %s\n", c.name); + std::fflush(stdout); + const DWORD code = run_child(c.name); + if (code != 0) std::printf("FAIL case %s exited with 0x%08lx\n", c.name, static_cast(code)); + if (code != 0) ++g_failed; + } std::printf("%s\n", g_failed ? "FAILED" : "all checks passed"); return g_failed ? 1 : 0; }