xmem: keep the space below 4 GiB for the title's 32-bit memory (port of VIctory#1009) #39

Open
WHOISJARDAS wants to merge 1 commit from upstream-pr/39 into main
WHOISJARDAS commented 2026-11-25 12:34:53 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by WHOISJARDAS on 2026-11-25T12:34:53Z.


On this machine (RX 9070 XT, Ryzen 7 9800X3D, Windows 11 26200) this fork's 4cbe9d7 cannot start the title: it stops at the title's own assertion, 0x80000003 at +0x19f4f58, about 1 s in. This is Marvisak/VIctory#790: the title's 185 MB 32-bit placeholder (XMemVirtualAlloc size=193986560 kind=0x42000 flags=0x7) finds no room below 4 GiB, because the host's memory got there first. Here 2.3 GB of it was the AMD driver's shader cache files (%LOCALAPPDATA%\AMD\DxcCache\*.parc) mapped below 4 GiB, and Exploit protection's Bottom-up ASLR is off system-wide, so it happens on every start.

This is a port of Marvisak/VIctory#1009 (NuraadGit, with MichaelSmithAI's bounded retry), the same change as Zettrox/ztrx#108:

  • xmem::low_guards::install() at the start of run reserves the free space below 4 GiB but the lowest 256 MB;
  • a refused 32-bit XMemVirtualAlloc releases guards one at a time and retries, guarding again what stays free;
  • a 32-bit request still refused logs one warn (nothing was logged before);
  • tests low_guards::tests::* (2).

Tested

RX 9070 XT (driver 32.0.32029.2010), Series X profile, this README's settings: 4cbe9d7 stopped at +0x19f4f58 at start; with this, it starts and reaches the world (space below 4 GiB kept for the title guards=2 mb=3722).

  • cargo test -p victory-hle --lib low_guards: 2 passed

AI use: Claude Code (Claude Opus 5.5) ported the change and ran the checks; the hardware and runs are mine.

🤖 Generated with Claude Code

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:issue:5491420292 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/39). Originally posted by [WHOISJARDAS](https://github.com/WHOISJARDAS) on 2026-11-25T12:34:53Z. --- On this machine (RX 9070 XT, Ryzen 7 9800X3D, Windows 11 26200) this fork's `4cbe9d7` cannot start the title: it stops at the title's own assertion, `0x80000003` at `+0x19f4f58`, about 1 s in. This is Marvisak/VIctory#790: the title's 185 MB 32-bit placeholder (`XMemVirtualAlloc` `size=193986560 kind=0x42000 flags=0x7`) finds no room below 4 GiB, because the host's memory got there first. Here 2.3 GB of it was the AMD driver's shader cache files (`%LOCALAPPDATA%\AMD\DxcCache\*.parc`) mapped below 4 GiB, and Exploit protection's Bottom-up ASLR is off system-wide, so it happens on every start. This is a port of Marvisak/VIctory#1009 (NuraadGit, with MichaelSmithAI's bounded retry), the same change as Zettrox/ztrx#108: - `xmem::low_guards::install()` at the start of `run` reserves the free space below 4 GiB but the lowest 256 MB; - a refused 32-bit `XMemVirtualAlloc` releases guards one at a time and retries, guarding again what stays free; - a 32-bit request still refused logs one `warn` (nothing was logged before); - tests `low_guards::tests::*` (2). ## Tested RX 9070 XT (driver 32.0.32029.2010), Series X profile, this README's settings: `4cbe9d7` stopped at `+0x19f4f58` at start; with this, it starts and reaches the world (`space below 4 GiB kept for the title guards=2 mb=3722`). - `cargo test -p victory-hle --lib low_guards`: 2 passed AI use: Claude Code (Claude Opus 5.5) ported the change and ran the checks; the hardware and runs are mine. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
gut0to commented 2026-11-27 14:49:34 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-27T14:49:34Z.

Code review location: crates/victory-hle/src/modules/xmem.rs; line 1883

@@ -1734,3 +1751,196 @@ fn log_memory(peak: &mut usize) {
         largest.join(", "),
     );
 }
+
+/// The space below 4 GiB, which the title's 32-bit memory (`XMemVirtualAlloc`
+/// with the 32-bit address flag) has to fit in.
+const FOUR_GIB: usize = 1 << 32;
+
+/// Guards over the space below 4 GiB. Windows places allocations bottom up,
+/// so the host's own memory (the driver's, heaps, the shader caches drivers
+/// map at device creation) can fill it first; with the system's bottom-up
+/// ASLR turned off (Exploit protection) it always starts there. On an
+/// AMD RX 9070 XT with that setting off, 3 MB was left, in 64 KiB pieces,
+/// when the title asked for a 185 MB 32-bit placeholder at startup (2.3 GB
+/// of it was the driver's mapped shader cache): the request was refused
+/// (`ERROR_NOT_ENOUGH_MEMORY`) and the title stopped at its own assertion.
+/// The debug layer's memory did the same elsewhere. So the free space below
+/// 4 GiB is reserved at startup, past [`low_guards::SLACK`] left for the
+/// host, and a 32-bit request that finds no room releases guards and tries
+/// again. (A port of Marvisak/VIctory#1009.)
+pub mod low_guards {
+    use std::sync::Mutex;
+
+    use windows_sys::Win32::System::Memory::{
+        MEM_FREE, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualAlloc,
+        VirtualFree, VirtualQuery,
+    };
+
+    use super::FOUR_GIB;
+
+    /// Free space left to the host below 4 GiB (the lowest free space).
+    pub(crate) const SLACK: usize = 256 << 20;
+    /// The allocation granularity of Windows.
+    const GRANULE: usize = 64 << 10;
+
+    /// The guards, `(base, bytes)`.
+    static GUARDS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+
+    fn guards() -> std::sync::MutexGuard<'static, Vec<(usize, usize)>> {
+        GUARDS.lock().unwrap_or_else(|e| e.into_inner())
+    }
+
+    /// The free runs in `[from, to)`, granule-aligned.
+    fn free_runs(from: usize, to: usize) -> Vec<(usize, usize)> {
+        let mut runs = Vec::new();
+        let mut at = from.max(GRANULE);
+        while at < to {
+            // SAFETY: plain data filled in by the query.
+            let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+            // SAFETY: a valid out pointer of the right size.
+            if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 {
+                break;
+            }
+            let base = m.BaseAddress as usize;
+            let end = (base + m.RegionSize).min(to);
+            if m.State == MEM_FREE {
+                let (start, end) = (
+                    base.max(from).next_multiple_of(GRANULE),
+                    end & !(GRANULE - 1),
+                );
+                if end > start {
+                    runs.push((start, end - start));
+                }
+            }
+            at = base + m.RegionSize;
+        }
+        runs
+    }
+
+    /// Reserves `[base, base + bytes)` as a guard; false if something took it.
+    fn guard(base: usize, bytes: usize) -> bool {
+        // SAFETY: a reservation of free address space; nothing refers to it.
+        let at = unsafe { VirtualAlloc(base as *const _, bytes, MEM_RESERVE, PAGE_NOACCESS) };
+        at as usize == base
+    }
+
+    /// Reserves the free space below 4 GiB but the lowest [`SLACK`]. Call
+    /// once, before the host allocates much (the GPU device, the caches).
+    pub fn install() {
+        let mut guards = guards();
+        let mut slack = SLACK;
+        for (mut base, mut bytes) in free_runs(0, FOUR_GIB) {
+            let left = slack.min(bytes);
+            (base, bytes, slack) = (base + left, bytes - left, slack - left);
+            if bytes > 0 && guard(base, bytes) {
+                guards.push((base, bytes));
+            }
+        }
+        let total: usize = guards.iter().map(|g| g.1).sum();
+        tracing::info!(
+            guards = guards.len(),
+            mb = total >> 20,
+            "space below 4 GiB kept for the title"
+        );
+    }
+
+    /// Try the smallest fitting guards first, then try smaller guards in
+    /// descending size order. A replacement guard cannot be retried here.
+    pub(crate) fn retry(
+        bytes: usize,
+        mut allocate: impl FnMut() -> *mut std::ffi::c_void,
+    ) -> *mut std::ffi::c_void {
+        use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
+
+        // Preserve the allocation error across address queries and reservations.
+        // SAFETY: reads this thread's last-error value.
+        let mut error = unsafe { GetLastError() };
+        let mut guards = guards();
+        let mut candidates = guards.clone();
+        candidates.sort_unstable_by_key(|&(_, size)| {
+            let fits = size >= bytes;
+            (!fits, if fits { size } else { usize::MAX - size })
+        });
+        for (base, size) in candidates {
+            // SAFETY: our own reservation, with no allocations inside it.
+            if unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) } == 0 {
+                continue;
+            }
+            guards.retain(|&(b, _)| b != base);
+            let at = allocate();
+            // SAFETY: reads this thread's last-error value.
+            error = unsafe { GetLastError() };
+            for (start, len) in free_runs(base, base + size) {
+                if guard(start, len) {
+                    guards.push((start, len));
+                }
+            }
+            if !at.is_null() {
+                return at;
+            }
+        }
+        // SAFETY: sets this thread's last-error value.
+        unsafe { SetLastError(error) };

Could the refused-retry test also assert last-error preservation? Its allocation closure currently returns null without setting an error, so the tests cover guard restoration but not that retry restores the final VirtualAlloc error after the address queries and guard recreation. An injected closure can set a known error such as ERROR_NOT_ENOUGH_MEMORY, then assert GetLastError() returns it after retry; the caller relies on this value when reporting exhaustion.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review-comment:4720780869 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/39#discussion_r4720780869). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-27T14:49:34Z. **Code review location:** `crates/victory-hle/src/modules/xmem.rs`; line 1883 ~~~~diff @@ -1734,3 +1751,196 @@ fn log_memory(peak: &mut usize) { largest.join(", "), ); } + +/// The space below 4 GiB, which the title's 32-bit memory (`XMemVirtualAlloc` +/// with the 32-bit address flag) has to fit in. +const FOUR_GIB: usize = 1 << 32; + +/// Guards over the space below 4 GiB. Windows places allocations bottom up, +/// so the host's own memory (the driver's, heaps, the shader caches drivers +/// map at device creation) can fill it first; with the system's bottom-up +/// ASLR turned off (Exploit protection) it always starts there. On an +/// AMD RX 9070 XT with that setting off, 3 MB was left, in 64 KiB pieces, +/// when the title asked for a 185 MB 32-bit placeholder at startup (2.3 GB +/// of it was the driver's mapped shader cache): the request was refused +/// (`ERROR_NOT_ENOUGH_MEMORY`) and the title stopped at its own assertion. +/// The debug layer's memory did the same elsewhere. So the free space below +/// 4 GiB is reserved at startup, past [`low_guards::SLACK`] left for the +/// host, and a 32-bit request that finds no room releases guards and tries +/// again. (A port of Marvisak/VIctory#1009.) +pub mod low_guards { + use std::sync::Mutex; + + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualAlloc, + VirtualFree, VirtualQuery, + }; + + use super::FOUR_GIB; + + /// Free space left to the host below 4 GiB (the lowest free space). + pub(crate) const SLACK: usize = 256 << 20; + /// The allocation granularity of Windows. + const GRANULE: usize = 64 << 10; + + /// The guards, `(base, bytes)`. + static GUARDS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); + + fn guards() -> std::sync::MutexGuard<'static, Vec<(usize, usize)>> { + GUARDS.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The free runs in `[from, to)`, granule-aligned. + fn free_runs(from: usize, to: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = from.max(GRANULE); + while at < to { + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 { + break; + } + let base = m.BaseAddress as usize; + let end = (base + m.RegionSize).min(to); + if m.State == MEM_FREE { + let (start, end) = ( + base.max(from).next_multiple_of(GRANULE), + end & !(GRANULE - 1), + ); + if end > start { + runs.push((start, end - start)); + } + } + at = base + m.RegionSize; + } + runs + } + + /// Reserves `[base, base + bytes)` as a guard; false if something took it. + fn guard(base: usize, bytes: usize) -> bool { + // SAFETY: a reservation of free address space; nothing refers to it. + let at = unsafe { VirtualAlloc(base as *const _, bytes, MEM_RESERVE, PAGE_NOACCESS) }; + at as usize == base + } + + /// Reserves the free space below 4 GiB but the lowest [`SLACK`]. Call + /// once, before the host allocates much (the GPU device, the caches). + pub fn install() { + let mut guards = guards(); + let mut slack = SLACK; + for (mut base, mut bytes) in free_runs(0, FOUR_GIB) { + let left = slack.min(bytes); + (base, bytes, slack) = (base + left, bytes - left, slack - left); + if bytes > 0 && guard(base, bytes) { + guards.push((base, bytes)); + } + } + let total: usize = guards.iter().map(|g| g.1).sum(); + tracing::info!( + guards = guards.len(), + mb = total >> 20, + "space below 4 GiB kept for the title" + ); + } + + /// Try the smallest fitting guards first, then try smaller guards in + /// descending size order. A replacement guard cannot be retried here. + pub(crate) fn retry( + bytes: usize, + mut allocate: impl FnMut() -> *mut std::ffi::c_void, + ) -> *mut std::ffi::c_void { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + + // Preserve the allocation error across address queries and reservations. + // SAFETY: reads this thread's last-error value. + let mut error = unsafe { GetLastError() }; + let mut guards = guards(); + let mut candidates = guards.clone(); + candidates.sort_unstable_by_key(|&(_, size)| { + let fits = size >= bytes; + (!fits, if fits { size } else { usize::MAX - size }) + }); + for (base, size) in candidates { + // SAFETY: our own reservation, with no allocations inside it. + if unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) } == 0 { + continue; + } + guards.retain(|&(b, _)| b != base); + let at = allocate(); + // SAFETY: reads this thread's last-error value. + error = unsafe { GetLastError() }; + for (start, len) in free_runs(base, base + size) { + if guard(start, len) { + guards.push((start, len)); + } + } + if !at.is_null() { + return at; + } + } + // SAFETY: sets this thread's last-error value. + unsafe { SetLastError(error) }; ~~~~ --- Could the refused-retry test also assert last-error preservation? Its allocation closure currently returns null without setting an error, so the tests cover guard restoration but not that `retry` restores the final `VirtualAlloc` error after the address queries and guard recreation. An injected closure can set a known error such as `ERROR_NOT_ENOUGH_MEMORY`, then assert `GetLastError()` returns it after retry; the caller relies on this value when reporting exhaustion.
gut0to commented 2026-11-27 14:49:34 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-27T14:49:34Z.

Review: COMMENTED


AI-assisted static review (ChatGPT); I inspected the retry tests but did not run them.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review:6089894686 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/39#pullrequestreview-6089894686). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-27T14:49:34Z. **Review:** COMMENTED --- AI-assisted static review (ChatGPT); I inspected the retry tests but did not run them.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/39:upstream-pr/39'
git switch 'upstream-pr/39'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/39'
git switch 'upstream-pr/39'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/39'
git switch 'upstream-pr/39'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/39'
git switch 'main'
git merge --squash 'upstream-pr/39'
git switch 'main'
git merge --ff-only 'upstream-pr/39'
git switch 'main'
git merge 'upstream-pr/39'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Belobug/VIctory-Belobug-AMD!39
No description provided.