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
12 changes: 12 additions & 0 deletions docs/running.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ Paths are placeholders: `<checkout>` is the repository, `<build>` the folder wit
measures in their own copy (`runtime/src/main.cpp` describes the trap instruction the first must point at). The
values are never committed. With `=0` alone the loader logs that the watchdog stays armed. (Measured by us; the
watchdog was identified in [#2019](https://github.com/ubiquitarianism/leonida/issues/2019#issuecomment-7172996360).)
- **Byte patches of the title (`LEONIDA_TITLE_PATCH`).** `LEONIDA_TITLE_PATCH=<rva>:<expected hex>:<new hex>`, several
separated by `,` or `+`, rewrites places of the executable before it runs, each only when the expected bytes are
there; the log says `applied` or `left alone` for each (`runtime/src/title_patch.h`). Like the watchdog's RVAs, the
values are not kept in the runtime. One use, measured on NVIDIA with `LEONIDA_DEVICE_TYPE=6` (Series S): there the
title upscales with its FidelityFX programs, which took about 400 ms of GPU time a world frame on an RTX 4070
(eight `fspx/amd_fidelityfx_upscaler_xbox_*` dispatches, wave32, not emulated). The d3d12 runtime's two patches
`OWN_UPSCALER` and the render-scale "maximum = minimum" in `d3d12/crates/leonida-loader/src/hooks.rs` switch the
title to its own temporal upscaler at a fixed 2/3 scale. Both are needed: with the first alone the own upscaler
sizes its targets for its largest scale and the title stops about 30 s in on its out-of-memory `int3`, when a
1,277 MiB pool that FidelityFX fills to 1,245 MiB is full (measured by us). With both, on an RTX 4070 12 GB
(driver 621.40, Windows 11), the world median over 280-600 s went from 0.99 to 1.75 frames/s, one run each, on a
runtime from `935a2cd5b` with `library/lib_cs_03010` translated by #2501's branch (not yet measured on later `main`).
- **The GPU timeout.** World frames take seconds each. The OS's GPU timeout must be longer, or the driver resets the
GPU: amdgpu's `lockup_timeout` on Linux, `TdrDelay` on Windows (sections below).
- **Large ray-tracing programs.** 724 library compute programs have 2 MiB of SPIR-V or more (676 of them ray-tracing
Expand Down
8 changes: 8 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
target_compile_definitions(title_write_watch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
target_compile_options(title_write_watch_test PRIVATE /W4 /permissive- /utf-8)

# LEONIDA_TITLE_PATCH (src/title_patch.h): the parser and the checked writes into a stand-in image.
add_executable(title_patch_test test/title_patch_test.cpp)
target_compile_definitions(title_patch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
target_compile_options(title_patch_test PRIVATE /W4 /permissive- /utf-8)

# title_memory_map (src/title_page_watch.h): map changes by range, and the texture pass that probes only what they hit.
add_executable(title_memory_map_test test/title_memory_map_test.cpp)
target_compile_definitions(title_memory_map_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
Expand Down Expand Up @@ -1741,6 +1746,9 @@ if(BUILD_TESTING)
if(WIN32 AND TARGET title_memory_map_test)
add_test(NAME title_memory_map COMMAND title_memory_map_test)
endif()
if(WIN32 AND TARGET title_patch_test)
add_test(NAME title_patch COMMAND title_patch_test)
endif()
if(WIN32 AND TARGET title_write_watch_test)
add_test(NAME title_write_watch COMMAND title_write_watch_test)
add_test(NAME title_write_watch_on COMMAND title_write_watch_test)
Expand Down
31 changes: 31 additions & 0 deletions runtime/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@

#include <cstring>

#include "title_patch.h"

namespace {

// The retail title runs a hang watchdog thread: when the game's main loop has not set its "kick" byte for 30
Expand Down Expand Up @@ -106,6 +108,34 @@ void keep_title_watchdog_kicked(std::uint8_t* base) {
}
}

// LEONIDA_TITLE_PATCH (title_patch.h): checked byte patches of the title's image from the environment, applied before
// it runs. Each one is reported as applied or left alone.
void apply_title_patches(std::uint8_t* base, std::size_t image_size) {
static char spec[2048];
const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_PATCH", spec, sizeof(spec));
if (!n) return;
if (n >= sizeof(spec)) {
std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_PATCH is longer than %zu characters; nothing patched\n",
sizeof(spec) - 1);
return;
}
std::vector<std::string> bad;
for (const auto& p : rt::title_patch::parse(spec, &bad)) {
const auto r = rt::title_patch::apply(base, image_size, p);
const char* what = r == rt::title_patch::Result::applied ? "applied"
: r == rt::title_patch::Result::mismatch ? "left alone: the expected bytes are not there"
: r == rt::title_patch::Result::outside ? "left alone: outside the image"
: r == rt::title_patch::Result::unreadable
? "left alone: not all of it is committed, readable memory"
: "left alone: VirtualProtect failed";
std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_PATCH at +0x%llx (%zu bytes) %s\n",
static_cast<unsigned long long>(p.rva), p.replace.size(), what);
}
for (const auto& item : bad)
std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_PATCH item '%s' is not <rva>:<expected hex>:<new hex> of equal "
"lengths; skipped\n", item.c_str());
}

// LEONIDA_PEEK="<rva>:3,<rva>,<rva>" (diagnostic): a thread prints the 8-byte values at these RVAs of the
// title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at
// pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this
Expand Down Expand Up @@ -668,6 +698,7 @@ int wmain(int argc, wchar_t** argv) {
std::printf("running %s\n", main_module.name.c_str());
std::fflush(stdout);
keep_title_watchdog_kicked(main_module.base);
apply_title_patches(main_module.base, main_module.size);
start_title_peek(main_module.base);
leonida::dev_overlay::start(); // LEONIDA_DEV_OVERLAY=1
leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
Expand Down
111 changes: 111 additions & 0 deletions runtime/src/title_patch.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#pragma once
// LEONIDA_TITLE_PATCH: checked byte patches of the title's image, named in the environment.
//
// LEONIDA_TITLE_PATCH="<rva>:<expected hex>:<new hex>[,<rva>:<expected hex>:<new hex>...]" ('+' works as well as
// ',' between patches, for launchers whose own lists are comma-separated)
//
// Before the title runs, each place is rewritten only when the bytes there are exactly the expected ones, the two
// strings have the same length (1-64 bytes) and the place lies inside the image. A place that does not match is left
// alone. Like LEONIDA_TITLE_WATCHDOG_KICK, the RVAs and bytes are measured locally and are not kept in the runtime:
// this is the mechanism, not a list of patches. An example is the title's choice of upscaler, see docs/running.md.
#include <windows.h>

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>

namespace rt::title_patch {

struct Patch {
std::uint64_t rva = 0;
std::vector<std::uint8_t> expect, replace;
};

enum class Result { applied, mismatch, outside, unreadable, protect_failed };

inline bool parse_hex(const char* text, std::size_t len, std::vector<std::uint8_t>& out) {
out.clear();
if (len == 0 || len % 2 || len > 128) return false;
auto nibble = [](char c) -> int {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
for (std::size_t i = 0; i < len; i += 2) {
const int hi = nibble(text[i]), lo = nibble(text[i + 1]);
if (hi < 0 || lo < 0) return false;
out.push_back(static_cast<std::uint8_t>(hi << 4 | lo));
}
return true;
}

// The patches of a specification, in order; each item that is not <rva>:<hex>:<hex> of equal lengths goes to `bad`.
inline std::vector<Patch> parse(const char* spec, std::vector<std::string>* bad = nullptr) {
std::vector<Patch> out;
for (const char* at = spec ? spec : ""; *at;) {
const char* end = at + std::strcspn(at, ",+");
const std::string item(at, end);
at = *end ? end + 1 : end;
if (item.empty()) continue;
const std::size_t c1 = item.find(':');
const std::size_t c2 = c1 == std::string::npos ? c1 : item.find(':', c1 + 1);
Patch p;
char* rva_end = nullptr;
p.rva = std::strtoull(item.c_str(), &rva_end, 16);
if (c2 == std::string::npos || rva_end != item.c_str() + c1 || c1 == 0 ||
!parse_hex(item.c_str() + c1 + 1, c2 - c1 - 1, p.expect) ||
!parse_hex(item.c_str() + c2 + 1, item.size() - c2 - 1, p.replace) || p.expect.size() != p.replace.size()) {
if (bad) bad->push_back(item);
continue;
}
out.push_back(std::move(p));
}
return out;
}

// Writes one patch into the image at `base` (`size` bytes) when the expected bytes are there. Every page the patch
// covers is checked first (committed, readable, not a guard page), region by region, so a patch that runs into an
// uncommitted or no-access region is refused before anything is read; each region keeps its own protection.
inline Result apply(std::uint8_t* base, std::size_t size, const Patch& p) {
if (p.expect.empty() || p.rva > size || p.expect.size() > size - p.rva) return Result::outside;
std::uint8_t* const where = base + p.rva;
std::uint8_t* const end = where + p.expect.size();
struct Piece {
std::uint8_t* at;
std::size_t len;
DWORD old;
};
Piece pieces[8]{}; // a patch is at most 64 bytes: it spans at most two pages, so few regions
std::size_t count = 0;
for (std::uint8_t* at = where; at < end;) {
MEMORY_BASIC_INFORMATION mbi{};
if (count == std::size(pieces) || !VirtualQuery(at, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT ||
!mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)))
return Result::unreadable;
std::uint8_t* const region_end = static_cast<std::uint8_t*>(mbi.BaseAddress) + mbi.RegionSize;
std::uint8_t* const stop = region_end < end ? region_end : end;
pieces[count++] = {at, static_cast<std::size_t>(stop - at), 0};
at = stop;
}
if (std::memcmp(where, p.expect.data(), p.expect.size()) != 0) return Result::mismatch;
for (std::size_t i = 0; i < count; ++i) {
if (!VirtualProtect(pieces[i].at, pieces[i].len, PAGE_EXECUTE_READWRITE, &pieces[i].old)) {
DWORD ignored = 0;
while (i-- > 0) VirtualProtect(pieces[i].at, pieces[i].len, pieces[i].old, &ignored);
return Result::protect_failed;
}
}
std::memcpy(where, p.replace.data(), p.replace.size());
for (std::size_t i = 0; i < count; ++i) {
DWORD ignored = 0;
VirtualProtect(pieces[i].at, pieces[i].len, pieces[i].old, &ignored);
}
FlushInstructionCache(GetCurrentProcess(), where, p.replace.size());
return Result::applied;
}

} // namespace rt::title_patch
129 changes: 129 additions & 0 deletions runtime/test/title_patch_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// rt::title_patch (runtime/src/title_patch.h): LEONIDA_TITLE_PATCH's parser and its checked writes, on a page of real
// executable memory standing in for the title's image. No game data, no GPU.
// 1. a specification with ',' and '+' between patches gives every patch, in order, with its bytes;
// 2. malformed items (no colons, odd hex, unequal lengths, empty fields, not hex) are reported and skipped;
// 3. a patch whose expected bytes are there is written, and the page keeps its protection;
// 4. a patch whose expected bytes are not there leaves the bytes alone;
// 5. a patch that reaches past the image, or starts past it, is refused without touching memory;
// 6. a patch that runs from a committed page into a reserved one, or into a no-access page, is refused
// before anything is read; one across two committed pages with different protections is applied and
// each page keeps its own protection.
#include <windows.h>

#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>

#include "../src/title_patch.h"

namespace {

int g_checks = 0;
int g_failures = 0;

void check(bool condition, const char* what) {
++g_checks;
std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
if (!condition) ++g_failures;
}

} // namespace

int main() {
using rt::title_patch::Result;
{
std::vector<std::string> bad;
const auto p = rt::title_patch::parse("10:0f45c1:0f1f00+2a:AABB:ccdd,3:01:02", &bad);
check(p.size() == 3 && bad.empty(), "1. three patches, none rejected");
check(p.size() == 3 && p[0].rva == 0x10 && p[0].expect == std::vector<std::uint8_t>{0x0f, 0x45, 0xc1} &&
p[0].replace == std::vector<std::uint8_t>{0x0f, 0x1f, 0x00},
"1. first patch: rva and bytes");
check(p.size() == 3 && p[1].rva == 0x2a && p[1].expect == std::vector<std::uint8_t>{0xaa, 0xbb} &&
p[2].rva == 3,
"1. upper-case hex and both separators");
}
{
std::vector<std::string> bad;
const auto p = rt::title_patch::parse("10,10:0f4:0f1,10:0f45:0f,:00:01,10::,10:zz:00,20:01:02", &bad);
check(p.size() == 1 && p[0].rva == 0x20, "2. only the well-formed item is kept");
check(bad.size() == 6, "2. six items reported");
}
SYSTEM_INFO si{};
GetSystemInfo(&si);
const std::size_t size = si.dwPageSize;
auto* image = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!image) {
std::printf("FAIL VirtualAlloc\n");
return 1;
}
for (std::size_t i = 0; i < size; ++i) image[i] = static_cast<std::uint8_t>(i * 7);
image[0x40] = 0x0f;
image[0x41] = 0x45;
image[0x42] = 0xc1;
DWORD old = 0;
VirtualProtect(image, size, PAGE_EXECUTE_READ, &old);
{
const auto p = rt::title_patch::parse("40:0f45c1:0f1f00");
check(p.size() == 1 && rt::title_patch::apply(image, size, p[0]) == Result::applied, "3. applied");
check(image[0x40] == 0x0f && image[0x41] == 0x1f && image[0x42] == 0x00, "3. new bytes in place");
check(image[0x3f] == static_cast<std::uint8_t>(0x3f * 7) && image[0x43] == static_cast<std::uint8_t>(0x43 * 7),
"3. neighbours untouched");
MEMORY_BASIC_INFORMATION mbi{};
VirtualQuery(image + 0x40, &mbi, sizeof(mbi));
check(mbi.Protect == PAGE_EXECUTE_READ, "3. protection restored");
}
{
const auto p = rt::title_patch::parse("40:0f45c1:909090");
check(p.size() == 1 && rt::title_patch::apply(image, size, p[0]) == Result::mismatch,
"4. a second run finds the patched bytes and refuses");
check(image[0x40] == 0x0f && image[0x41] == 0x1f && image[0x42] == 0x00, "4. bytes unchanged");
}
{
char spec[64];
std::snprintf(spec, sizeof(spec), "%zx:%02x%02x:0000", size - 1, image[size - 1], 0);
const auto p = rt::title_patch::parse(spec);
check(p.size() == 1 && rt::title_patch::apply(image, size, p[0]) == Result::outside, "5. reaches past the end");
std::snprintf(spec, sizeof(spec), "%zx:00:01", size + 0x100);
const auto q = rt::title_patch::parse(spec);
check(q.size() == 1 && rt::title_patch::apply(image, size, q[0]) == Result::outside, "5. starts past the end");
}
VirtualFree(image, 0, MEM_RELEASE);
{
// Two pages reserved, only the first committed: a patch over the boundary reads no reserved byte.
auto* two = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 2 * size, MEM_RESERVE, PAGE_NOACCESS));
check(two && VirtualAlloc(two, size, MEM_COMMIT, PAGE_READWRITE), "6. reserve two pages, commit one");
if (two) {
two[size - 2] = 0x11;
two[size - 1] = 0x22;
char spec[64];
std::snprintf(spec, sizeof(spec), "%zx:11220000:99999999", size - 2);
const auto p = rt::title_patch::parse(spec);
check(p.size() == 1 && rt::title_patch::apply(two, 2 * size, p[0]) == Result::unreadable,
"6. into a reserved page: refused");
check(two[size - 2] == 0x11 && two[size - 1] == 0x22, "6. committed bytes unchanged");
// Both committed, the second no-access: refused as well.
VirtualAlloc(two + size, size, MEM_COMMIT, PAGE_NOACCESS);
check(rt::title_patch::apply(two, 2 * size, p[0]) == Result::unreadable, "6. into a no-access page: refused");
// Second page readable with another protection: applied, each page keeps its own.
DWORD old2 = 0;
VirtualProtect(two + size, size, PAGE_READONLY, &old2);
DWORD old1 = 0;
VirtualProtect(two, size, PAGE_EXECUTE_READ, &old1);
std::snprintf(spec, sizeof(spec), "%zx:11220000:aabbccdd", size - 2);
const auto q = rt::title_patch::parse(spec);
check(q.size() == 1 && rt::title_patch::apply(two, 2 * size, q[0]) == Result::applied,
"6. across two committed pages: applied");
check(two[size - 2] == 0xaa && two[size - 1] == 0xbb && two[size] == 0xcc && two[size + 1] == 0xdd,
"6. both pages written");
MEMORY_BASIC_INFORMATION a{}, b{};
VirtualQuery(two, &a, sizeof(a));
VirtualQuery(two + size, &b, sizeof(b));
check(a.Protect == PAGE_EXECUTE_READ && b.Protect == PAGE_READONLY, "6. each page keeps its protection");
VirtualFree(two, 0, MEM_RELEASE);
}
}
std::printf("%d checks, %d failures\n", g_checks, g_failures);
return g_failures ? 1 : 0;
}