Skip to content

d3d12-loader: console_insn range checks don't overflow at the top of memory (D3D12-LOADER-CONSOLE-INSN-CHECKED-RANGES) - #2858

Merged
OreoFR merged 1 commit into
ProjectLeonida:mainfrom
Kal0s-design:fix/console-insn-checked-ranges
Dec 1, 2026
Merged

OreoFR merged 1 commit into
ProjectLeonida:mainfrom
Kal0s-design:fix/console-insn-checked-ranges

Conversation

@Kal0s-design

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D12-LOADER-CONSOLE-INSN-CHECKED-RANGES (#2570 (comment))

What and why

readable() and writable() in d3d12/crates/leonida-loader/src/console_insn.rs computed va + bytes and BaseAddress + RegionSize unchecked. They run inside the vectored exception handler. A clzero with RAX near the top of the address space made the debug build panic with an overflow there, which takes the process down. In release the end wrapped and could let the range check pass.

The change: both use checked_add and answer false on overflow, so a range that runs past the top is neither readable nor writable, and such a clzero is left to fault as it would.

This ports ahmetbagci's fix from the sibling VIctory tree (TaynanGT/Vice-Tay c2f2b5b, GPL-3.0), credited as co-author. Its write_sites.rs half is already in main through #2664.

Tested

  • New test console_insn::tests::ranges_past_the_top_of_the_address_space_do_not_overflow: readable(usize::MAX - 4, 16) and writable(usize::MAX & !63, 64) are false, and emulate on a clzero with RAX = u64::MAX returns 0. On main (3393ceec9) it panics (attempt to add with overflow at console_insn.rs:313); with the change it passes.
  • cargo test -p leonida-loader --lib: 85 passed, 0 failed (main: 84).
  • cargo clippy -p leonida-loader --lib --tests: no warning in the changed lines.
  • Windows only, unit tests; the title wasn't run.

GPUs tested: n/a (CPU unit tests)

AI-assisted: yes

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: no translator change)

🤖 Generated with Claude Code

…memory

readable() and writable() computed va + bytes (and BaseAddress +
RegionSize) unchecked. They run inside the vectored exception handler,
where a clzero with RAX near the top of the address space made the
debug build panic with an overflow (taking the process down) and let a
wrapped end pass the range check in release. A range that runs past the
top is now neither readable nor writable, and such a clzero is left to
fault as it would.

After ahmetbagci's fix in TaynanGT/Vice-Tay (c2f2b5b); its write_sites
half is already in ProjectLeonida#2664.

Co-Authored-By: ahmetbagci <6625856+ahmetbagci@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fiestorra

Copy link
Copy Markdown
Contributor

Verified on Windows: the crate is green with it, and it adds one test - measured against main's own file.

main 3393ceec9, cherry-picked (one commit), cargo 1.98.1:

cargo test -p leonida-loader
  with this pull request:               ok. 85 passed; 0 failed
  with console_insn.rs from main:       ok. 84 passed; 0 failed

So the overflow check is tied to its test and the other 84 did not move.

One thing worth saying about the shape: a range check that does not overflow is exactly the kind of change that a test can pin down and a reviewer cannot eyeball - the arithmetic either wraps for a given input or it does not, and the input has to be constructed. The test that comes with it is the only evidence there is that the boundary is where the comment says.

What I could not test: a real console instruction stream hitting that boundary - the unit tests are what I ran.

AI-assisted: yes - DeepSeek v4.1 (flash), both arms on the machine above.

Written with an AI assistant.

@Neutron-0

Copy link
Copy Markdown

Verified on Windows 11, and the control bites: the new test panics on today's main and passes with this.

main 7fbcd456e, cargo 1.98.1:

cargo test -p leonida-loader --lib --locked
  on main, with the new test alone:   FAILED
      thread 'console_insn::tests::ranges_past_the_top_of_the_address_space_do_not_overflow' panicked at crates\leonida-loader\src\console_insn.rs:313:21:
      attempt to add with overflow
  with this pull request:             85 passed, 0 failed   (main has 84)

The control was this pull request's own test with the fix reverted, so the panic is the fix's doing and not the test's: readable(usize::MAX - 4, 16) overflows in va + bytes on main, before the query is even made.

Two notes for the record, both in the pull request's favour:

  • The fix computes end with checked_add before the VirtualQuery, so a range past the top of the address space never asks the kernel about an address it cannot describe; and the region end is checked with checked_add as well, which is the other overflow named here.
  • That order matters for this code in particular: it runs inside the vectored exception handler, where a panic takes the process down - the failure mode this pull request is about - so answering "not readable" has to happen without anything that can panic.

No game files and no GPU were needed for this check: the tests are Windows unit tests and the title was not run.

@MoonEyes

MoonEyes commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Verified by MoonEyes (another person than the author) on head 3cd5de60b merged with main cd0c52fcf: I read the whole diff. cargo test -p leonida-loader: 88 passed, 0 failed. With checked_add put back to a plain va + bytes, ranges_past_the_top_of_the_address_space_do_not_overflow fails.

In-game run with the six others of a batch on main 21e6bbf4b: RTX 4060 8 GB, NVIDIA 610.88, Windows 11 26300, -SeriesS -FrameGen 2, about 860 s in the world, then a second one of about 440 s, 0 device lost, 0 panic; pictures of the same scene compared with main, same. Black surfaces in early cutscenes while the PC's memory is full are there on plain main too.

AI-assisted (Claude Code).

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2858 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The fix is the right one, and the pull request's new test is a real red on main: with the overflow checks that cargo test turns on, main's code panics with attempt to add with overflow where the new code answers false.

Head 3cd5de60, base the current main 88a9f133, merge base 3393ceec, 1 commit, 1 file, +32/−2: d3d12/crates/leonida-loader/src/console_insn.rs. It merges onto today's main without a conflict.

1. What it changes

Two range checks in the module that emulates the console-only instructions:

// before
&& m.BaseAddress as usize + m.RegionSize >= va + bytes
// after
&& (m.BaseAddress as usize).checked_add(m.RegionSize).is_some_and(|region_end| region_end >= end)

fn writable(va: usize, bytes: usize) -> bool {
    let Some(end) = va.checked_add(bytes) else { return false };
    writable_to(va, end) == Some(end)
}

va is an address taken from the title's own register (ctx.Rip, ctx.Rax), so it can be any 64-bit value; va + bytes can therefore run off the top of the address space.

2. The pull request's reasoning checks out

"inside the exception handler an overflow panic takes the process down"

readable and writable are called from exactly two places, and both are on the exception-dispatch path:

console_insn.rs:375   if !readable(rip, 1) { ... }        // inside emulate()
console_insn.rs:378   let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0);
console_insn.rs:437   if !writable(line, 64) { ... }

and emulate is:

pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 — "ctx is the faulting thread's context, from the exception being dispatched."

So a panic raised there unwinds out of the vectored exception handler, which is the "takes the process down" the comment describes. rip is ctx.Rip as usize — the title's own instruction pointer.

The clzero path is already safe and the pull request leaves it alone: first.checked_add(passes * 64) at console_insn.rs:467, with passes bounded by MOST = (2 << 30) / 64.

3. How I checked it

leonida-loader does not build on Linux — console_insn is #[cfg(windows)] (lib.rs:24-25) and calls VirtualQuery, VirtualProtect and GetCurrentProcessorNumber. So I copied readable, writable and writable_to out of the file verbatim, for both main and the pull request, into a standalone program (tools/rust/2858_harness.rs) with a mock VirtualQuery, and ran the pull request's two assertions against both.

The mock has two behaviours, because the answer depends on it:

  • A — VirtualQuery fails. What real Windows does for a user-mode address that high: the address is not mapped, the query fails.
  • B — VirtualQuery always answers. A large committed, writable region, to see whether a wrapped end can let the check through.

4. Red and green

Built with the overflow checks on, which is what cargo test's test profile does (overflow-checks follows debug-assertions):

build mock main's code the pull request's code
debug (cargo test) A panic — attempt to add with overflow false — PASS
debug (cargo test) B panic — attempt to add with overflow false — PASS
release (no overflow checks) A false false
release (no overflow checks) B true — the wrapped end lets the check pass false

The two assertions are the pull request's own:

assert!(!readable(usize::MAX - 4, 16));
assert!(!writable(usize::MAX & !63, 64));

On main they do not merely fail, they panic: usize::MAX - 4 + 16 and usize::MAX & !63 + 64 both overflow, and in readable the overflow is only reached when VirtualQuery answers (the && short-circuits before it otherwise), while in writable the va + bytes is an argument and is always evaluated. The new checked_add turns both into a plain false.

5. How much of this is observable in a shipped build

Worth being precise, because the release row above is the one a player would meet:

  • In a debug build (the test profile, and a developer's build of the loader) main's code panics inside the exception handler. That is the real defect, and the fix removes it.
  • In a release build the overflow wraps instead of panicking, and for a user-mode address that high VirtualQuery fails anyway (row A), so main would have answered false too. The "a wrapped end let the range check pass" needs VirtualQuery to answer (row B), which on Windows needs a mapping at such an address — a user-mode address cannot have one, so that row is a hardening rather than an observable difference in a release build.

Either way the change is right: it removes the panic, and it closes the wrap.

6. The credit in the test's comment is checkable

"After ahmetbagci's fix in TaynanGT/Vice-Tay (c2f2b5b)."

TaynanGT/Vice-Tay@c2f2b5b is public: "Use checked addition in console_insn and write_sites bounds checks", 2026-11-29, touching crates/victory-loader/src/console_insn.rs (+28/−2) and crates/victory-loader/src/write_sites.rs (+12/−1) — the same change, in the related project.

I looked for the same class of unchecked addition in leonida's write_sites.rs, the other file that fix touched: its arithmetic is on slice indices (code.get(at + 1)?, bounded by get) and on offsets parsed from our own list file (usize::from_str_radix(offset.trim_start_matches("0x"), 16) at write_sites.rs:238), not from the title's registers — a different threat model, so no counterpart to fix here.

7. A small asymmetry, not a defect

readable now guards m.BaseAddress + m.RegionSize with checked_add, but writable_to still computes the same sum unguarded (console_insn.rs:346). It cannot overflow in practice — BaseAddress is a real user-mode region base and RegionSize is that region's size — so this is symmetry rather than a bug, and I would not ask for a change. writable_to's other caller, the clzero loop, is already guarded.

8. What I did not check

  • The third assertion of the new test, which builds a CONTEXT, points Rax at u64::MAX and calls emulate:

    let mut context: CONTEXT = std::mem::zeroed();
    context.Rip = code.as_ptr() as u64;
    context.Rax = u64::MAX;
    assert_eq!(emulate(&mut context), 0);

    It needs a real CONTEXT and the emulator's instruction decoder, so it only runs on Windows. I did not run it. What I checked instead is that the code it exercises reaches readable/writable with va taken from ctx.Rax (console_insn.rs:369, :437), which is the case the fix covers.

  • Windows. Everything above is Linux (Fedora 45, x86_64) with the pinned toolchain (rustc 1.98.1). The mock VirtualQuery is a stand-in, not Windows' own; §3 and §5 say exactly what it does and does not settle.

  • The rest of leonida-loader's tests — the crate does not build here, so I ran neither the pull request's test in the crate nor the crate's other tests.

  • The CODE/WRITABLE caches (thread_local! in console_insn.rs:35-41): my harness models them, but the remembered-region path is not what these two assertions exercise — both inputs are far outside any remembered region — so I did not measure it.

  • The emulated instruction set (console_insn_decode.rs) and near()/jump(): untouched by this pull request and not examined beyond the two call sites above.

AI-assisted: MiniMax M3.1 Flash.

@KelboLive KelboLive 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.

The writable half is right and pinned: reverting it to writable_to(va, va + bytes) == Some(va + bytes) panics in the new test at console_insn.rs:319:21, and cargo test -p leonida-loader --lib is 85/85 here. With Rax = u64::MAX, line = MAX-63 and +64 overflows on the VEH path (crash.rs:469-477), so this is a real debug panic fixed.

The readable half is not pinned. Restoring readable verbatim to main's one-liner still passes the new test, because VirtualQuery short-circuits before va + bytes — I probed Windows directly: VirtualQuery(0xfffffffffffffffb) = 0, (0xffffffffffffffc0) = 0, a stack address = 48. So assert!(!readable(usize::MAX - 4, 16)) is already green on main, and the body's "it panics at console_insn.rs:313" is pointing at the writable line. Either pin readable through a pure range helper, or say in the body that it is hardening.

Two minor things:

  • writable_to still computes m.BaseAddress as usize + m.RegionSize unchecked (:350), which is the same expression this PR now guards in readable — inconsistent with the "nothing in the handler may panic" rationale, though it cannot overflow for a real region.
  • "its write_sites.rs half is already in main through #2664" is not true today: #2664 is open, and its head is not an ancestor of main; main's write_sites.rs has no such checked_add.

Also worth noting: the "in release the end wrapped and could let the check pass" line is true arithmetic but not observable — writable_to(va, 0) still needs VirtualQuery to succeed at 0xffff…ffc0, which Windows refuses. That is fine as hardening; it just is not a release bug.

Merge is clean; 368 commits behind, but console_insn.rs is byte-identical between the merge base and main, and no other open PR touches it.

@OreoFR

OreoFR commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Merging (added to the merge queue). Head 3cd5de6 merges cleanly with main c4ca576. Claim: D3D12-LOADER-CONSOLE-INSN-CHECKED-RANGES (#2570 (comment)). Red/green: imShangLi (Linux, PASS: main panics with an add overflow, the head passes), KelboLive review on this head (reverting the writable half panics in the new test). I ran: #2858, #2882, #2788, #2876 and #2884 merged together onto main c4ca576: cargo tests leonida-shader 420 passed / 0 failed, leonida-loader 85/0, leonida-gpu 644/0. In-game run: RTX 4070 Laptop 8 GB, NVIDIA 621.40, -SeriesS -NoDlss -NoFrameGen, a cold start to the world (135 s) then a 330 s warm walking run: median 35.4 ms (28.2 fps), private memory max 24.4 GB, 0 device lost. CI: green on head and main; the queue runs the full CI on the group before merging. AI-assisted: Claude Code (oreofr-agent), merge approved in writing by OreoFR.

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