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
3 changes: 2 additions & 1 deletion docs/boot.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
92 changes: 71 additions & 21 deletions runtime/shims/startup_trace.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@
#pragma once

#include <windows.h>
#include <set>

#include <atomic>
#include <cerrno>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <initializer_list>
#include <mutex>
#include <string>

Expand All @@ -39,13 +39,25 @@
namespace rt::startup_trace {

namespace detail {
inline std::atomic<bool> 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<bool> 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;
Expand Down Expand Up @@ -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<const unsigned char*>(info->ExceptionRecord->ExceptionAddress);
if (!at || *at != 0xCC || info->ContextRecord->Rip != reinterpret_cast<DWORD64>(at)) return false;
static std::mutex m;
static std::set<const void*> 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<bool> 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<const void*> int3_sites[kInt3Sites]{};

inline bool first_int3_at(const void* at) {
const auto key = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(at));
size_t i = static_cast<size_t>((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<uint64_t>(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<const unsigned char*>(c.Rip);
const auto* address = static_cast<const unsigned char*>(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<uint64_t>(at))));
info->ContextRecord->Rip = reinterpret_cast<DWORD64>(at) + 1;
return true;
}

Expand Down Expand Up @@ -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;
}
Expand Down
28 changes: 15 additions & 13 deletions runtime/shims/xgameruntime_offline.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,23 @@ constexpr char kEventName[] = "XGameEventImpl";
constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}};
std::atomic<long> 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<int>& 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<int> 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,
Expand Down Expand Up @@ -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<int> 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
Expand Down
Loading
Loading