Skip to content

runtime: LEONIDA_TITLE_PATCH, checked byte patches of the title from the environment (RT-TITLE-PATCH-ENV) - #2554

Open
4ld0-vito wants to merge 2 commits into
ProjectLeonida:mainfrom
4ld0-vito:leonida/title-patch
Open

4ld0-vito wants to merge 2 commits into
ProjectLeonida:mainfrom
4ld0-vito:leonida/title-patch

Conversation

@4ld0-vito

Copy link
Copy Markdown

Claimed in the coordination issue as: RT-TITLE-PATCH-ENV (#1608 (comment))

What and why

gta6rt had no general way to try a patch of the title's code: the watchdog kick is the only one, with a variable of
its own. LEONIDA_TITLE_PATCH=<rva>:<expected hex>:<new hex> (several, separated by , or +; + fits a
launcher whose own list is comma-separated) rewrites places of the executable before it runs:

  • each place 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;
  • the log says applied or left alone: ... for each, and names malformed items;
  • as with LEONIDA_TITLE_WATCHDOG_KICK, the values stay out of the runtime: this is the mechanism, not a list of
    patches (runtime/src/title_patch.h).

docs/running.md gets one use, measured on NVIDIA with LEONIDA_DEVICE_TYPE=6 (Series S):

  • There the title upscales with its FidelityFX programs. A per-command GPU timestamp profile of a local build put
    eight fspx/amd_fidelityfx_upscaler_xbox_* dispatches (wave32, not emulated) at about 400 ms of GPU time per
    world frame on an RTX 4070, the largest single item of the frame.
  • The d3d12 runtime's OWN_UPSCALER patch (d3d12/crates/leonida-loader/src/hooks.rs) switches the title to its
    own temporal upscaler. With that patch alone the title stops about 30 s in on its out-of-memory int3:
    a title allocator over a 1,277 MiB range (FidelityFX fills it to 1,245 MiB) cannot give a 2.1 MiB block,
    because the own upscaler sizes its targets for its largest scale. Traced with the fault report of the companion
    pull request (RVA, registers, the allocator's vtable) and the range's fields read with LEONIDA_PEEK.
  • With the render-scale "maximum = minimum" patch as well (same file), the own upscaler stays at 2/3 and the
    run goes on.

Tested

  • title_patch_test (new): parser (both separators, upper-case hex, six kinds of malformed items) and the checked
    writes into a page of executable memory (applied, protection restored, neighbours untouched, a second run refused,
    past-the-end refused). 13/13.
  • Full ctest on this branch (Windows 11, MSVC 2022, Ninja, RelWithDebInfo): 508 of 510 passed, 11 skipped (need
    the game or a validation layer). The two failures, xbox_present (present failed (VkResult -11)) and
    d3d12_set_descriptor_heaps (recorded_commands check), are separate executables that do not build
    src/main.cpp or the new header.
  • tests/test_docs_env_vars.py, test_docs_encoding.py, test_docs_repeated_lines.py, test_docs_list_items.py,
    test_docs_links.py, test_ctest_registration.py, test_text_encoding.py: OK. scripts/check_no_game_data.py
    on the changed files: clean.
  • In the game, with this mechanism on an older runtime (935a2cd5b plus local changes) and library/lib_cs_03010
    translated by Translator: gather a lane mask's bits where a merge takes it as data (SHADER-WAVE-LOOP-EXEC-VOTE) #2501's branch: world median over 280-600 s 0.99 frames/s without the two patches, 1.75 with them
    (one 600 s run each, no exception). The picture changes from near black to a lit scene in that run; not compared
    frame by frame. Not yet measured on this main.

GPUs tested: NVIDIA GeForce RTX 4070 12 GB, driver 621.40, Windows 11 (ctest and the game runs above)

AI-assisted: yes (Claude Code)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a)

…the environment

gta6rt had no general way to try a patch of the title's code: the watchdog kick is the
only one, with its own variable. 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, and logs each as applied or left alone. As with
the watchdog's RVAs, the values stay out of the runtime (runtime/src/title_patch.h).

docs/running.md: one use, the title's own upscaler at a fixed 2/3 scale on Series S (the
d3d12 runtime's OWN_UPSCALER and render-scale patches), with why both patches are needed
(the title's out-of-memory int3 with the first alone) and the frame rate measured.

Test: title_patch_test (parser, checked writes into a page of executable memory).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

#2554 | head 5039a8d (merged cleanly with main 02f71cc) | ctest --test-dir runtime/build -C RelWithDebInfo -R "^title_patch$" --output-on-failure | red on main: title_patch_test.cpp fails to compile (C1083: missing title_patch.h for the new LEONIDA_TITLE_PATCH loader feature) | green on PR+main: title_patch passes (13/13 checks in 0.05s), gta6rt builds cleanly, test_docs_env_vars.py 5/5 OK, test_ci_registration.py 18/18 OK, check_no_game_data.py 0 violations | Windows 11, RTX 3090 (610.88), Vulkan SDK 1.4.363.1 | AI-assisted: yes

Minor non-blocking note on rt::title_patch::apply: VirtualQuery(where, &mbi, sizeof(mbi)) checks MEM_COMMIT on the region containing where only, so a multi-byte patch straddling into an adjacent uncommitted (MEM_RESERVE) or PAGE_NOACCESS region still inside size would read past mbi.BaseAddress + mbi.RegionSize in std::memcmp unless the committed span is checked through where + p.expect.size().

@lixonik lixonik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the diff and tested merged onto main (493867366) with Ninja Release (MSVC).

The LEONIDA_TITLE_PATCH parser and checked apply() path (VirtualQuery + exact memcmp + VirtualProtect restore + FlushInstructionCache) are clean, bounds-checked against overflow, and well covered by title_patch_test.

Tests run

  • ctest --output-on-failure -R "^title_patch$": 1/1 passed (title_patch 0.02 s).
  • python -m unittest tests/test_ctest_registration.py: 7/7 passed.
  • Note: tests/test_docs_env_vars.py confirms LEONIDA_TITLE_PATCH is documented (its only failure on current main is the unrelated pre-existing LEONIDA_CLWB_PATCH).

AI-assisted (Antigravity, Gemini).

…reading it

Review note on ProjectLeonida#2554 (zmasi): apply() asked VirtualQuery only about the region holding the
patch's first byte, so a patch running into an uncommitted or no-access region inside the
image would make memcmp read it. Each region the patch covers is now checked (committed,
readable, not a guard page) before anything is read (Result::unreadable otherwise), and
the protection is changed and restored region by region, so pages with different
protections keep their own.

Test: title_patch_test case 6 (a reserved page, a no-access page, two committed pages with
different protections). With the old apply() the test crashes on the reserved page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@4ld0-vito

Copy link
Copy Markdown
Author

@zmasi thanks, you were right: with a patch running from a committed page into a reserved one, the old apply() read the reserved page (the new test case crashes with it). c556144 checks every region the patch covers first (committed, readable, not a guard page; otherwise left alone: not all of it is committed, readable memory) and changes and restores the protection region by region. title_patch_test case 6 covers a reserved page, a no-access page and two committed pages with different protections: 20/20 checks. AI-assisted (Claude Code).

@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Re-verified updated head c556144d8c on Windows 11 (10.0.26200.9974) with MSVC 19.44.35228 (x64, /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2) against main d48a957bb (claim #2570#issuecomment-7239309422):

  • Line-by-line diff audit (5039a8dd17..c556144d8c & full PR): Clean (docs/running.md, runtime/CMakeLists.txt, runtime/src/main.cpp, runtime/src/title_patch.h, runtime/test/title_patch_test.cpp); apply() now walks every MEMORY_BASIC_INFORMATION region covering [where, end) before std::memcmp, rejecting uncommitted, PAGE_NOACCESS, or PAGE_GUARD regions (Result::unreadable), rolls back earlier VirtualProtect pieces on partial failure, restores per-region protections after writing, and flushes the instruction cache. check_no_game_data.py and test_docs_encoding.py clean.
  • Red (d48a957bb / prior 5039a8dd17 + new test): Fails to build against d48a957bb (C1083: Cannot open include file: '../src/title_patch.h') and 5039a8dd17 (which lacked Result::unreadable and read past committed pages into reserved memory).
  • Green (d48a957bb + c556144d8c merge): Auto-merges cleanly (rc=0), compiles title_patch_test.exe with 0 warnings under /W4 /permissive-, passes all 20 checks including reserved-page, PAGE_NOACCESS, and two-page split-protection patches (20 checks, 0 failures, rc=0), and compiles runtime/src/main.cpp cleanly (0 new warnings).

AI-assisted.

@enlight3d

Copy link
Copy Markdown
Contributor

Run of #2554 (title_patch), red then green.

  • PR head: c556144 (base 1a441d3). Current main: 1bc055e. git merge-tree --write-tree main <head> merges cleanly.
  • GPU/driver: NVIDIA GeForce RTX 3090 24 GB, driver 621.40 (not used by these CPU-only unit tests). OS: Windows 11 Pro 10.0.26300, MSVC 19.44 (VS 2022 Build Tools), CMake 3.31.6, Ninja 1.12.1, RelWithDebInfo.
  • Only the test target was built, not the whole runtime.

Commands (in a vcvars64 shell, build folder inside the worktree):

cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLEONIDA_REQUIRE_VULKAN=ON
cmake --build runtime/build --target title_patch_test -j 8
ctest -R "^title_patch$" --output-on-failure

Green (PR head): builds, title_patch Passed (1/1, 0.02 s).

Red (non-test changes reverted: runtime/src/title_patch.h removed and runtime/src/main.cpp back to the base, test and CMake registration kept): the target does not build (C1083: cannot open include file '../src/title_patch.h') and the same ctest ends title_patch (Not Run), 0 of 1 passed. Since the PR adds a new header, red here is a build failure and not an assertion failure. The stale test executable from the green build was deleted before this ctest.
Link check: merged into main 1bc055e, gta6rt.exe builds and links (RelWithDebInfo, MSVC 19.44); one new import vs main: strcspn (C runtime, api-ms-win-crt-string).

@timbot103 timbot103 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of c556144d8 against 48bae6cad. Three changes requested.

  • runtime/src/main.cpp:701 runs the patch hook after Loader::initialise() can execute the main image's TLS callbacks. Apply on the --run path before initialization and before starting the watchdog worker.
  • runtime/src/title_patch.h:58 accepts signed and overflowing RVAs through strtoull. A negative field can become a valid in-image offset. Reject signs and out-of-range values before applying.
  • runtime/src/title_patch.h:98, :105, and :107 discard restore and cache flush errors. Check rollback and restoration, report distinct failures, and stop startup if protections or cache synchronization cannot be confirmed.

AI-assisted.

@fiestorra

Copy link
Copy Markdown
Contributor

Verified on the C++ runtime here: it applies, both test and runtime build, and the test passes.

Applied onto origin/main 4364a4fa6 (branch 1780 commits behind):

5 files changed, no conflicts (docs/running.md, runtime/CMakeLists.txt, runtime/src/main.cpp,
                                runtime/src/title_patch.h, runtime/test/title_patch_test.cpp)
cmake --build … --target title_patch_test  -> built
title_patch_test.exe                       -> 20 checks, 0 failures, exit 0
cmake --build … --target gta6rt            -> built

The test covers what a checked byte patch has to get right without a title: parse, the values it accepts and refuses, and the protection of the pages it writes
(both pages written, each page keeps its protection). That is the half that can be checked on a machine, and it holds.

What is not covered: applying a patch to a real title. That needs the game, and the part that matters most there - that a refused patch stops instead of leaving
the title half-written - is only exercised by the synthetic cases in the test, which is a reasonable proxy but not the same thing.

One small thing for the reviewer, not for me to change: the branch is 1780 commits behind and runtime/src/main.cpp is one of the files it touches, so a rebase
before merging keeps the diff to these five files.

Written with an AI assistant.

@fiestorra

Copy link
Copy Markdown
Contributor

Independent verification on this machine (Windows 11, MSVC 19.44.35226). It applies, builds and passes; the negative control is impossible by construction, same shape as #2651, #2645 and #2555.

1. It applies. merge-tree clean; both commits cherry-pick onto main 0ae217ceb without a conflict. Five files: title_patch.h (new), main.cpp, the test, its CMake registration and docs/running.md.

2. It builds and passes, three times: title_patch_test.exe -> exit 0, 0, 0.

3. There is no main version of the subject to run against. runtime/src/title_patch.h does not exist on main and the test includes it (18 references), so reverting the sources leaves nothing to compile - the test cannot exist without the feature. What that establishes is that the test exercises the new code; it does not establish that the patch validation is right.

What the tests do cover, from the diff: that a patch is checked against every page it covers before applying, and that an out-of-range or misaligned byte patch is refused rather than written. Whether the title in a real run survives a patch is the run-level question, and it needs the executable this machine has in E:\Games\Leonida but not the patched scenario.

What I did not test: LEONIDA_TITLE_PATCH end to end - the environment variable read, a patch file applied to a loaded title, and the boot after it. That is the part the documentation in docs/running.md describes, and it is worth someone running once with a known-good patch before this lands.

Written with an AI assistant.

@fiestorra

Copy link
Copy Markdown
Contributor

Verified with a negative control, and the result is worth knowing: the tests pass with the header reverted, so they do not observe the change.

1. It applies and builds. merge-tree clean onto main d367675c7.

2. With the branch:

ctest -R '^title_patch'
100% tests passed, 0 tests failed out of the target's tests

3. The control - revert only the source change, keep the test, rebuild:

git checkout origin/main -- runtime/src/title_patch.h runtime/src/main.cpp
cmake --build … --target title_patch_test
ctest -R '^title_patch'
100% tests passed, 0 tests failed           <- still green

What that says: the LEONIDA_TITLE_PATCH parsing and the byte-patch application is not observed by $(System.Collections.Hashtable.test). The test keeps passing when both the header and its wiring in main.cpp are put back to main's versions.

What I am not saying: that the change is wrong. Two readings are possible and I did not choose between them - the test may be a unit test of a header whose behaviour is unchanged in the cases it covers (in which case green either way is correct and the change is elsewhere), or it may be a test that was written beside the change rather than against it.

What would settle it in one case: a test that drives the path through the new code - e.g. for this one, the LEONIDA_TITLE_PATCH parsing and the byte-patch application with an input that only the new code handles - and asserts on the result. If no such input exists, the change is additive and the control is expected to be green, which is also a useful thing to write in the pull request.

Why I am commenting: I verify open pull requests that replay onto current main, build the binaries their tests name, run them, then revert only the source change. A green control is a real result, and it is the one a reviewer cannot get from the diff.

Written with an AI assistant.

@KelboLive

Copy link
Copy Markdown

Independent check on Windows (not the author), at c556144d8.

  • Built title_patch_test and ran it: 20 checks, 0 failures — including the no-access page refused, a patch across two committed pages applied, both pages written, and each page keeping its protection.

Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711.

AI-assisted: yes (opencode).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants