Skip to content
Closed
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
5 changes: 5 additions & 0 deletions docs/retail_boot_chain.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ Without a debugger, the unhandled `int3` of a fatal assert ends the process with
`C0000005` during teardown, not `80000003`. An exit code of `C0000374` from `--run` can be such an assert, not a
heap bug.

Hypothesis: a console devkit continues past a failed assert, and some of the title's asserts are tuning checks, not
faults. `LEONIDA_SKIP_ASSERTS=N` (off by default; [runtime/README.md](../runtime/README.md)) steps `gta6rt` over the
first N guest `int3` asserts, logging each, so a run can get past such a stop and show what comes next. A debugging
aid for the title's own asserts; it does not touch any protection or anti-debug check.

## 2. Physical pages (`xmem.dll`)

The shapes, from the call sites and the checks that follow them:
Expand Down
16 changes: 16 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)

add_executable(gta6rt
src/main.cpp
src/guest_asserts.cpp
src/pe_loader.cpp
shims/registry.cpp
shims/file_system.cpp
Expand Down Expand Up @@ -820,6 +821,21 @@ if(BUILD_TESTING)
target_link_options(startup_trace_test PRIVATE /OPT:NOREF)
add_dependencies(startup_trace_test gta6rt_tls_host)
add_test(NAME startup_trace COMMAND startup_trace_test)

# LEONIDA_SKIP_ASSERTS=N (src/guest_asserts.h): the decision function on synthetic inputs, and a real
# __debugbreak round trip on VirtualAlloc'd executable memory (guest code: outside every module).
add_executable(guest_asserts_test
test/guest_asserts_test.cpp
src/guest_asserts.cpp
src/pe_loader.cpp
shims/registry.cpp
)
target_include_directories(guest_asserts_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_compile_definitions(guest_asserts_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS)
target_compile_options(guest_asserts_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
target_link_options(guest_asserts_test PRIVATE /OPT:NOREF)
add_dependencies(guest_asserts_test gta6rt_tls_host)
add_test(NAME guest_asserts COMMAND guest_asserts_test)
endif()

if(TARGET device_proxy_test)
Expand Down
16 changes: 16 additions & 0 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,22 @@ 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.

### Stepping over guest asserts: `LEONIDA_SKIP_ASSERTS`

Off by default. `LEONIDA_SKIP_ASSERTS=N` with N > 0 installs a vectored exception handler (last in the chain) that
steps over the first N `int3` breakpoints raised by guest code: "guest code" here means outside every loaded module
(the mapped images, guest allocations and the runtime's generated thunks), at a byte that is `0xCC`. Each one is
logged as `[rt] assert skipped: int3 in guest code at <module+RVA, or the address> (LEONIDA_SKIP_ASSERTS)` and
execution resumes at the next byte. A breakpoint in a loaded host module, a fault that is not an `int3`, and any
`int3` after the N-th continue the exception search as before. Being a vectored handler it runs before a guest
`__try` that would catch the `int3` itself.

Hypothesis: a console devkit continues past a failed assert, and some of the retail title's asserts are tuning checks
rather than faults (see [retail_boot_chain.md](../docs/retail_boot_chain.md)), so this is a way to see what comes
after, not a fix. A debugging aid for the title's own asserts; it does not touch any protection or anti-debug check.
`LEONIDA_SKIP_INT3` (with `--trace`) is the unbounded diagnostic variant. Test: `guest_asserts_test` (a real `int3`
on `VirtualAlloc`'d executable memory).

## PE loader

`src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when
Expand Down
47 changes: 47 additions & 0 deletions runtime/src/guest_asserts.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include "guest_asserts.h"

#include <cstdio>

#include "../shims/startup_trace.h"

namespace rt::guest_asserts {

namespace {
std::atomic<long> g_remaining{0};

// The byte at `p` can be read: committed, not guarded or inaccessible, and a readable protection.
bool readable(const void* p) {
MEMORY_BASIC_INFORMATION mbi{};
if (!p || VirtualQuery(p, &mbi, sizeof mbi) != sizeof mbi) return false;
if (mbi.State != MEM_COMMIT || (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS))) return false;
return (mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0;
}
}

LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
if (!info || !info->ExceptionRecord || info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT)
return EXCEPTION_CONTINUE_SEARCH;
const auto* at = static_cast<const unsigned char*>(info->ExceptionRecord->ExceptionAddress);
HMODULE host = nullptr;
const bool in_host = GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(at), &host) != 0;
if (in_host) return EXCEPTION_CONTINUE_SEARCH; // a host module's own breakpoint
if (!info->ContextRecord || info->ContextRecord->Rip != reinterpret_cast<DWORD64>(at) || !readable(at))
return EXCEPTION_CONTINUE_SEARCH;
if (!should_skip(g_remaining, in_host, *at)) return EXCEPTION_CONTINUE_SEARCH;
std::fprintf(stderr, "[rt] assert skipped: int3 in guest code at %s (LEONIDA_SKIP_ASSERTS)\n",
rt::startup_trace::where(reinterpret_cast<uint64_t>(at)).c_str());
info->ContextRecord->Rip = reinterpret_cast<DWORD64>(at) + 1;
return EXCEPTION_CONTINUE_EXECUTION;
}

bool install(long count) {
if (count <= 0) return false;
g_remaining = count;
// Last in the chain, after a debugger and the other handlers.
return AddVectoredExceptionHandler(0, &handler) != nullptr;
}

} // namespace rt::guest_asserts
40 changes: 40 additions & 0 deletions runtime/src/guest_asserts.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// LEONIDA_SKIP_ASSERTS=N: step over the first N `int3` asserts raised by guest code (opt-in, off by default).
//
// Hypothesis: a console devkit lets a title continue past a failed assert, and some of the retail title's asserts
// are tuning checks rather than faults (docs/retail_boot_chain.md). With the variable set to a positive number the
// runtime installs a vectored exception handler that, for a breakpoint at an address outside every loaded module
// (the mapped images, guest allocations and the runtime's generated thunks), whose byte is 0xCC, logs the site and
// resumes one byte later. Anything else continues the exception search untouched. A debugging aid for the title's
// own asserts; it does not touch any protection or anti-debug check.
#pragma once

#include <windows.h>

#include <atomic>
#include <cstdint>
#include <cstdlib>

namespace rt::guest_asserts {

// True when a breakpoint whose byte is `byte` is to be stepped over. `remaining` is decremented once per skipped
// int3 and never below 0 once spent, so N allows exactly N skips.
inline bool should_skip(std::atomic<long>& remaining, bool in_host_module, unsigned char byte) {
if (in_host_module || byte != 0xCC) return false;
if (remaining.load(std::memory_order_relaxed) <= 0) return false;
return remaining.fetch_sub(1) - 1 >= 0;
}

// Parses the variable's value: a positive count, else 0 (off).
inline long parse_count(const char* text) {
if (!text) return 0;
const long n = std::strtol(text, nullptr, 10);
return n > 0 ? n : 0;
}

// Installs the handler with the given budget; a count of 0 installs nothing. Returns whether it was installed.
bool install(long count);

// The handler itself, exposed for the test. Uses the budget set by install().
LONG CALLBACK handler(EXCEPTION_POINTERS* info);

} // namespace rt::guest_asserts
6 changes: 6 additions & 0 deletions runtime/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

#include "base_reservation.h"
#include "code_hooks.h"
#include "guest_asserts.h"
#include "mods.h"
#include "pe_loader.h"
#include "../shims/d3d12_trace.h"
Expand Down Expand Up @@ -147,6 +148,11 @@ int wmain(int argc, wchar_t** argv) {
"this executable (docs/modding.md)\n", leonida::mods::active().size());
}
rt::d3d12_trace::set_enabled(trace_d3d12);
{
char skip_asserts[16] = {};
const DWORD n = GetEnvironmentVariableA("LEONIDA_SKIP_ASSERTS", skip_asserts, sizeof skip_asserts);
rt::guest_asserts::install(n > 0 && n < sizeof skip_asserts ? rt::guest_asserts::parse_count(skip_asserts) : 0);
}
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");
Expand Down
87 changes: 87 additions & 0 deletions runtime/test/guest_asserts_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Tests for LEONIDA_SKIP_ASSERTS (src/guest_asserts.h). Synthetic only: the decision function on made-up inputs,
// then a real int3 round trip on executable memory from VirtualAlloc, which lies outside every module and so counts
// as guest code. No game data, no GPU.
#include <windows.h>

#include <atomic>
#include <cstdio>
#include <cstring>
#include <string>

#include "guest_asserts.h"

namespace {

int g_checks = 0;
int g_failed = 0;

void check(bool ok, const std::string& what) {
++g_checks;
std::printf("%s %s\n", ok ? "ok " : "FAIL ", what.c_str());
if (!ok) ++g_failed;
}

using rt::guest_asserts::should_skip;

void decision_tests() {
std::atomic<long> n{2};
check(should_skip(n, false, 0xCC) && n == 1, "guest int3 is skipped and the counter decremented");
check(!should_skip(n, true, 0xCC) && n == 1, "an address in a host module is not skipped and costs nothing");
check(!should_skip(n, false, 0x90) && n == 1, "a byte other than 0xCC is not skipped and costs nothing");
check(should_skip(n, false, 0xCC) && n == 0, "the last allowed skip uses the counter up");
check(!should_skip(n, false, 0xCC), "an exhausted counter does not skip");
check(!should_skip(n, false, 0xCC), "and stays exhausted");

check(rt::guest_asserts::parse_count(nullptr) == 0, "default (variable unset) is off");
check(rt::guest_asserts::parse_count("") == 0, "an empty value is off");
check(rt::guest_asserts::parse_count("0") == 0, "0 is off");
check(rt::guest_asserts::parse_count("-3") == 0, "a negative value is off");
check(rt::guest_asserts::parse_count("x") == 0, "a non-number is off");
check(rt::guest_asserts::parse_count("2") == 2, "2 allows two skips");
check(!rt::guest_asserts::install(0), "a count of 0 installs no handler");
}

typedef int (*Fn)();

// Runs `code` as a function in executable memory under __try, so a not-skipped int3 reports instead of crashing.
// Returns 1 when it returned normally, 0 when the breakpoint reached the __except filter.
int call_guarded(Fn fn, int* result) {
__try {
*result = fn();
return 1;
} __except (GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
return 0;
}
}

void round_trip_tests() {
// mov eax, 42 ; int3 ; int3 ; int3 ; ret
const unsigned char code[] = {0xB8, 42, 0, 0, 0, 0xCC, 0xCC, 0xCC, 0xC3};
void* mem = VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
check(mem != nullptr, "executable memory allocated");
if (!mem) return;
std::memcpy(mem, code, sizeof code);
HMODULE host = nullptr;
check(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
static_cast<LPCWSTR>(mem), &host),
"the allocation belongs to no module (guest code)");

int r = 0;
check(call_guarded(reinterpret_cast<Fn>(mem), &r) == 0, "without the handler the int3 is not stepped over");

check(rt::guest_asserts::install(3), "install(3) adds the handler");
r = 0;
check(call_guarded(reinterpret_cast<Fn>(mem), &r) == 1 && r == 42, "three guest int3 are stepped over, code resumes");
r = 0;
check(call_guarded(reinterpret_cast<Fn>(mem), &r) == 0, "the budget is spent: the next int3 is not skipped");
VirtualFree(mem, 0, MEM_RELEASE);
}

} // namespace

int main() {
decision_tests();
round_trip_tests();
std::printf("%d checks, %d failed\n", g_checks, g_failed);
return g_failed ? 1 : 0;
}
Loading