d3d12_xs: guard reads of placed-texture memory with a fault-recovering call (root fix for #110) #153

Closed
github-bot wants to merge 2 commits from gh-pr/153/head into gh-pr/153/base
Owner

@⁠MeNoSkills on GitHub · 2026-11-22 16:19 UTC · original
MeNoSkills:fix/upload-guarded-reads → main · +487 −71 · 3 files · 2 commits · closed without merging

Follow-up to #146, which kept direct reads by default and offered a copying snapshot behind an env var. You asked for the root fix: handle a title pointer that goes bad where it is used, without a copy per call. Refs #110.

Change

  • New guard.rs: guarded(f) -> Option<R> runs f through a small x86-64 trampoline (global_asm!) and a vectored exception handler. If f takes an access violation or in-page error while a guard is active on that thread, the handler restores the stack and registers saved by the trampoline and the call returns None. It is a __try/__except equivalent for a closure. Nonvolatile registers (including xmm6-xmm15) are saved and restored by the trampoline; the handler is installed once and only acts when the current thread has an active guard, otherwise it lets the exception continue.
  • upload.rs: every direct read of title memory runs under the guard: the hash, the all-zero test, the sparse copy, the de-tile (also inside the parallel workers) and the zero-watch scan. When a read fails, the subresource is counted as unreadable, keeps no hash and is retried on a later pump, as the existing "unreadable placed texture" path does.
  • Removed the ReadProcessMemory snapshot and TOMBOX_UPLOAD_SAFE_READ, which the guard makes unnecessary.

Cost

No copy and no extra pass on the default path. Micro-bench guarded_reads_cost_one_call_per_range_not_per_byte (release, one run, one machine), hash of a buffer with and without the guard:

hash of unguarded guarded
16 KiB 2741 ns/call 2733 ns/call (-0.3%)
256 KiB 44009 ns/call 44000 ns/call (0.0%)
4 MiB 709938 ns/call 708056 ns/call (-0.3%)

The remaining cost is one trampoline call and one thread-local write per guarded range. These are micro-bench numbers; I have no title dump, so I cannot give per-frame numbers.

Tests

  • guard::tests: normal result, decommitted page returns None, nested guards, 1000 faults with a running accumulator to check the saved registers, a concurrent decommit/recommit thread against a reader (20000 reads: 19557 completed, 443 faulted and were skipped, no crash), and the guard is cleared afterwards.
  • upload::zero_watch_tests::decommitted_memory_skips_the_read_instead_of_faulting: hash, zero test and de-tile all fail cleanly on a decommitted page and succeed on the intact ones.
  • cargo test --locked -p d3d12_xs --lib: 459 passed, 27 failed. The same 27 fail on current main in my environment (Windows 10 build 19045, not Windows 11), main has 453 passing.
  • python .github/scripts/pr_gate.py --base upstream/main --head HEAD: 0 problems.

Caveats

  • The guard catches any access violation inside the closure it wraps, including one caused by a bug in our own code, and turns it into a skipped read. It should only wrap reads of title memory, as done here.
  • Frames abandoned by a recovered fault are not unwound: their destructors do not run (a possible leak, no unsoundness for the plain closures used here).
  • x86-64 Windows only (the whole crate already is). I tested on Windows 10 only, not on Windows 11, and not with a title.
**@⁠MeNoSkills** on GitHub · 2026-11-22 16:19 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/153) `MeNoSkills:fix/upload-guarded-reads` → `main` · +487 −71 · 3 files · 2 commits · closed without merging Follow-up to #146, which kept direct reads by default and offered a copying snapshot behind an env var. You asked for the root fix: handle a title pointer that goes bad where it is used, without a copy per call. Refs #110. ## Change - New `guard.rs`: `guarded(f) -> Option<R>` runs `f` through a small x86-64 trampoline (`global_asm!`) and a vectored exception handler. If `f` takes an access violation or in-page error while a guard is active on that thread, the handler restores the stack and registers saved by the trampoline and the call returns `None`. It is a `__try/__except` equivalent for a closure. Nonvolatile registers (including xmm6-xmm15) are saved and restored by the trampoline; the handler is installed once and only acts when the current thread has an active guard, otherwise it lets the exception continue. - `upload.rs`: every direct read of title memory runs under the guard: the hash, the all-zero test, the sparse copy, the de-tile (also inside the parallel workers) and the zero-watch scan. When a read fails, the subresource is counted as unreadable, keeps no hash and is retried on a later pump, as the existing "unreadable placed texture" path does. - Removed the `ReadProcessMemory` snapshot and `TOMBOX_UPLOAD_SAFE_READ`, which the guard makes unnecessary. ## Cost No copy and no extra pass on the default path. Micro-bench `guarded_reads_cost_one_call_per_range_not_per_byte` (release, one run, one machine), hash of a buffer with and without the guard: | hash of | unguarded | guarded | |---|---|---| | 16 KiB | 2741 ns/call | 2733 ns/call (-0.3%) | | 256 KiB | 44009 ns/call | 44000 ns/call (0.0%) | | 4 MiB | 709938 ns/call | 708056 ns/call (-0.3%) | The remaining cost is one trampoline call and one thread-local write per guarded range. These are micro-bench numbers; I have no title dump, so I cannot give per-frame numbers. ## Tests - `guard::tests`: normal result, decommitted page returns `None`, nested guards, 1000 faults with a running accumulator to check the saved registers, a concurrent decommit/recommit thread against a reader (20000 reads: 19557 completed, 443 faulted and were skipped, no crash), and the guard is cleared afterwards. - `upload::zero_watch_tests::decommitted_memory_skips_the_read_instead_of_faulting`: hash, zero test and de-tile all fail cleanly on a decommitted page and succeed on the intact ones. - `cargo test --locked -p d3d12_xs --lib`: 459 passed, 27 failed. The same 27 fail on current main in my environment (Windows 10 build 19045, not Windows 11), main has 453 passing. - `python .github/scripts/pr_gate.py --base upstream/main --head HEAD`: 0 problems. ## Caveats - The guard catches any access violation inside the closure it wraps, including one caused by a bug in our own code, and turns it into a skipped read. It should only wrap reads of title memory, as done here. - Frames abandoned by a recovered fault are not unwound: their destructors do not run (a possible leak, no unsoundness for the plain closures used here). - x86-64 Windows only (the whole crate already is). I tested on Windows 10 only, not on Windows 11, and not with a title.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 06:11:58 +00:00
github-bot closed this pull request 2026-11-26 06:11:58 +00:00
Author
Owner

@⁠omonkeyz on GitHub · 2026-11-22 16:28 UTC · original

Thanks, this is the right direction for #110: no copy, and the bench shows no measurable cost. The asm looks right to me (alignment, xmm6-15 and the nonvolatile registers, shadow space, and the CONTEXT offsets), and the extern "C" trampoline makes a panic abort rather than unwind into code with no unwind info. It will be applied once these four conditions hold:

  1. Narrow the catch. The handler acts only when the faulting thread's guard depth is > 0 and the fault address (ExceptionInformation[1]) is outside our own modules' images and heaps, i.e. a title address. In every other case it returns EXCEPTION_CONTINUE_SEARCH, so a bug in our own code still crashes visibly.
  2. Log every caught fault, rate-limited, with the fault address and the call site (e.g. the faulting RIP, or a #[track_caller] location passed into guarded), so recovered faults never pass silently.
  3. Keep guarded closures trivial by structure. They must not take locks, allocate, or hold RAII guards, because an abandoned frame never runs its destructors. A comment would break the repo's no-comment rule, so enforce it in code. For example, make the guarded entry point take raw pointers and lengths plus a plain fn (not a capturing closure), or add a test that pins this down.
  4. Coexistence with other exception handlers (DXC, the title's own VEH/SEH): register with First = 0, or explain in the PR why First = 1 is needed and safe.

Please also rebase onto current main (604b5a1). Thanks again!

**@⁠omonkeyz** on GitHub · 2026-11-22 16:28 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/153#issuecomment-7082099340) Thanks, this is the right direction for #110: no copy, and the bench shows no measurable cost. The asm looks right to me (alignment, xmm6-15 and the nonvolatile registers, shadow space, and the CONTEXT offsets), and the extern "C" trampoline makes a panic abort rather than unwind into code with no unwind info. It will be applied once these four conditions hold: 1. **Narrow the catch.** The handler acts only when the faulting thread's guard depth is > 0 **and** the fault address (`ExceptionInformation[1]`) is outside our own modules' images and heaps, i.e. a title address. In every other case it returns `EXCEPTION_CONTINUE_SEARCH`, so a bug in our own code still crashes visibly. 2. **Log every caught fault**, rate-limited, with the fault address and the call site (e.g. the faulting RIP, or a `#[track_caller]` location passed into `guarded`), so recovered faults never pass silently. 3. **Keep guarded closures trivial by structure.** They must not take locks, allocate, or hold RAII guards, because an abandoned frame never runs its destructors. A comment would break the repo's no-comment rule, so enforce it in code. For example, make the guarded entry point take raw pointers and lengths plus a plain `fn` (not a capturing closure), or add a test that pins this down. 4. **Coexistence with other exception handlers** (DXC, the title's own VEH/SEH): register with `First = 0`, or explain in the PR why `First = 1` is needed and safe. Please also rebase onto current main (604b5a1). Thanks again!
Author
Owner

@⁠MeNoSkills on GitHub · 2026-11-22 16:35 UTC · original

Thanks for the careful review. Rebased onto 604b5a1 and updated in 112da49; all four conditions are in.

  1. Narrow catch. guarded(lo, len, f, ctx) now takes the title range the closure is about to read. The handler acts only when a guard is active on the thread, the code is an access violation or in-page error, there are at least 2 exception parameters, and the fault address (ExceptionInformation[1]) is inside [lo, lo+len). Anything else returns EXCEPTION_CONTINUE_SEARCH, so a bug in our own code (a stray pointer, a write to the upload buffer) still crashes visibly. I used the declared range instead of "outside our images and heaps" because it is stricter and does not need to enumerate heaps. Tests cover the boundaries (first and last byte, one past either end, address 0, one parameter, other exception codes) and drive the handler with a fabricated EXCEPTION_RECORD and CONTEXT to check it leaves them untouched when it declines.

  2. Logging. Every recovered fault is recorded with the fault address, the faulting RIP and the call site (#[track_caller] through the helpers, so it points into upload.rs), rate limited to the first 32 and then every 1024th. The log call happens after recovery, outside the handler. There is also a recovered() counter, which the tests use.

  3. Trivial by structure. There are no closures any more. guarded takes a plain unsafe extern "C" fn(*mut c_void) and a pointer to a job struct of plain data (hash, non-zero scan, sparse copy, de-tile). Each job has a const _: () = assert!(!needs_drop::<Job>()), so adding a field with a destructor fails to compile. The job functions do not allocate or take locks. This does not enforce the lock/alloc rule by type, only by structure and review.

  4. Coexistence. Registered with First = 0, so the title's, DXC's and other VEH handlers run before ours. I do not have a case that needs First = 1.

cargo test --locked -p d3d12_xs --lib: 462 passed, 27 failed; the same 27 fail on main in my environment (Windows 10 build 19045). Micro-bench guarded vs unguarded hash: +0.5% (16 KiB), +0.1% (256 KiB), -0.1% (4 MiB), i.e. noise. I still have not run this on Windows 11 or with a title.

**@⁠MeNoSkills** on GitHub · 2026-11-22 16:35 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/153#issuecomment-7082193685) Thanks for the careful review. Rebased onto 604b5a1 and updated in 112da49; all four conditions are in. 1. Narrow catch. `guarded(lo, len, f, ctx)` now takes the title range the closure is about to read. The handler acts only when a guard is active on the thread, the code is an access violation or in-page error, there are at least 2 exception parameters, and the fault address (ExceptionInformation[1]) is inside [lo, lo+len). Anything else returns EXCEPTION_CONTINUE_SEARCH, so a bug in our own code (a stray pointer, a write to the upload buffer) still crashes visibly. I used the declared range instead of "outside our images and heaps" because it is stricter and does not need to enumerate heaps. Tests cover the boundaries (first and last byte, one past either end, address 0, one parameter, other exception codes) and drive the handler with a fabricated EXCEPTION_RECORD and CONTEXT to check it leaves them untouched when it declines. 2. Logging. Every recovered fault is recorded with the fault address, the faulting RIP and the call site (#[track_caller] through the helpers, so it points into upload.rs), rate limited to the first 32 and then every 1024th. The log call happens after recovery, outside the handler. There is also a `recovered()` counter, which the tests use. 3. Trivial by structure. There are no closures any more. `guarded` takes a plain `unsafe extern "C" fn(*mut c_void)` and a pointer to a job struct of plain data (hash, non-zero scan, sparse copy, de-tile). Each job has a `const _: () = assert!(!needs_drop::<Job>())`, so adding a field with a destructor fails to compile. The job functions do not allocate or take locks. This does not enforce the lock/alloc rule by type, only by structure and review. 4. Coexistence. Registered with First = 0, so the title's, DXC's and other VEH handlers run before ours. I do not have a case that needs First = 1. `cargo test --locked -p d3d12_xs --lib`: 462 passed, 27 failed; the same 27 fail on main in my environment (Windows 10 build 19045). Micro-bench guarded vs unguarded hash: +0.5% (16 KiB), +0.1% (256 KiB), -0.1% (4 MiB), i.e. noise. I still have not run this on Windows 11 or with a title.
Author
Owner

@⁠omonkeyz on GitHub · 2026-11-22 17:24 UTC · original

Applied in 5d5bc33 and 439826e (merged in fe391fe) with your authorship kept, thanks. All four conditions hold:

  • the handler acts only on a fault inside the declared range;
  • recovered faults are logged with a rate limit, the fault address and the call site;
  • the signature now takes a plain fn and a context pointer;
  • the handler is registered last.

I made one change: in a_read_of_decommitted_memory_inside_the_range_is_recovered_and_counted, the recovered() check is now >= before + 2 instead of exact equality. RECOVERED is a process-wide counter, and the concurrent-decommit test increments it at the same time, so the exact check failed under the default parallel test run. cargo test -p d3d12_xs --lib now passes 494/494.

**@⁠omonkeyz** on GitHub · 2026-11-22 17:24 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/153#issuecomment-7082810973) Applied in 5d5bc33 and 439826e (merged in fe391fe) with your authorship kept, thanks. All four conditions hold: - the handler acts only on a fault inside the declared range; - recovered faults are logged with a rate limit, the fault address and the call site; - the signature now takes a plain fn and a context pointer; - the handler is registered last. I made one change: in `a_read_of_decommitted_memory_inside_the_range_is_recovered_and_counted`, the `recovered()` check is now `>= before + 2` instead of exact equality. `RECOVERED` is a process-wide counter, and the concurrent-decommit test increments it at the same time, so the exact check failed under the default parallel test run. `cargo test -p d3d12_xs --lib` now passes 494/494.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.