Skip to content
Open
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
4 changes: 4 additions & 0 deletions docs/boot.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ 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 <module>+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").
* `LEONIDA_STUB_PIPELINES=1` creates a pipeline whose translated shader is missing (no shader library, or no entry
for its program) as a no-op stub instead of failing `CreateGraphicsPipelineState` / `CreateComputePipelineState`.
The stub is never registered, so `SetPipelineState` binds no PSO and its draws and dispatches are no-ops (D3D-482).
Expand Down
19 changes: 19 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,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
Expand Down Expand Up @@ -1548,6 +1558,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()
Expand Down Expand Up @@ -1734,6 +1747,12 @@ if(BUILD_TESTING)
"-DTOOL=$<TARGET_FILE:gta6rt>" "-DWANT=${GTA6RT_STACK}"
-P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake")
add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- 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 $<TARGET_FILE:tiny_game> -- 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")
# A /GA executable under --run and --init reads its TLS from slot 0, and the trace names gta6rt.exe as the image
# whose index 0 moved.
add_test(NAME run_tiny_tls_ga COMMAND ${CMAKE_COMMAND}
Expand Down
23 changes: 21 additions & 2 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -598,15 +617,15 @@ 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` |

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.
Expand Down
151 changes: 151 additions & 0 deletions runtime/src/assert_skip.h
Original file line number Diff line number Diff line change
@@ -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 <windows.h>

#include <atomic>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cwchar>
#include <string>

#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<unsigned>(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<unsigned> limit{0};
inline std::atomic<unsigned> claimed{0}; // skips handed out, may pass `limit` by the declined ones
inline std::atomic<bool> 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<LPCWSTR>(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<const unsigned char*>(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<DWORD64>(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
12 changes: 12 additions & 0 deletions runtime/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ void start_title_peek(std::uint8_t* base) {

} // namespace

#include "assert_skip.h"
#include "base_reservation.h"
#include "code_hooks.h"
#include "cpu_emulation.h"
Expand Down Expand Up @@ -407,6 +408,17 @@ int wmain(int argc, wchar_t** argv) {
if (!rt::cpu_emulation::install())
std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler failed (error %lu); instructions this CPU lacks "
"will stop the game\n", GetLastError());
// 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);
Expand Down
Loading