Second start with a saved pipeline cache hangs the PC: constrained XMemVirtualAlloc search holds the address-space lock while dxgmms2 waits on it #3765

Closed
opened 2026-11-30 06:19:18 +00:00 by github-bot · 8 comments
Owner

@⁠victorious-gh on GitHub · 2026-11-30 06:14 UTC · original

I fixed the white screen crash at the start. I narrowed it down to the cached shaders, by swapping the victory cache dir on each startup to fix it. #2737 is the same issue i'm facing. The following is claude's description and fix for the issue. I applied a patch from claude and it worked.

Summary

On the second start with a saved pipeline cache, about 3 s into the game, the game window goes white and stops responding. Soon after, Windows can no longer start new processes. The game process can't be ended, and only a power-off recovers the PC. A manual kernel dump shows a lock chain: the game's constrained XMemVirtualAlloc reservation spends tens of seconds in the kernel's address search while holding the process address-space lock, and the graphics kernel's memory manager (dxgmms2) waits on that lock while holding its own. Placing the reservation at an address we find ourselves fixes it on my PC.

Environment

  • Windows 11, 10.0.26100.9974, with VBS/HVCI on (Hyper-V present)
  • RTX 4070 Ti (12 GB), driver 610.88
  • 64 GB RAM, 20 logical processors
  • Hang reproduced on a build from f889bb07. The fix was tested on 41adb55, which doesn't change xmem.rs or the XMemVirtualAlloc path.
  • Launched with scripts\play-nvidia.ps1 -NoMenu -SeriesS -Dlss quality -Fps 30 -Preload, with no frame generation and no mods
  • TdrLevel is not set (Windows default)

Steps to reproduce

  1. Start with an empty cache folder: -More VICTORY_CACHE_DIR=<new folder>. The game runs normally. Close it with F1 → SAVE AND CLOSE GAME.
  2. Start again with the same cache folder.
  3. About 3 s after title pipelines to start early pipelines=N, the hang begins.

This reproduces on most second starts, not all. It hung 3 of 3 times with a cache of 2482 early pipelines (157 MB library) and also with 1844. One second start with 1812 early pipelines didn't hang.

What you see

  • The game window turns white and shows "Not responding".
  • New processes don't start: Task Manager, cmd, Win+X/Win+R, Resource Monitor.
  • Already-running programs, such as a browser, keep working.
  • System log: SCM 7000/7011 timeouts (AppXSvc, WerSvc, gpsvc and others) and DCOM 10010 for as long as the hang lasts (40+ minutes in one case).
  • No nvlddmkm 4101, so TDR never fires.
  • TerminateProcess on the game returns "Access is denied", because the process is already exiting and can't finish.
  • Recovery needs a power-off (Kernel-Power 41, bugcheck 0).

Log

Every hang ends on the same lines:

INFO victory_gpu::pipeline::library: title pipelines to start early pipelines=2482
INFO victory_hle::modules::xmem: title memory asked for as protection 0x4, kind 0x203000, flags 0x3: 4 times, 82 MB, ...

In runs that don't hang, the next line, about 6 ms later, is the title's 3.9 GB placeholder:

XMemVirtualAlloc without write watching ... size=4170186752 kind=0x42000 flags=0x23

In the hung runs that line never appears, even with VICTORY_LOG_SYNC=1.

Kernel dump (manual 0xE2, about 30 s into the hang)

Threads in victory.exe:

  1. Running, KernelTime 27.4 s of the process's 30 s. It holds the process address-space lock:
    nt!RtlFindClearBitsEx
    nt!MiFindEmptyAddressRange
    nt!MiSelectUserAddress
    nt!MiReserveUserMemory
    nt!MiAllocateVirtualMemory
    nt!NtAllocateVirtualMemoryEx      <- VirtualAlloc2 with MEM_ADDRESS_REQUIREMENTS (XMemVirtualAlloc)
    
  2. Holds the dxgmms2 recycle-heap mutex and waits for the address-space lock:
    nt!ExfAcquirePushLockExclusiveEx
    nt!LOCK_ADDRESS_SPACE
    nt!MiReserveUserMemory
    nt!NtAllocateVirtualMemory
    dxgmms2!VidMmAllocateVirtualMemory
    dxgmms2!VIDMM_RECYCLE_BLOCK::Allocate
    dxgmms2!VIDMM_RECYCLE_HEAP::Allocate
    dxgmms2!VIDMM_RECYCLE_HEAP_MGR::Allocate
    dxgmms2!VIDMM_GLOBAL::CommitLocalBackingStore
    ...
    dxgkrnl!DxgkCreateAllocation
    
  3. 7 more threads wait (WrPushLock, non-alertable) for that mutex:
    dxgmms2!DXGAUTOMUTEX::Acquire
    dxgmms2!VIDMM_RECYCLE_HEAP_MGR::Allocate
    dxgmms2!VIDMM_GLOBAL::CommitLocalBackingStore
    ...
    dxgkrnl!DxgkCreateAllocation
    

Full !process 0 1f victory.exe output available on request.

What I think is happening

These parts are inferences, not things the dump proves:

  • With a saved cache, thousands of pipelines start early. The driver's GPU allocations reserve virtual memory in the game process at the same time as the title's big constrained reservation in [4 GiB, 2^40). This fragments that window, and the kernel's constrained search (MiFindEmptyAddressRange) gets pathologically slow.
  • The other programs hanging suggests the dxgmms2 lock is shared across processes, so other programs' GPU allocations queue behind it. The dump only shows victory.exe's threads.

Fix (confirmed on my PC)

For constrained reservations in XMemVirtualAlloc, find the address ourselves instead of using the kernel's search:

  • Walk the window with VirtualQueryEx (a few hundred regions) to find the first free, aligned range that fits.
  • Call VirtualAlloc2 with that explicit base and no MEM_ADDRESS_REQUIREMENTS.
  • If another thread takes the range in between, retry further on (a few tries). If nothing fits, fall back to the current constrained call.
  • MEM_TOP_DOWN requests stay with the kernel.
  • VICTORY_XMEM_OWN_SEARCH=0 restores the current behavior.

Tested on 41adb55 with the same repro. Two second starts with saved caches got through:

  • 1844 early pipelines: the same cache that hung the unpatched build.
  • 2271 early pipelines: played for about 6 minutes, then closed normally.

In both runs the 3.9 GB placeholder was placed about 22 ms after title pipelines to start early, at 0x1b00000000:

INFO victory_gpu::pipeline::library: title pipelines to start early pipelines=1844
INFO victory_hle::modules::xmem: XMemVirtualAlloc without write watching ... at=0x1b00000000 size=4170186752 kind=0x42000 flags=0x23
INFO victory_gpu::pipeline::make: pipeline workers workers=5

Happy to open a PR.

Workaround (without the fix)

Use a new, empty VICTORY_CACHE_DIR for each run, or clear the shader cache before starting. This costs a full shader build every time.

  • The unhandled-exception filter returns EXCEPTION_CONTINUE_SEARCH, which hands crashes to Windows Error Reporting. When new processes can't start, WerFault can't start either, so the crashed process stays up.
  • By default the process runs at ABOVE_NORMAL, and title threads that ask for TIME_CRITICAL/HIGHEST get it (the cap only applies with VICTORY_STARTUP_PRIORITIES). This makes it harder for the rest of the system to respond when the game is busy.
**@⁠victorious-gh** on GitHub · 2026-11-30 06:14 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765) I fixed the white screen crash at the start. I narrowed it down to the cached shaders, by swapping the victory cache dir on each startup to fix it. #2737 is the same issue i'm facing. The following is claude's description and fix for the issue. I applied a patch from claude and it worked. ### Summary On the second start with a saved pipeline cache, about 3 s into the game, the game window goes white and stops responding. Soon after, Windows can no longer start new processes. The game process can't be ended, and only a power-off recovers the PC. A manual kernel dump shows a lock chain: the game's constrained `XMemVirtualAlloc` reservation spends tens of seconds in the kernel's address search while holding the process address-space lock, and the graphics kernel's memory manager (`dxgmms2`) waits on that lock while holding its own. Placing the reservation at an address we find ourselves fixes it on my PC. ### Environment - Windows 11, 10.0.26100.9974, with VBS/HVCI on (Hyper-V present) - RTX 4070 Ti (12 GB), driver 610.88 - 64 GB RAM, 20 logical processors - Hang reproduced on a build from `f889bb07`. The fix was tested on `41adb55`, which doesn't change `xmem.rs` or the `XMemVirtualAlloc` path. - Launched with `scripts\play-nvidia.ps1 -NoMenu -SeriesS -Dlss quality -Fps 30 -Preload`, with no frame generation and no mods - `TdrLevel` is not set (Windows default) ### Steps to reproduce 1. Start with an empty cache folder: `-More VICTORY_CACHE_DIR=<new folder>`. The game runs normally. Close it with F1 → SAVE AND CLOSE GAME. 2. Start again with the same cache folder. 3. About 3 s after `title pipelines to start early pipelines=N`, the hang begins. This reproduces on most second starts, not all. It hung 3 of 3 times with a cache of 2482 early pipelines (157 MB library) and also with 1844. One second start with 1812 early pipelines didn't hang. ### What you see - The game window turns white and shows "Not responding". - New processes don't start: Task Manager, cmd, Win+X/Win+R, Resource Monitor. - Already-running programs, such as a browser, keep working. - System log: SCM 7000/7011 timeouts (AppXSvc, WerSvc, gpsvc and others) and DCOM 10010 for as long as the hang lasts (40+ minutes in one case). - No `nvlddmkm` 4101, so TDR never fires. - `TerminateProcess` on the game returns "Access is denied", because the process is already exiting and can't finish. - Recovery needs a power-off (Kernel-Power 41, bugcheck 0). ### Log Every hang ends on the same lines: ``` INFO victory_gpu::pipeline::library: title pipelines to start early pipelines=2482 INFO victory_hle::modules::xmem: title memory asked for as protection 0x4, kind 0x203000, flags 0x3: 4 times, 82 MB, ... ``` In runs that don't hang, the next line, about 6 ms later, is the title's 3.9 GB placeholder: ``` XMemVirtualAlloc without write watching ... size=4170186752 kind=0x42000 flags=0x23 ``` In the hung runs that line never appears, even with `VICTORY_LOG_SYNC=1`. ### Kernel dump (manual 0xE2, about 30 s into the hang) Threads in `victory.exe`: 1. **Running, KernelTime 27.4 s of the process's 30 s.** It holds the process address-space lock: ``` nt!RtlFindClearBitsEx nt!MiFindEmptyAddressRange nt!MiSelectUserAddress nt!MiReserveUserMemory nt!MiAllocateVirtualMemory nt!NtAllocateVirtualMemoryEx <- VirtualAlloc2 with MEM_ADDRESS_REQUIREMENTS (XMemVirtualAlloc) ``` 2. **Holds the `dxgmms2` recycle-heap mutex** and waits for the address-space lock: ``` nt!ExfAcquirePushLockExclusiveEx nt!LOCK_ADDRESS_SPACE nt!MiReserveUserMemory nt!NtAllocateVirtualMemory dxgmms2!VidMmAllocateVirtualMemory dxgmms2!VIDMM_RECYCLE_BLOCK::Allocate dxgmms2!VIDMM_RECYCLE_HEAP::Allocate dxgmms2!VIDMM_RECYCLE_HEAP_MGR::Allocate dxgmms2!VIDMM_GLOBAL::CommitLocalBackingStore ... dxgkrnl!DxgkCreateAllocation ``` 3. **7 more threads** wait (WrPushLock, non-alertable) for that mutex: ``` dxgmms2!DXGAUTOMUTEX::Acquire dxgmms2!VIDMM_RECYCLE_HEAP_MGR::Allocate dxgmms2!VIDMM_GLOBAL::CommitLocalBackingStore ... dxgkrnl!DxgkCreateAllocation ``` Full `!process 0 1f victory.exe` output available on request. ### What I think is happening These parts are inferences, not things the dump proves: - With a saved cache, thousands of pipelines start early. The driver's GPU allocations reserve virtual memory in the game process at the same time as the title's big constrained reservation in [4 GiB, 2^40). This fragments that window, and the kernel's constrained search (`MiFindEmptyAddressRange`) gets pathologically slow. - The other programs hanging suggests the `dxgmms2` lock is shared across processes, so other programs' GPU allocations queue behind it. The dump only shows `victory.exe`'s threads. ### Fix (confirmed on my PC) For constrained reservations in `XMemVirtualAlloc`, find the address ourselves instead of using the kernel's search: - Walk the window with `VirtualQueryEx` (a few hundred regions) to find the first free, aligned range that fits. - Call `VirtualAlloc2` with that explicit base and no `MEM_ADDRESS_REQUIREMENTS`. - If another thread takes the range in between, retry further on (a few tries). If nothing fits, fall back to the current constrained call. - `MEM_TOP_DOWN` requests stay with the kernel. - `VICTORY_XMEM_OWN_SEARCH=0` restores the current behavior. Tested on `41adb55` with the same repro. Two second starts with saved caches got through: - 1844 early pipelines: the same cache that hung the unpatched build. - 2271 early pipelines: played for about 6 minutes, then closed normally. In both runs the 3.9 GB placeholder was placed about 22 ms after `title pipelines to start early`, at `0x1b00000000`: ``` INFO victory_gpu::pipeline::library: title pipelines to start early pipelines=1844 INFO victory_hle::modules::xmem: XMemVirtualAlloc without write watching ... at=0x1b00000000 size=4170186752 kind=0x42000 flags=0x23 INFO victory_gpu::pipeline::make: pipeline workers workers=5 ``` Happy to open a PR. ### Workaround (without the fix) Use a new, empty `VICTORY_CACHE_DIR` for each run, or clear the shader cache before starting. This costs a full shader build every time. ### Related (separate issues if wanted) - The unhandled-exception filter returns `EXCEPTION_CONTINUE_SEARCH`, which hands crashes to Windows Error Reporting. When new processes can't start, `WerFault` can't start either, so the crashed process stays up. - By default the process runs at `ABOVE_NORMAL`, and title threads that ask for `TIME_CRITICAL`/`HIGHEST` get it (the cap only applies with `VICTORY_STARTUP_PRIORITIES`). This makes it harder for the rest of the system to respond when the game is busy.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-30 06:19:18 +00:00
Author
Owner

@⁠victorious-gh on GitHub · 2026-11-30 06:19 UTC · original

The following is the patch provided by claude:

diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs
index f1912a7..5fb0b2a 100644
--- a/apps/victory/src/run.rs
+++ b/apps/victory/src/run.rs
@@ -979,14 +979,23 @@ fn timers(base: usize, size: usize) {
 /// with its frames stopped first. Bit 0 of the byte at `+0x71b6340` is the watchdog's quit flag:
 /// set, its thread leaves before it counts (found in trustno1-coder/VIctory-NVIDIA#1428). Set here
 /// only for the image this was read from: the trap must be where it was found. Set again every
-/// half second, as the title may clear it while it starts. `VICTORY_TITLE_WATCHDOG=1`: the
-/// title's watchdog is left alone.
+/// half second, as the title may clear it while it starts.
+///
+/// Left alone by default, as the escape from a stuck run: a frame loop stopped for 30 s ends the
+/// game (and with `victory_loader::end_unhandled` the process ends at once, without waiting for
+/// Windows Error Reporting) instead of a white window holding the PC. A first run of a new build
+/// can stop that long while its pipelines are made: `--preload` once makes them ahead.
+/// `VICTORY_TITLE_WATCHDOG=0`: told to quit, as before.
 #[cfg(windows)]
 fn quiet_title_watchdog(base: usize, size: usize) {
     const TRAP: usize = 0x23cf683;
     const TRAP_BYTES: [u8; 11] = [0xc7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x21, 0xd4, 0x8b, 0x4d];
     const QUIT: usize = 0x71b6340;
-    if std::env::var_os("VICTORY_TITLE_WATCHDOG").is_some_and(|v| v == "1") {
+    if !std::env::var_os("VICTORY_TITLE_WATCHDOG").is_some_and(|v| v == "0") {
+        eprintln!(
+            "VIctory: the title's 30 s watchdog is on: a frame loop stopped for 30 s ends the game \
+             (VICTORY_TITLE_WATCHDOG=0: off)"
+        );
         return;
     }
     if TRAP + TRAP_BYTES.len() > size || QUIT >= size {
@@ -1000,7 +1009,7 @@ fn quiet_title_watchdog(base: usize, size: usize) {
     }
     eprintln!(
         "VIctory: the title's 30 s watchdog is told to quit, so a long stall is not ended as a crash at +0x23cf683 \
-         (VICTORY_TITLE_WATCHDOG=1: left alone)"
+         (VICTORY_TITLE_WATCHDOG=0)"
     );
     let flag = base + QUIT;
     let started = std::thread::Builder::new().name("victory-watchdog-off".to_owned()).spawn(move || {
diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml
index b645ab7..bf128fc 100644
--- a/crates/victory-hle/Cargo.toml
+++ b/crates/victory-hle/Cargo.toml
@@ -32,6 +32,7 @@ windows-sys = { workspace = true, features = [
     "Win32_System_Diagnostics_Debug",
     "Win32_System_IO",
     "Win32_System_Ioctl",
+    "Win32_System_JobObjects",
     "Win32_System_LibraryLoader",
     "Win32_System_Memory",
     "Win32_System_Power",
diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs
index efe32e2..0a5d3b5 100644
--- a/crates/victory-hle/src/modules/kernel.rs
+++ b/crates/victory-hle/src/modules/kernel.rs
@@ -409,7 +409,7 @@ pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize {
 
 extern "system" fn report_unhandled(info: *const c_void) -> i32 {
     host::report_unhandled(info);
-    match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) {
+    let answer = match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) {
         0 => 0, // EXCEPTION_CONTINUE_SEARCH
         filter => {
             type Filter = extern "system" fn(*const c_void) -> i32;
@@ -417,7 +417,13 @@ extern "system" fn report_unhandled(info: *const c_void) -> i32 {
             let filter: Filter = unsafe { std::mem::transmute(filter) };
             filter(info)
         }
+    };
+    // Left to the system, the crash would wait for Windows Error Reporting:
+    // ended here instead (`victory_loader::end_unhandled`).
+    if answer == 0 {
+        host::end_unhandled(info);
     }
+    answer
 }
 
 /// See [`exit`]; only the current process is logged.
@@ -760,11 +766,14 @@ pub extern "system" fn GetCommandLineW() -> *const u16 {
 /// `VICTORY_STARTUP_PRIORITIES=<seconds>` (off by default) raises them for
 /// the first seconds of the run only, while the title loads beside the
 /// pipeline library's loads, and gives them back what they asked for after
-/// (with `VICTORY_TITLE_PRIORITIES=0`; without it they stay raised). It
-/// also holds every title thread at normal at most, for the whole run: the
-/// process runs above normal, and a title thread at "highest" or "time
-/// critical" would be level with or above the normal threads of another program
-/// in the high class that must not wait for us.
+/// (with `VICTORY_TITLE_PRIORITIES=0`; without it they stay raised).
+///
+/// Every title thread is also held at normal at most, for the whole run (by
+/// default; `VICTORY_TITLE_PRIORITY_CAP=0`: as asked, as before): on the
+/// console those threads have cores of their own, here a title thread at
+/// "highest" or "time critical" is level with or above the threads of every
+/// other program, Task Manager's and the virus scanner's among them, and with
+/// it busy they could not start.
 fn title_priority(asked: i32, raise: bool, cap: bool) -> i32 {
     const IDLE: i32 = -15;
     const LOWEST: i32 = -2;
@@ -779,18 +788,27 @@ fn title_priority(asked: i32, raise: bool, cap: bool) -> i32 {
 }
 
 /// Whether idle and lowest asks are raised, and asks above normal held at
-/// normal, `elapsed` into the run: see [`title_priority`].
+/// normal, `elapsed` into the run: see [`title_priority`]. `cap` holds them
+/// at normal without the startup switch too.
 fn priority_rules(
     as_set: bool,
     startup: Option<std::time::Duration>,
     elapsed: std::time::Duration,
+    cap: bool,
 ) -> (bool, bool) {
     match startup {
-        None => (!as_set, false),
+        None => (!as_set, cap),
         Some(window) => (!as_set || elapsed < window, true),
     }
 }
 
+/// `VICTORY_TITLE_PRIORITY_CAP`: title threads held at normal at most, on
+/// unless it is `0`.
+fn priority_cap() -> bool {
+    static CAP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *CAP.get_or_init(|| !std::env::var_os("VICTORY_TITLE_PRIORITY_CAP").is_some_and(|v| v == "0"))
+}
+
 /// `VICTORY_STARTUP_PRIORITIES`, in seconds.
 fn startup_window() -> Option<std::time::Duration> {
     static WINDOW: std::sync::OnceLock<Option<std::time::Duration>> = std::sync::OnceLock::new();
@@ -884,7 +902,7 @@ pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) ->
     let as_set = *AS_SET
         .get_or_init(|| std::env::var_os("VICTORY_TITLE_PRIORITIES").is_some_and(|v| v == "0"));
     let startup = startup_window();
-    let (mut raise, cap) = priority_rules(as_set, startup, run_time());
+    let (mut raise, cap) = priority_rules(as_set, startup, run_time(), priority_cap());
     if raise
         && as_set
         && title_priority(priority, true, cap) != title_priority(priority, false, cap)
@@ -1289,6 +1307,11 @@ mod host {
         unsafe { victory_loader::report_unhandled(info.cast()) };
     }
 
+    pub(super) fn end_unhandled(info: *const c_void) {
+        // SAFETY: as above.
+        unsafe { victory_loader::end_unhandled(info.cast()) };
+    }
+
     pub(super) fn note_title_output(line: &str) {
         victory_loader::note_title_output(line);
     }
@@ -1415,6 +1438,8 @@ mod host {
 
     pub(super) fn report_unhandled(_: *const c_void) {}
 
+    pub(super) fn end_unhandled(_: *const c_void) {}
+
     pub(super) fn note_title_output(_: &str) {}
 
     /// UTF-8, up to the first NUL.
@@ -1513,21 +1538,27 @@ mod tests {
         use std::time::Duration;
         let asks = [-15, -2, 0, 2, 15];
         let window = Some(Duration::from_secs(220));
-        let given = |as_set, startup, elapsed: u64| -> Vec<i32> {
-            let (raise, cap) = priority_rules(as_set, startup, Duration::from_secs(elapsed));
+        let given_with = |as_set, startup, elapsed: u64, cap_on: bool| -> Vec<i32> {
+            let (raise, cap) = priority_rules(as_set, startup, Duration::from_secs(elapsed), cap_on);
             asks.iter()
                 .map(|&p| title_priority(p, raise, cap))
                 .collect()
         };
-        // Neither switch: raised, the rest as asked.
-        assert_eq!(given(false, None, 10), [-1, -1, 0, 2, 15]);
-        // VICTORY_TITLE_PRIORITIES=0: as asked.
-        assert_eq!(given(true, None, 10), [-15, -2, 0, 2, 15]);
-        // With the startup switch, during its seconds and after.
+        let given = |as_set, startup, elapsed| given_with(as_set, startup, elapsed, true);
+        // Neither switch: raised, and nothing above normal.
+        assert_eq!(given(false, None, 10), [-1, -1, 0, 0, 0]);
+        // VICTORY_TITLE_PRIORITIES=0: as asked, but nothing above normal.
+        assert_eq!(given(true, None, 10), [-15, -2, 0, 0, 0]);
+        // VICTORY_TITLE_PRIORITY_CAP=0: above normal as asked, as before.
+        assert_eq!(given_with(false, None, 10, false), [-1, -1, 0, 2, 15]);
+        assert_eq!(given_with(true, None, 10, false), [-15, -2, 0, 2, 15]);
+        // With the startup switch, during its seconds and after (held at
+        // normal whatever VICTORY_TITLE_PRIORITY_CAP says).
         assert_eq!(given(true, window, 10), [-1, -1, 0, 0, 0]);
         assert_eq!(given(true, window, 300), [-15, -2, 0, 0, 0]);
         assert_eq!(given(false, window, 10), [-1, -1, 0, 0, 0]);
         assert_eq!(given(false, window, 300), [-1, -1, 0, 0, 0]);
+        assert_eq!(given_with(false, window, 300, false), [-1, -1, 0, 0, 0]);
     }
 
     #[test]
diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index 4acd5c5..ee78e78 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -232,6 +232,118 @@ fn largest_free_gap(lowest: usize, highest: usize) -> (usize, usize) {
     (best, runs)
 }
 
+/// `MEM_TOP_DOWN`: a reservation the title wants from the top of its
+/// window, left to the system's search.
+const MEM_TOP_DOWN_KIND: u32 = 0x10_0000;
+
+/// Whether the title's reservations in its window (`MEM_ADDRESS_REQUIREMENTS`)
+/// are placed at an address our own walk of the window found
+/// ([`reserve_first_fit`]), not by the system's search
+/// (`VICTORY_XMEM_OWN_SEARCH=0`: the system's, as before). The system's
+/// search for the title's 3.9 GB placeholder ran 27 s in the kernel
+/// (`nt!RtlFindClearBitsEx` under `MiFindEmptyAddressRange`) holding the
+/// process's address-space lock, on a second run whose pipelines started
+/// early beside it: the graphics kernel's memory manager, waiting for that
+/// lock under its own, stopped every program's GPU allocations behind it,
+/// the PC with it (a kernel dump, 2026-11-29). A walk of the regions
+/// (`VirtualQueryEx`, a few hundred) takes no lock that long.
+fn own_search() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        let on = !std::env::var_os("VICTORY_XMEM_OWN_SEARCH").is_some_and(|v| v == "0");
+        tracing::info!(
+            on,
+            "the title's reservations in its window are placed by our own walk of the window, not the system's search (VICTORY_XMEM_OWN_SEARCH=0: the system's)"
+        );
+        on
+    })
+}
+
+/// The first address from `from` at which `size` bytes, `align`ed (64 KiB at
+/// least, the allocation granularity), fit inside one free region of
+/// `regions` (start, length, free; in address order) and end by `highest`
+/// (the window's last address, inclusive).
+fn first_fit(
+    regions: impl IntoIterator<Item = (usize, usize, bool)>,
+    from: usize,
+    highest: usize,
+    size: usize,
+    align: usize,
+) -> Option<usize> {
+    let align = align.max(64 << 10).next_power_of_two();
+    let limit = highest.saturating_add(1);
+    for (start, len, free) in regions {
+        if !free {
+            continue;
+        }
+        let end = start.saturating_add(len).min(limit);
+        let Some(at) = start.max(from).checked_add(align - 1).map(|a| a & !(align - 1)) else {
+            continue;
+        };
+        if at < end && end - at >= size {
+            return Some(at);
+        }
+    }
+    None
+}
+
+/// The regions of this process's addresses from `from` to `highest`: start,
+/// length and whether free, in address order.
+fn regions(from: usize, highest: usize) -> Vec<(usize, usize, bool)> {
+    const MEM_FREE: u32 = 0x1_0000;
+    let mut found = Vec::new();
+    let mut at = from;
+    while at <= highest {
+        // SAFETY: plain data, filled by the call.
+        let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+        // SAFETY: `info` is an out-parameter of the right size.
+        let n = unsafe {
+            VirtualQueryEx(GetCurrentProcess(), at as *const c_void, &mut info, size_of::<MEMORY_BASIC_INFORMATION>())
+        };
+        if n == 0 || info.RegionSize == 0 {
+            break;
+        }
+        let start = info.BaseAddress as usize;
+        found.push((start, info.RegionSize, info.State == MEM_FREE));
+        at = start.saturating_add(info.RegionSize);
+        if at <= start {
+            break;
+        }
+    }
+    found
+}
+
+/// Reserves (or reserves and commits, as `kind` says) `size` bytes in
+/// [`lowest`, `highest`] at the first place [`first_fit`] finds there, the
+/// address given to the system so that it searches nothing. Tried a few
+/// times, further on each time, as another thread may take a place between
+/// the walk and the call; `None` when nothing fits or every try was
+/// refused (the system's own search is tried then).
+fn reserve_first_fit(
+    lowest: usize,
+    highest: usize,
+    size: usize,
+    align: usize,
+    kind: u32,
+    protect: u32,
+) -> Option<*mut c_void> {
+    let step = align.max(64 << 10).next_power_of_two();
+    let mut from = lowest;
+    for _ in 0..4 {
+        let at = first_fit(regions(from, highest), from, highest, size, align)?;
+        // SAFETY: a free range of our own addresses, as the walk just found
+        // it; the system refuses it if it is taken by now.
+        let got = unsafe {
+            VirtualAlloc2(GetCurrentProcess(), at as *const c_void, size, kind, protect, std::ptr::null_mut(), 0)
+        };
+        if !got.is_null() {
+            return Some(got);
+        }
+        from = at.saturating_add(step);
+    }
+    None
+}
+
 /// For tests: `VICTORY_TEST_REFUSE_MB=<n>` acts as if Windows refused the
 /// title's first reservation of `n` MiB (rounded down) at an address of our
 /// choice: 6236 for its 6.5 GB heap.
@@ -331,22 +443,34 @@ pub extern "system" fn XMemVirtualAlloc(
     if watch_placement || constrained && kind & MEM_RESERVE_PLACEHOLDER == 0 {
         kind |= MEM_WRITE_WATCH;
     }
-    // SAFETY: the title's own arguments, cleaned of console bits; the
-    // parameter points at `requirements`, which outlives the call.
-    let mut allocate = |kind| unsafe {
-        VirtualAlloc2(
-            GetCurrentProcess(),
-            base,
-            size,
-            kind,
-            protect,
-            if constrained {
-                &mut parameter
-            } else {
-                std::ptr::null_mut()
-            },
-            constrained.into(),
-        )
+    let align = requirements.Alignment;
+    let mut allocate = |kind: u32| {
+        // At an address of our choice: found by our own walk of the window
+        // ([`reserve_first_fit`]), not by the system's search.
+        if constrained
+            && kind & MEM_TOP_DOWN_KIND == 0
+            && own_search()
+            && let Some(at) = reserve_first_fit(lowest, highest, size, align, kind, protect)
+        {
+            return at;
+        }
+        // SAFETY: the title's own arguments, cleaned of console bits; the
+        // parameter points at `requirements`, which outlives the call.
+        unsafe {
+            VirtualAlloc2(
+                GetCurrentProcess(),
+                base,
+                size,
+                kind,
+                protect,
+                if constrained {
+                    &mut parameter
+                } else {
+                    std::ptr::null_mut()
+                },
+                constrained.into(),
+            )
+        }
     };
     let mut at = if constrained && refuse_for_test(size) { std::ptr::null_mut() } else { allocate(kind) };
     if at.is_null() && constrained {
@@ -3885,6 +4009,34 @@ pub(crate) fn module() -> HleModule {
 mod tests {
     use super::*;
 
+    /// The first free region that holds the size from an aligned start, in
+    /// the window: taken regions and too-small gaps are passed over, the
+    /// start is aligned up, and nothing past the window's end is used.
+    #[test]
+    fn first_fit_takes_the_first_aligned_free_room_in_the_window() {
+        const K64: usize = 64 << 10;
+        const M2: usize = 2 << 20;
+        let regions = [
+            (0x1_0000_0000, 0x1000_0000, false), // taken
+            (0x1_1000_0000, 0x10_0000, true),    // 1 MiB free: too small
+            (0x1_1010_0000, 0x1000_0000, false), // taken
+            (0x1_2010_0000, 0x4000_0000, true),  // 1 GiB free, not 2 MiB aligned
+        ];
+        // 64 KiB alignment: the second free region, at its start.
+        assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x2000_0000, K64), Some(0x1_2010_0000));
+        // 2 MiB alignment: its start rounded up.
+        assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x2000_0000, M2), Some(0x1_2020_0000));
+        // The 1 MiB gap holds 512 KiB.
+        assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x8_0000, K64), Some(0x1_1000_0000));
+        // Bigger than any free region: nothing.
+        assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x8000_0000, K64), None);
+        // A window that ends inside the free region: only what fits before its end.
+        assert_eq!(first_fit(regions, 0x1_0000_0000, 0x1_2010_0000 + 0x2000_0000 - 1, 0x2000_0000, K64), Some(0x1_2010_0000));
+        assert_eq!(first_fit(regions, 0x1_0000_0000, 0x1_2010_0000 + 0x1000_0000 - 1, 0x2000_0000, K64), None);
+        // Searching on from further in (a retry): past the first place.
+        assert_eq!(first_fit(regions, 0x1_2010_0000 + K64, usize::MAX, 0x2000_0000, K64), Some(0x1_2011_0000));
+    }
+
     fn query(address: *const c_void) -> BasicInformation {
         // SAFETY: plain data; zero is a valid value.
         let mut info: BasicInformation = unsafe { std::mem::zeroed() };
diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs
index 71be273..de57e07 100644
--- a/crates/victory-hle/src/runtime.rs
+++ b/crates/victory-hle/src/runtime.rs
@@ -302,6 +302,9 @@ pub fn use_console_timers() {
         timeBeginPeriod(1);
     }
     ahead_of_other_programs();
+    keep_the_pc_responsive();
+    contain_the_run();
+    escape_key();
     victory_gpu::place_process();
 }
 
@@ -310,23 +313,326 @@ pub fn use_console_timers() {
 /// program that keeps the processors busy at normal priority (a build, a
 /// virus scan) starved it, loading took 40 to 60 s instead of 28 to 33, and
 /// the opening ran without the models that were to be there (runs cpu-1,
-/// play-1125-0203). The process runs above normal, as long as it runs.
-/// `VICTORY_PROCESS_PRIORITY=normal`: as it was started.
+/// play-1125-0203).
+///
+/// Left at normal by default: above normal, with the pipeline workers and
+/// the title's own threads busy, other programs could not start (Task
+/// Manager, a console, services timing out for 40 minutes, the PC restarted
+/// by its power button). `VICTORY_PROCESS_PRIORITY=above`: above normal, as
+/// before, for the loading times above.
 #[cfg(windows)]
 fn ahead_of_other_programs() {
     use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, SetPriorityClass};
-    if std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "normal" || v == "0") {
+    if !std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "above" || v == "1") {
+        tracing::info!("the process runs at normal priority (VICTORY_PROCESS_PRIORITY=above: above normal)");
         return;
     }
     // SAFETY: a plain process setting.
     let set = unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) } != 0;
-    tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=normal: not)");
+    tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=above)");
+}
+
+/// Seconds in a row with every processor busy before the process steps
+/// down, and with room again before it steps back.
+#[cfg(windows)]
+const BUSY_SECONDS: u32 = 8;
+#[cfg(windows)]
+const CALM_SECONDS: u32 = 30;
+
+/// Whether a second's processor time, `idle` of `total` (as
+/// `GetSystemTimes` counts them: kernel time includes idle), left the PC
+/// almost nothing: under 3 % idle.
+#[cfg(any(windows, test))]
+fn saturated(idle: u64, total: u64) -> bool {
+    total > 0 && idle.saturating_mul(100) < total.saturating_mul(3)
+}
+
+/// Whether it left room again: 15 % idle or more.
+#[cfg(any(windows, test))]
+fn calm(idle: u64, total: u64) -> bool {
+    total > 0 && idle.saturating_mul(100) >= total.saturating_mul(15)
+}
+
+/// Keeps the PC usable while the run takes every processor: after
+/// [`BUSY_SECONDS`] in a row with all of them busy the process runs below
+/// normal priority, so that other programs (the virus scanner every new
+/// program waits for, Task Manager, services) still get to run; after
+/// [`CALM_SECONDS`] with room again it goes back to the priority it had.
+/// Checked once a second by a thread that sleeps the rest of the time, at the
+/// top priority so it runs while the processors are taken.
+/// `VICTORY_SHARE_CPU=0`: not.
+#[cfg(windows)]
+fn keep_the_pc_responsive() {
+    use windows_sys::Win32::Foundation::FILETIME;
+    use windows_sys::Win32::System::Threading::{
+        BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess, GetCurrentThread, GetPriorityClass, GetSystemTimes,
+        SetPriorityClass, SetThreadPriority, THREAD_PRIORITY_TIME_CRITICAL,
+    };
+    if std::env::var_os("VICTORY_SHARE_CPU").is_some_and(|v| v == "0") {
+        tracing::info!("the processors are not shared out when all are busy (VICTORY_SHARE_CPU=0)");
+        return;
+    }
+    fn ticks(t: FILETIME) -> u64 {
+        (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime)
+    }
+    /// Idle time and all time (kernel, idle included, plus user) so far.
+    fn times() -> Option<(u64, u64)> {
+        let (mut idle, mut kernel, mut user) = (FILETIME::default(), FILETIME::default(), FILETIME::default());
+        // SAFETY: three FILETIMEs to fill, alive for the call.
+        let ok = unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } != 0;
+        ok.then(|| (ticks(idle), ticks(kernel) + ticks(user)))
+    }
+    let started = std::thread::Builder::new().name("victory-share-cpu".to_owned()).spawn(|| {
+        // SAFETY: a plain call on this thread.
+        unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) };
+        let Some(mut last) = times() else {
+            tracing::warn!("no processor times: the processors are not shared out when all are busy");
+            return;
+        };
+        let (mut busy, mut quiet) = (0u32, 0u32);
+        // The class to go back to while stepped down.
+        let mut stepped_from: Option<u32> = None;
+        loop {
+            std::thread::sleep(std::time::Duration::from_secs(1));
+            let Some(now) = times() else { return };
+            let (idle, total) = (now.0.saturating_sub(last.0), now.1.saturating_sub(last.1));
+            last = now;
+            busy = if saturated(idle, total) { busy + 1 } else { 0 };
+            quiet = if calm(idle, total) { quiet + 1 } else { 0 };
+            match stepped_from {
+                None if busy >= BUSY_SECONDS => {
+                    // SAFETY: a plain process query.
+                    let was = unsafe { GetPriorityClass(GetCurrentProcess()) };
+                    // SAFETY: a plain process setting.
+                    let set = unsafe { SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS) } != 0;
+                    tracing::warn!(
+                        set,
+                        "every processor busy for {BUSY_SECONDS} s: the process runs below normal priority until there is room again, so other programs can still start (VICTORY_SHARE_CPU=0: not)"
+                    );
+                    if set && was != 0 {
+                        stepped_from = Some(was);
+                    }
+                    quiet = 0;
+                }
+                Some(was) if quiet >= CALM_SECONDS => {
+                    // SAFETY: a plain process setting.
+                    let set = unsafe { SetPriorityClass(GetCurrentProcess(), was) } != 0;
+                    tracing::info!(set, "room on the processors again for {CALM_SECONDS} s: the process's own priority is back");
+                    stepped_from = None;
+                    busy = 0;
+                }
+                _ => {}
+            }
+        }
+    });
+    if let Err(error) = started {
+        tracing::warn!(%error, "no thread to share the processors out when all are busy");
+    }
+}
+
+/// `VICTORY_CPU_CAP_PERCENT` (off by default): the share of all the PC's
+/// processor time this process may take, held by Windows (a job object's hard
+/// cap), whatever its threads' priorities. Off unless asked: the first run
+/// with a 90 % cap froze the whole PC 3 s in (input, hot keys, a log written
+/// straight to disk, all stopped at once), at a point every run before it had
+/// passed; a throttled thread holding what the system waits for is the
+/// suspicion. `None` for unset, 0, 100 or more (no cap) or a value that is not
+/// a number. In the job object's units: 1/100 of a percent.
+#[cfg(any(windows, test))]
+fn cpu_rate(asked: Option<&str>) -> Option<u32> {
+    let percent = asked?.trim().parse::<u32>().ok()?;
+    (1..100).contains(&percent).then_some(percent * 100)
+}
+
+/// The most this process may commit: what the PC had free to commit at the
+/// start, less `headroom` (`VICTORY_COMMIT_HEADROOM_GB`, off by default: a
+/// run near the limit would end where it could have gone on) kept for other
+/// programs. `None` without a headroom (0), or when less than 4 GiB
+/// would be left to the run: a limit then would only end it at once.
+#[cfg(any(windows, test))]
+fn commit_cap(free: u64, headroom: u64) -> Option<u64> {
+    const LEAST: u64 = 4 << 30;
+    (headroom > 0).then(|| free.saturating_sub(headroom)).filter(|&cap| cap >= LEAST)
+}
+
+/// Puts this process in a job object of its own with the limits of
+/// [`cpu_rate`] and, when asked, [`commit_cap`], so that a run that takes
+/// every processor (or, with the limit, all of the memory Windows can
+/// commit) cannot take the PC with it: past the processor share its threads
+/// wait for the next interval, past the memory its next allocation fails
+/// (the run ends; the PC goes on).
+/// Programs it starts are not in the job (the F1 menu's restart starts the
+/// next run from here).
+#[cfg(windows)]
+fn contain_the_run() {
+    use windows_sys::Win32::System::JobObjects::{
+        AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_CPU_RATE_CONTROL_ENABLE,
+        JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP, JOB_OBJECT_LIMIT_PROCESS_MEMORY,
+        JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK, JOBOBJECT_CPU_RATE_CONTROL_INFORMATION,
+        JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectCpuRateControlInformation,
+        JobObjectExtendedLimitInformation, SetInformationJobObject,
+    };
+    use windows_sys::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION};
+    use windows_sys::Win32::System::Threading::GetCurrentProcess;
+    let rate = cpu_rate(std::env::var("VICTORY_CPU_CAP_PERCENT").ok().as_deref());
+    let headroom_gb = std::env::var("VICTORY_COMMIT_HEADROOM_GB")
+        .ok()
+        .and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(0);
+    let free = {
+        // SAFETY: zeroed is a valid PERFORMANCE_INFORMATION; filled by the call.
+        let mut info: PERFORMANCE_INFORMATION = unsafe { std::mem::zeroed() };
+        info.cb = size_of::<PERFORMANCE_INFORMATION>() as u32;
+        // SAFETY: `info` is ours, `cb` its size.
+        let ok = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0;
+        ok.then(|| (info.CommitLimit.saturating_sub(info.CommitTotal) as u64).saturating_mul(info.PageSize as u64))
+    };
+    let cap = free.and_then(|free| commit_cap(free, headroom_gb << 30));
+    if rate.is_none() && cap.is_none() {
+        tracing::info!("the run is not held to a processor share (VICTORY_CPU_CAP_PERCENT not set) or a memory limit (VICTORY_COMMIT_HEADROOM_GB not set)");
+        return;
+    }
+    // SAFETY: a new, unnamed job object; its handle is kept for the whole run (never closed).
+    let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
+    if job.is_null() {
+        tracing::warn!("no job object: the run is not held to a processor share or a memory limit");
+        return;
+    }
+    // SAFETY: zeroed is a valid JOBOBJECT_EXTENDED_LIMIT_INFORMATION (no limits).
+    let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
+    limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
+    if let Some(cap) = cap {
+        limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY;
+        limits.ProcessMemoryLimit = cap as usize;
+    }
+    // SAFETY: our job, and the structure the class names, alive for the call.
+    let limited = unsafe {
+        SetInformationJobObject(
+            job,
+            JobObjectExtendedLimitInformation,
+            (&raw const limits).cast(),
+            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
+        )
+    } != 0;
+    let mut capped = false;
+    if let Some(rate) = rate {
+        // SAFETY: zeroed is a valid JOBOBJECT_CPU_RATE_CONTROL_INFORMATION.
+        let mut control: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION = unsafe { std::mem::zeroed() };
+        control.ControlFlags = JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP;
+        control.Anonymous.CpuRate = rate;
+        // SAFETY: as above.
+        capped = unsafe {
+            SetInformationJobObject(
+                job,
+                JobObjectCpuRateControlInformation,
+                (&raw const control).cast(),
+                size_of::<JOBOBJECT_CPU_RATE_CONTROL_INFORMATION>() as u32,
+            )
+        } != 0;
+    }
+    // SAFETY: our job and our own process.
+    let assigned = unsafe { AssignProcessToJobObject(job, GetCurrentProcess()) } != 0;
+    tracing::info!(
+        assigned,
+        limited,
+        capped,
+        cpu_percent = rate.map(|r| r / 100),
+        commit_mb = cap.map(|c| c >> 20),
+        "the run is held to what VICTORY_CPU_CAP_PERCENT and VICTORY_COMMIT_HEADROOM_GB ask for, so the PC stays usable"
+    );
+}
+
+/// Ctrl+Alt+Shift+End ends this process at once, from a thread of its own
+/// that waits for nothing but the key: it needs neither the title's window
+/// nor a new program (Task Manager, a console), which a stuck PC may no
+/// longer start. A thread stuck in a driver can still hold the process until
+/// the driver lets go. `VICTORY_ESCAPE_KEY=0`: no key.
+#[cfg(windows)]
+fn escape_key() {
+    use windows_sys::Win32::System::Threading::{
+        GetCurrentProcess, GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_TIME_CRITICAL, TerminateProcess,
+    };
+    use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
+        MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, RegisterHotKey, VK_END,
+    };
+    use windows_sys::Win32::UI::WindowsAndMessaging::{GetMessageW, MSG, WM_HOTKEY};
+    if std::env::var_os("VICTORY_ESCAPE_KEY").is_some_and(|v| v == "0") {
+        return;
+    }
+    let started = std::thread::Builder::new().name("victory-escape-key".to_owned()).spawn(|| {
+        // SAFETY: a plain call on this thread.
+        unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) };
+        const ID: i32 = 0x5643; // any id of this thread's
+        // SAFETY: a hot key for this thread's own queue (no window).
+        let registered = unsafe {
+            RegisterHotKey(std::ptr::null_mut(), ID, MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT, u32::from(VK_END))
+        } != 0;
+        if !registered {
+            tracing::warn!("Ctrl+Alt+Shift+End is taken by another program: no key to end the game with");
+            return;
+        }
+        tracing::info!("Ctrl+Alt+Shift+End ends the game at once (VICTORY_ESCAPE_KEY=0: no key)");
+        // SAFETY: zeroed is a valid MSG; filled by each call.
+        let mut msg: MSG = unsafe { std::mem::zeroed() };
+        // SAFETY: this thread's queue; > 0 while there are messages.
+        while unsafe { GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) } > 0 {
+            if msg.message == WM_HOTKEY && msg.wParam == ID as usize {
+                eprintln!("VIctory: Ctrl+Alt+Shift+End: the game ends now");
+                // SAFETY: ends this process; nothing of it is waited for.
+                unsafe { TerminateProcess(GetCurrentProcess(), 1) };
+            }
+        }
+    });
+    if let Err(error) = started {
+        tracing::warn!(%error, "no thread for Ctrl+Alt+Shift+End: no key to end the game with");
+    }
 }
 
 #[cfg(test)]
 mod tests {
     use super::*;
 
+    /// The processor share: none unless asked, none for 0, 100 or more, or
+    /// for what is not a number.
+    #[test]
+    fn the_processor_share_is_asked_in_percent() {
+        assert_eq!(cpu_rate(None), None);
+        assert_eq!(cpu_rate(Some("90")), Some(9000));
+        assert_eq!(cpu_rate(Some(" 75 ")), Some(7500));
+        assert_eq!(cpu_rate(Some("0")), None);
+        assert_eq!(cpu_rate(Some("100")), None);
+        assert_eq!(cpu_rate(Some("half")), None);
+    }
+
+    /// The memory limit leaves the headroom free, and is not set at all
+    /// without a headroom or with too little left for the run.
+    #[test]
+    fn the_memory_limit_leaves_room_for_other_programs() {
+        const GB: u64 = 1 << 30;
+        assert_eq!(commit_cap(50 * GB, 6 * GB), Some(44 * GB));
+        assert_eq!(commit_cap(50 * GB, 0), None);
+        assert_eq!(commit_cap(9 * GB, 6 * GB), None);
+        assert_eq!(commit_cap(2 * GB, 6 * GB), None);
+    }
+
+    /// A second with every processor busy, one with a little room, and one
+    /// with plenty: only the first counts toward stepping down, only the
+    /// last toward stepping back.
+    #[test]
+    fn busy_and_calm_seconds_are_told_apart() {
+        // 16 processors for a second: 160,000,000 ticks of 100 ns.
+        let total = 160_000_000;
+        assert!(saturated(total / 100, total));
+        assert!(!calm(total / 100, total));
+        assert!(!saturated(total / 10, total));
+        assert!(!calm(total / 10, total));
+        assert!(!saturated(total / 4, total));
+        assert!(calm(total / 4, total));
+        // No time passed (a clock that did not move): neither.
+        assert!(!saturated(0, 0));
+        assert!(!calm(0, 0));
+    }
+
     #[test]
     fn a_quoted_angle_bracket_does_not_end_its_tag() {
         let text = "<Game><ShellVisuals DefaultDisplayName=\"A > B\" Description='x>y'/>\
diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs
index d2f03b4..87b1a01 100644
--- a/crates/victory-loader/src/crash.rs
+++ b/crates/victory-loader/src/crash.rs
@@ -120,11 +120,51 @@ fn title_output() -> String {
     said.iter().map(|l| format!("  title said: {l}\n")).collect()
 }
 
+/// Whether a crash, once reported, is left to Windows Error Reporting
+/// (`VICTORY_ERROR_REPORTING=1`), read when the handlers are installed so
+/// that the crash itself reads no environment.
+static TO_WINDOWS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+/// Ends the process an unhandled exception is about to end, at once, with
+/// the exception's code, once [`report_unhandled`] has logged it. Left to
+/// Windows, the crash waits for Windows Error Reporting, which starts a
+/// program of its own (WerFault): on a PC that can no longer start one (a
+/// stuck run's services timed out for 40 minutes, the Error Reporting
+/// service among them) the crashed process stood there instead of ending.
+/// The title's 30 s watchdog ends a stopped frame loop this way.
+/// `VICTORY_ERROR_REPORTING=1`: left to Windows (its dialog and dumps), as
+/// before.
+///
+/// # Safety
+///
+/// `info` is null or the exception pointers passed to an unhandled-exception
+/// filter.
+pub unsafe fn end_unhandled(info: *const EXCEPTION_POINTERS) {
+    use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
+    if TO_WINDOWS.load(std::sync::atomic::Ordering::Relaxed) {
+        return;
+    }
+    let code = if info.is_null() {
+        1
+    } else {
+        // SAFETY: the caller passes the filter's exception pointers.
+        unsafe { (*(*info).ExceptionRecord).ExceptionCode as u32 }
+    };
+    // SAFETY: ends this process; nothing of it is waited for.
+    unsafe { TerminateProcess(GetCurrentProcess(), code) };
+}
+
 /// Installs the handlers; call once before running title code.
 pub fn report_crashes() {
+    TO_WINDOWS.store(
+        std::env::var_os("VICTORY_ERROR_REPORTING").is_some_and(|v| v == "1"),
+        std::sync::atomic::Ordering::Relaxed,
+    );
     unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 {
         // SAFETY: the system passes the exception being dispatched.
         unsafe { report_unhandled(info) };
+        // SAFETY: as above.
+        unsafe { end_unhandled(info) };
         EXCEPTION_CONTINUE_SEARCH
     }
     // SAFETY: registers handlers that only read the exception they are
diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs
index 1f301af..2253bb4 100644
--- a/crates/victory-loader/src/lib.rs
+++ b/crates/victory-loader/src/lib.rs
@@ -54,7 +54,8 @@ mod windows;
 
 #[cfg(windows)]
 pub use crash::{
-    locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled,
+    end_unhandled, locate, log_crash, log_crashes_to, note_title_output, report_crashes,
+    report_unhandled,
 };
 #[cfg(all(windows, feature = "diagnostics"))]
 pub use crash::save_on_crash;
diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1
index 11a45ee..9f75fd9 100644
--- a/scripts/play-foxhound.ps1
+++ b/scripts/play-foxhound.ps1
@@ -70,7 +70,11 @@ param(
     # cannot be written — Steam's launch options hand every argument over as it was typed, and
     # anything else starting this with -File does too, and no parameter can be given twice —
     # `NAME=VALUE`, several of them comma-separated in one `-More`; `NAME=` unsets a switch.
-    [object[]]$More = @()
+    [object[]]$More = @(),
+    # A victory.exe left behind by an earlier run is not ended before the start (see Stop-VictoryLeftovers).
+    [switch]$KeepLeftovers,
+    # The game is ended when its window has not answered for this many seconds (Start-HangWatch); 0: never.
+    [ValidateRange(0, 86400)][int]$HangSeconds = 120
 )
 $repo = Split-Path $PSScriptRoot -Parent
 . (Join-Path $PSScriptRoot 'preload-window.ps1')
@@ -113,8 +117,13 @@ if ($menu['VICTORY_MENU_FPS'] -match '^\d+$' -and [int]$menu['VICTORY_MENU_FPS']
 # Pipeline workers raise shader-build throughput but also increase the startup memory peak.
 # Use fewer on 16 GiB hosts; `-More` can still override this for a specific run.
 $physicalRam = (Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction SilentlyContinue).TotalPhysicalMemory
-$pipelineWorkers = '8'
-if ($physicalRam) { $pipelineWorkers = if ($physicalRam -le 16GB) { '4' } else { '12' } }
+# Also never more than a quarter of the logical processors (2 to 6): 12 on a 64 GB PC, with the title's own
+# threads beside them, left nothing for other programs; Task Manager, a console and services could not start.
+# A preload (-Preload) makes the pipelines ahead, so few are left to make while playing.
+$logical = [Environment]::ProcessorCount
+$byCores = [Math]::Max(2, [Math]::Min(6, [int][Math]::Floor($logical / 4)))
+$pipelineWorkers = "$byCores"
+if ($physicalRam -and $physicalRam -le 16GB) { $pipelineWorkers = "$([Math]::Min(4, $byCores))" }
 $settings = @{
     # Submission and copy machinery
     # Left off: VICTORY_RELAY=2, as fast as off on an RTX 5070 Ti (26.9 against 27.4 fps, the first cutscene's diner
@@ -369,6 +378,74 @@ $paths = 'VICTORY_MENU_PAD', 'VICTORY_HOME', 'VICTORY_ADAPTER', 'VICTORY_CONFIG'
 Get-ChildItem Env:VICTORY_* -ErrorAction SilentlyContinue | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" }
 foreach ($k in $settings.Keys) { Set-Item "Env:$k" $settings[$k] }
 
+# Cleanup before the start: a victory.exe left behind by an earlier run is ended. The F1 menu's SAVE AND RESTART
+# can leave the old game without a window, and a closed preload can leave its pipeline workers (`victory warm`);
+# either holds its memory and its processors. Only those started over a minute ago: a game that is still opening
+# its window is left alone. A game with a window, or a preload or warm run whose parent still runs, is listed
+# but left alone too. -KeepLeftovers: none ended.
+function Stop-VictoryLeftovers {
+    $all = @(Get-CimInstance Win32_Process -Filter "Name='victory.exe'" -ErrorAction SilentlyContinue)
+    if (-not $all.Count) { return }
+    $alive = @{}; foreach ($p in Get-Process -ErrorAction SilentlyContinue) { $alive[[int]$p.Id] = $p }
+    foreach ($w in $all) {
+        $proc = $alive[[int]$w.ProcessId]
+        if (-not $proc) { continue }
+        $cmd = [string]$w.CommandLine
+        $kind = if ($cmd -match '\spreload(\s|$)') { 'preload' } elseif ($cmd -match '\swarm(\s|$)') { 'warm' } elseif ($cmd -match '\s(play|run)(\s|$)') { 'game' } else { 'other' }
+        $window = $proc.MainWindowHandle -ne [IntPtr]::Zero
+        # A parent id can be reused after the parent ended: it only counts if that process started before this one.
+        $parent = $alive[[int]$w.ParentProcessId]
+        $parentAlive = $false
+        if ($parent) { try { $parentAlive = $parent.StartTime -le $proc.StartTime } catch { $parentAlive = $true } }
+        $age = try { ((Get-Date) - $proc.StartTime).TotalSeconds } catch { 0 }
+        $left = switch ($kind) { 'game' { -not $window } { $_ -in 'preload', 'warm' } { -not $parentAlive } default { $false } }
+        $mb = [Math]::Round($proc.PrivateMemorySize64 / 1MB)
+        if ($left -and $age -ge 60 -and -not $KeepLeftovers) {
+            Write-Host ("Ending a victory.exe left behind: pid {0}, {1}, {2:N0} MB committed" -f $w.ProcessId, $kind, $mb)
+            # Not /T: after the F1 menu's restart this launcher is itself a child of the old game.
+            & taskkill.exe /PID $w.ProcessId /F 2>&1 | Out-Null
+        } else {
+            Write-Host ("victory.exe already running, left alone: pid {0}, {1}, {2:N0} MB committed{3}" -f $w.ProcessId, $kind, $mb, $(if ($window) { ', with a window' } else { '' }))
+        }
+    }
+}
+Stop-VictoryLeftovers
+
+# Hang watch: the game started from here is ended when its window has not answered Windows for -HangSeconds
+# in a row. It runs on a thread of this window's own process, started before the game: when the PC is stuck it
+# needs no new program (Task Manager, taskkill and consoles were what could not start), and it ends the game
+# through .NET, not taskkill. A window still being made, or none (a preload's workers), is never counted. A
+# thread stuck in a driver can still hold the process until the driver lets go. Ctrl+Alt+Shift+End in the game
+# does the same at once.
+function Start-HangWatch([datetime]$since, [int]$seconds) {
+    if ($seconds -le 0) { return $null }
+    $ps = [powershell]::Create()
+    $null = $ps.AddScript({
+        param($since, $seconds)
+        [Threading.Thread]::CurrentThread.Priority = [Threading.ThreadPriority]::Highest
+        $first = @{}   # pid -> when its window was first seen not answering
+        while ($true) {
+            Start-Sleep -Seconds 5
+            foreach ($g in [Diagnostics.Process]::GetProcessesByName('victory')) {
+                try { if ($g.StartTime -lt $since) { continue } } catch { continue }
+                $g.Refresh()
+                # Responding asks the main window (a few seconds at most); a process without one answers yes.
+                if ($g.MainWindowHandle -eq [IntPtr]::Zero -or $g.Responding) { $first.Remove($g.Id); continue }
+                if (-not $first.ContainsKey($g.Id)) { $first[$g.Id] = [DateTime]::UtcNow; continue }
+                $stuck = ([DateTime]::UtcNow - $first[$g.Id]).TotalSeconds
+                if ($stuck -ge $seconds) {
+                    [Console]::WriteLine(("Hang watch: the game's window has not answered for {0:N0} s: ending victory.exe (pid {1}). -HangSeconds 0: never." -f $stuck, $g.Id))
+                    try { $g.Kill() } catch { [Console]::WriteLine("Hang watch: it could not be ended: $_") }
+                    $first.Remove($g.Id)
+                }
+            }
+        }
+    }).AddArgument($since).AddArgument($seconds)
+    $null = $ps.BeginInvoke()
+    return $ps
+}
+$hangWatch = $null
+
 $logs = Join-Path $homeDir 'logs'; New-Item -ItemType Directory -Force $logs | Out-Null
 $log = Join-Path $logs ('victory-nvidia-{0:yyyyMMdd-HHmmss}.log' -f (Get-Date))
 $writer = [IO.StreamWriter]::new($log, $false, [Text.UTF8Encoding]::new($false)); $writer.AutoFlush = $true
@@ -412,11 +489,16 @@ try {
     $psi = [Diagnostics.ProcessStartInfo]::new('cmd.exe', ('/d /s /c ""%VFG_BIN%" run "%VFG_EXE%" --console {0} --execute 2>&1"' -f $console))
     $psi.UseShellExecute = $false; $psi.CreateNoWindow = $true; $psi.RedirectStandardOutput = $true
     $psi.StandardOutputEncoding = [Text.UTF8Encoding]::new($false); $psi.WorkingDirectory = $repo
+    $hangWatch = Start-HangWatch (Get-Date) $HangSeconds
+    if ($hangWatch) { Write-Host "Hang watch: the game is ended if its window stops answering for $HangSeconds s; the game's own watchdog ends a frame loop stopped for 30 s (Ctrl+Alt+Shift+End: at once)." }
     $p = [Diagnostics.Process]::Start($psi)
     while ($null -ne ($line = $p.StandardOutput.ReadLine())) { $writer.WriteLine($line); $line }
     $p.WaitForExit()
     $global:LASTEXITCODE = $p.ExitCode
 }
-finally { Pop-Location; $writer.Dispose(); Close-PreloadWindow $preloadWindow }
+finally {
+    if ($hangWatch) { try { $hangWatch.Stop(); $hangWatch.Dispose() } catch {} }
+    Pop-Location; $writer.Dispose(); Close-PreloadWindow $preloadWindow
+}
 # What `victory run` returned: a title that failed is a failed start for whoever called this script.
 exit $LASTEXITCODE
**@⁠victorious-gh** on GitHub · 2026-11-30 06:19 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7270538253) The following is the patch provided by claude: ```diff diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index f1912a7..5fb0b2a 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -979,14 +979,23 @@ fn timers(base: usize, size: usize) { /// with its frames stopped first. Bit 0 of the byte at `+0x71b6340` is the watchdog's quit flag: /// set, its thread leaves before it counts (found in trustno1-coder/VIctory-NVIDIA#1428). Set here /// only for the image this was read from: the trap must be where it was found. Set again every -/// half second, as the title may clear it while it starts. `VICTORY_TITLE_WATCHDOG=1`: the -/// title's watchdog is left alone. +/// half second, as the title may clear it while it starts. +/// +/// Left alone by default, as the escape from a stuck run: a frame loop stopped for 30 s ends the +/// game (and with `victory_loader::end_unhandled` the process ends at once, without waiting for +/// Windows Error Reporting) instead of a white window holding the PC. A first run of a new build +/// can stop that long while its pipelines are made: `--preload` once makes them ahead. +/// `VICTORY_TITLE_WATCHDOG=0`: told to quit, as before. #[cfg(windows)] fn quiet_title_watchdog(base: usize, size: usize) { const TRAP: usize = 0x23cf683; const TRAP_BYTES: [u8; 11] = [0xc7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x21, 0xd4, 0x8b, 0x4d]; const QUIT: usize = 0x71b6340; - if std::env::var_os("VICTORY_TITLE_WATCHDOG").is_some_and(|v| v == "1") { + if !std::env::var_os("VICTORY_TITLE_WATCHDOG").is_some_and(|v| v == "0") { + eprintln!( + "VIctory: the title's 30 s watchdog is on: a frame loop stopped for 30 s ends the game \ + (VICTORY_TITLE_WATCHDOG=0: off)" + ); return; } if TRAP + TRAP_BYTES.len() > size || QUIT >= size { @@ -1000,7 +1009,7 @@ fn quiet_title_watchdog(base: usize, size: usize) { } eprintln!( "VIctory: the title's 30 s watchdog is told to quit, so a long stall is not ended as a crash at +0x23cf683 \ - (VICTORY_TITLE_WATCHDOG=1: left alone)" + (VICTORY_TITLE_WATCHDOG=0)" ); let flag = base + QUIT; let started = std::thread::Builder::new().name("victory-watchdog-off".to_owned()).spawn(move || { diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index b645ab7..bf128fc 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -32,6 +32,7 @@ windows-sys = { workspace = true, features = [ "Win32_System_Diagnostics_Debug", "Win32_System_IO", "Win32_System_Ioctl", + "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Power", diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index efe32e2..0a5d3b5 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -409,7 +409,7 @@ pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize { extern "system" fn report_unhandled(info: *const c_void) -> i32 { host::report_unhandled(info); - match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { + let answer = match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { 0 => 0, // EXCEPTION_CONTINUE_SEARCH filter => { type Filter = extern "system" fn(*const c_void) -> i32; @@ -417,7 +417,13 @@ extern "system" fn report_unhandled(info: *const c_void) -> i32 { let filter: Filter = unsafe { std::mem::transmute(filter) }; filter(info) } + }; + // Left to the system, the crash would wait for Windows Error Reporting: + // ended here instead (`victory_loader::end_unhandled`). + if answer == 0 { + host::end_unhandled(info); } + answer } /// See [`exit`]; only the current process is logged. @@ -760,11 +766,14 @@ pub extern "system" fn GetCommandLineW() -> *const u16 { /// `VICTORY_STARTUP_PRIORITIES=<seconds>` (off by default) raises them for /// the first seconds of the run only, while the title loads beside the /// pipeline library's loads, and gives them back what they asked for after -/// (with `VICTORY_TITLE_PRIORITIES=0`; without it they stay raised). It -/// also holds every title thread at normal at most, for the whole run: the -/// process runs above normal, and a title thread at "highest" or "time -/// critical" would be level with or above the normal threads of another program -/// in the high class that must not wait for us. +/// (with `VICTORY_TITLE_PRIORITIES=0`; without it they stay raised). +/// +/// Every title thread is also held at normal at most, for the whole run (by +/// default; `VICTORY_TITLE_PRIORITY_CAP=0`: as asked, as before): on the +/// console those threads have cores of their own, here a title thread at +/// "highest" or "time critical" is level with or above the threads of every +/// other program, Task Manager's and the virus scanner's among them, and with +/// it busy they could not start. fn title_priority(asked: i32, raise: bool, cap: bool) -> i32 { const IDLE: i32 = -15; const LOWEST: i32 = -2; @@ -779,18 +788,27 @@ fn title_priority(asked: i32, raise: bool, cap: bool) -> i32 { } /// Whether idle and lowest asks are raised, and asks above normal held at -/// normal, `elapsed` into the run: see [`title_priority`]. +/// normal, `elapsed` into the run: see [`title_priority`]. `cap` holds them +/// at normal without the startup switch too. fn priority_rules( as_set: bool, startup: Option<std::time::Duration>, elapsed: std::time::Duration, + cap: bool, ) -> (bool, bool) { match startup { - None => (!as_set, false), + None => (!as_set, cap), Some(window) => (!as_set || elapsed < window, true), } } +/// `VICTORY_TITLE_PRIORITY_CAP`: title threads held at normal at most, on +/// unless it is `0`. +fn priority_cap() -> bool { + static CAP: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *CAP.get_or_init(|| !std::env::var_os("VICTORY_TITLE_PRIORITY_CAP").is_some_and(|v| v == "0")) +} + /// `VICTORY_STARTUP_PRIORITIES`, in seconds. fn startup_window() -> Option<std::time::Duration> { static WINDOW: std::sync::OnceLock<Option<std::time::Duration>> = std::sync::OnceLock::new(); @@ -884,7 +902,7 @@ pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) -> let as_set = *AS_SET .get_or_init(|| std::env::var_os("VICTORY_TITLE_PRIORITIES").is_some_and(|v| v == "0")); let startup = startup_window(); - let (mut raise, cap) = priority_rules(as_set, startup, run_time()); + let (mut raise, cap) = priority_rules(as_set, startup, run_time(), priority_cap()); if raise && as_set && title_priority(priority, true, cap) != title_priority(priority, false, cap) @@ -1289,6 +1307,11 @@ mod host { unsafe { victory_loader::report_unhandled(info.cast()) }; } + pub(super) fn end_unhandled(info: *const c_void) { + // SAFETY: as above. + unsafe { victory_loader::end_unhandled(info.cast()) }; + } + pub(super) fn note_title_output(line: &str) { victory_loader::note_title_output(line); } @@ -1415,6 +1438,8 @@ mod host { pub(super) fn report_unhandled(_: *const c_void) {} + pub(super) fn end_unhandled(_: *const c_void) {} + pub(super) fn note_title_output(_: &str) {} /// UTF-8, up to the first NUL. @@ -1513,21 +1538,27 @@ mod tests { use std::time::Duration; let asks = [-15, -2, 0, 2, 15]; let window = Some(Duration::from_secs(220)); - let given = |as_set, startup, elapsed: u64| -> Vec<i32> { - let (raise, cap) = priority_rules(as_set, startup, Duration::from_secs(elapsed)); + let given_with = |as_set, startup, elapsed: u64, cap_on: bool| -> Vec<i32> { + let (raise, cap) = priority_rules(as_set, startup, Duration::from_secs(elapsed), cap_on); asks.iter() .map(|&p| title_priority(p, raise, cap)) .collect() }; - // Neither switch: raised, the rest as asked. - assert_eq!(given(false, None, 10), [-1, -1, 0, 2, 15]); - // VICTORY_TITLE_PRIORITIES=0: as asked. - assert_eq!(given(true, None, 10), [-15, -2, 0, 2, 15]); - // With the startup switch, during its seconds and after. + let given = |as_set, startup, elapsed| given_with(as_set, startup, elapsed, true); + // Neither switch: raised, and nothing above normal. + assert_eq!(given(false, None, 10), [-1, -1, 0, 0, 0]); + // VICTORY_TITLE_PRIORITIES=0: as asked, but nothing above normal. + assert_eq!(given(true, None, 10), [-15, -2, 0, 0, 0]); + // VICTORY_TITLE_PRIORITY_CAP=0: above normal as asked, as before. + assert_eq!(given_with(false, None, 10, false), [-1, -1, 0, 2, 15]); + assert_eq!(given_with(true, None, 10, false), [-15, -2, 0, 2, 15]); + // With the startup switch, during its seconds and after (held at + // normal whatever VICTORY_TITLE_PRIORITY_CAP says). assert_eq!(given(true, window, 10), [-1, -1, 0, 0, 0]); assert_eq!(given(true, window, 300), [-15, -2, 0, 0, 0]); assert_eq!(given(false, window, 10), [-1, -1, 0, 0, 0]); assert_eq!(given(false, window, 300), [-1, -1, 0, 0, 0]); + assert_eq!(given_with(false, window, 300, false), [-1, -1, 0, 0, 0]); } #[test] diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 4acd5c5..ee78e78 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -232,6 +232,118 @@ fn largest_free_gap(lowest: usize, highest: usize) -> (usize, usize) { (best, runs) } +/// `MEM_TOP_DOWN`: a reservation the title wants from the top of its +/// window, left to the system's search. +const MEM_TOP_DOWN_KIND: u32 = 0x10_0000; + +/// Whether the title's reservations in its window (`MEM_ADDRESS_REQUIREMENTS`) +/// are placed at an address our own walk of the window found +/// ([`reserve_first_fit`]), not by the system's search +/// (`VICTORY_XMEM_OWN_SEARCH=0`: the system's, as before). The system's +/// search for the title's 3.9 GB placeholder ran 27 s in the kernel +/// (`nt!RtlFindClearBitsEx` under `MiFindEmptyAddressRange`) holding the +/// process's address-space lock, on a second run whose pipelines started +/// early beside it: the graphics kernel's memory manager, waiting for that +/// lock under its own, stopped every program's GPU allocations behind it, +/// the PC with it (a kernel dump, 2026-11-29). A walk of the regions +/// (`VirtualQueryEx`, a few hundred) takes no lock that long. +fn own_search() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = !std::env::var_os("VICTORY_XMEM_OWN_SEARCH").is_some_and(|v| v == "0"); + tracing::info!( + on, + "the title's reservations in its window are placed by our own walk of the window, not the system's search (VICTORY_XMEM_OWN_SEARCH=0: the system's)" + ); + on + }) +} + +/// The first address from `from` at which `size` bytes, `align`ed (64 KiB at +/// least, the allocation granularity), fit inside one free region of +/// `regions` (start, length, free; in address order) and end by `highest` +/// (the window's last address, inclusive). +fn first_fit( + regions: impl IntoIterator<Item = (usize, usize, bool)>, + from: usize, + highest: usize, + size: usize, + align: usize, +) -> Option<usize> { + let align = align.max(64 << 10).next_power_of_two(); + let limit = highest.saturating_add(1); + for (start, len, free) in regions { + if !free { + continue; + } + let end = start.saturating_add(len).min(limit); + let Some(at) = start.max(from).checked_add(align - 1).map(|a| a & !(align - 1)) else { + continue; + }; + if at < end && end - at >= size { + return Some(at); + } + } + None +} + +/// The regions of this process's addresses from `from` to `highest`: start, +/// length and whether free, in address order. +fn regions(from: usize, highest: usize) -> Vec<(usize, usize, bool)> { + const MEM_FREE: u32 = 0x1_0000; + let mut found = Vec::new(); + let mut at = from; + while at <= highest { + // SAFETY: plain data, filled by the call. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is an out-parameter of the right size. + let n = unsafe { + VirtualQueryEx(GetCurrentProcess(), at as *const c_void, &mut info, size_of::<MEMORY_BASIC_INFORMATION>()) + }; + if n == 0 || info.RegionSize == 0 { + break; + } + let start = info.BaseAddress as usize; + found.push((start, info.RegionSize, info.State == MEM_FREE)); + at = start.saturating_add(info.RegionSize); + if at <= start { + break; + } + } + found +} + +/// Reserves (or reserves and commits, as `kind` says) `size` bytes in +/// [`lowest`, `highest`] at the first place [`first_fit`] finds there, the +/// address given to the system so that it searches nothing. Tried a few +/// times, further on each time, as another thread may take a place between +/// the walk and the call; `None` when nothing fits or every try was +/// refused (the system's own search is tried then). +fn reserve_first_fit( + lowest: usize, + highest: usize, + size: usize, + align: usize, + kind: u32, + protect: u32, +) -> Option<*mut c_void> { + let step = align.max(64 << 10).next_power_of_two(); + let mut from = lowest; + for _ in 0..4 { + let at = first_fit(regions(from, highest), from, highest, size, align)?; + // SAFETY: a free range of our own addresses, as the walk just found + // it; the system refuses it if it is taken by now. + let got = unsafe { + VirtualAlloc2(GetCurrentProcess(), at as *const c_void, size, kind, protect, std::ptr::null_mut(), 0) + }; + if !got.is_null() { + return Some(got); + } + from = at.saturating_add(step); + } + None +} + /// For tests: `VICTORY_TEST_REFUSE_MB=<n>` acts as if Windows refused the /// title's first reservation of `n` MiB (rounded down) at an address of our /// choice: 6236 for its 6.5 GB heap. @@ -331,22 +443,34 @@ pub extern "system" fn XMemVirtualAlloc( if watch_placement || constrained && kind & MEM_RESERVE_PLACEHOLDER == 0 { kind |= MEM_WRITE_WATCH; } - // SAFETY: the title's own arguments, cleaned of console bits; the - // parameter points at `requirements`, which outlives the call. - let mut allocate = |kind| unsafe { - VirtualAlloc2( - GetCurrentProcess(), - base, - size, - kind, - protect, - if constrained { - &mut parameter - } else { - std::ptr::null_mut() - }, - constrained.into(), - ) + let align = requirements.Alignment; + let mut allocate = |kind: u32| { + // At an address of our choice: found by our own walk of the window + // ([`reserve_first_fit`]), not by the system's search. + if constrained + && kind & MEM_TOP_DOWN_KIND == 0 + && own_search() + && let Some(at) = reserve_first_fit(lowest, highest, size, align, kind, protect) + { + return at; + } + // SAFETY: the title's own arguments, cleaned of console bits; the + // parameter points at `requirements`, which outlives the call. + unsafe { + VirtualAlloc2( + GetCurrentProcess(), + base, + size, + kind, + protect, + if constrained { + &mut parameter + } else { + std::ptr::null_mut() + }, + constrained.into(), + ) + } }; let mut at = if constrained && refuse_for_test(size) { std::ptr::null_mut() } else { allocate(kind) }; if at.is_null() && constrained { @@ -3885,6 +4009,34 @@ pub(crate) fn module() -> HleModule { mod tests { use super::*; + /// The first free region that holds the size from an aligned start, in + /// the window: taken regions and too-small gaps are passed over, the + /// start is aligned up, and nothing past the window's end is used. + #[test] + fn first_fit_takes_the_first_aligned_free_room_in_the_window() { + const K64: usize = 64 << 10; + const M2: usize = 2 << 20; + let regions = [ + (0x1_0000_0000, 0x1000_0000, false), // taken + (0x1_1000_0000, 0x10_0000, true), // 1 MiB free: too small + (0x1_1010_0000, 0x1000_0000, false), // taken + (0x1_2010_0000, 0x4000_0000, true), // 1 GiB free, not 2 MiB aligned + ]; + // 64 KiB alignment: the second free region, at its start. + assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x2000_0000, K64), Some(0x1_2010_0000)); + // 2 MiB alignment: its start rounded up. + assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x2000_0000, M2), Some(0x1_2020_0000)); + // The 1 MiB gap holds 512 KiB. + assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x8_0000, K64), Some(0x1_1000_0000)); + // Bigger than any free region: nothing. + assert_eq!(first_fit(regions, 0x1_0000_0000, usize::MAX, 0x8000_0000, K64), None); + // A window that ends inside the free region: only what fits before its end. + assert_eq!(first_fit(regions, 0x1_0000_0000, 0x1_2010_0000 + 0x2000_0000 - 1, 0x2000_0000, K64), Some(0x1_2010_0000)); + assert_eq!(first_fit(regions, 0x1_0000_0000, 0x1_2010_0000 + 0x1000_0000 - 1, 0x2000_0000, K64), None); + // Searching on from further in (a retry): past the first place. + assert_eq!(first_fit(regions, 0x1_2010_0000 + K64, usize::MAX, 0x2000_0000, K64), Some(0x1_2011_0000)); + } + fn query(address: *const c_void) -> BasicInformation { // SAFETY: plain data; zero is a valid value. let mut info: BasicInformation = unsafe { std::mem::zeroed() }; diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index 71be273..de57e07 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -302,6 +302,9 @@ pub fn use_console_timers() { timeBeginPeriod(1); } ahead_of_other_programs(); + keep_the_pc_responsive(); + contain_the_run(); + escape_key(); victory_gpu::place_process(); } @@ -310,23 +313,326 @@ pub fn use_console_timers() { /// program that keeps the processors busy at normal priority (a build, a /// virus scan) starved it, loading took 40 to 60 s instead of 28 to 33, and /// the opening ran without the models that were to be there (runs cpu-1, -/// play-1125-0203). The process runs above normal, as long as it runs. -/// `VICTORY_PROCESS_PRIORITY=normal`: as it was started. +/// play-1125-0203). +/// +/// Left at normal by default: above normal, with the pipeline workers and +/// the title's own threads busy, other programs could not start (Task +/// Manager, a console, services timing out for 40 minutes, the PC restarted +/// by its power button). `VICTORY_PROCESS_PRIORITY=above`: above normal, as +/// before, for the loading times above. #[cfg(windows)] fn ahead_of_other_programs() { use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, SetPriorityClass}; - if std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "normal" || v == "0") { + if !std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "above" || v == "1") { + tracing::info!("the process runs at normal priority (VICTORY_PROCESS_PRIORITY=above: above normal)"); return; } // SAFETY: a plain process setting. let set = unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) } != 0; - tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=normal: not)"); + tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=above)"); +} + +/// Seconds in a row with every processor busy before the process steps +/// down, and with room again before it steps back. +#[cfg(windows)] +const BUSY_SECONDS: u32 = 8; +#[cfg(windows)] +const CALM_SECONDS: u32 = 30; + +/// Whether a second's processor time, `idle` of `total` (as +/// `GetSystemTimes` counts them: kernel time includes idle), left the PC +/// almost nothing: under 3 % idle. +#[cfg(any(windows, test))] +fn saturated(idle: u64, total: u64) -> bool { + total > 0 && idle.saturating_mul(100) < total.saturating_mul(3) +} + +/// Whether it left room again: 15 % idle or more. +#[cfg(any(windows, test))] +fn calm(idle: u64, total: u64) -> bool { + total > 0 && idle.saturating_mul(100) >= total.saturating_mul(15) +} + +/// Keeps the PC usable while the run takes every processor: after +/// [`BUSY_SECONDS`] in a row with all of them busy the process runs below +/// normal priority, so that other programs (the virus scanner every new +/// program waits for, Task Manager, services) still get to run; after +/// [`CALM_SECONDS`] with room again it goes back to the priority it had. +/// Checked once a second by a thread that sleeps the rest of the time, at the +/// top priority so it runs while the processors are taken. +/// `VICTORY_SHARE_CPU=0`: not. +#[cfg(windows)] +fn keep_the_pc_responsive() { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{ + BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess, GetCurrentThread, GetPriorityClass, GetSystemTimes, + SetPriorityClass, SetThreadPriority, THREAD_PRIORITY_TIME_CRITICAL, + }; + if std::env::var_os("VICTORY_SHARE_CPU").is_some_and(|v| v == "0") { + tracing::info!("the processors are not shared out when all are busy (VICTORY_SHARE_CPU=0)"); + return; + } + fn ticks(t: FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime) + } + /// Idle time and all time (kernel, idle included, plus user) so far. + fn times() -> Option<(u64, u64)> { + let (mut idle, mut kernel, mut user) = (FILETIME::default(), FILETIME::default(), FILETIME::default()); + // SAFETY: three FILETIMEs to fill, alive for the call. + let ok = unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } != 0; + ok.then(|| (ticks(idle), ticks(kernel) + ticks(user))) + } + let started = std::thread::Builder::new().name("victory-share-cpu".to_owned()).spawn(|| { + // SAFETY: a plain call on this thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let Some(mut last) = times() else { + tracing::warn!("no processor times: the processors are not shared out when all are busy"); + return; + }; + let (mut busy, mut quiet) = (0u32, 0u32); + // The class to go back to while stepped down. + let mut stepped_from: Option<u32> = None; + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + let Some(now) = times() else { return }; + let (idle, total) = (now.0.saturating_sub(last.0), now.1.saturating_sub(last.1)); + last = now; + busy = if saturated(idle, total) { busy + 1 } else { 0 }; + quiet = if calm(idle, total) { quiet + 1 } else { 0 }; + match stepped_from { + None if busy >= BUSY_SECONDS => { + // SAFETY: a plain process query. + let was = unsafe { GetPriorityClass(GetCurrentProcess()) }; + // SAFETY: a plain process setting. + let set = unsafe { SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS) } != 0; + tracing::warn!( + set, + "every processor busy for {BUSY_SECONDS} s: the process runs below normal priority until there is room again, so other programs can still start (VICTORY_SHARE_CPU=0: not)" + ); + if set && was != 0 { + stepped_from = Some(was); + } + quiet = 0; + } + Some(was) if quiet >= CALM_SECONDS => { + // SAFETY: a plain process setting. + let set = unsafe { SetPriorityClass(GetCurrentProcess(), was) } != 0; + tracing::info!(set, "room on the processors again for {CALM_SECONDS} s: the process's own priority is back"); + stepped_from = None; + busy = 0; + } + _ => {} + } + } + }); + if let Err(error) = started { + tracing::warn!(%error, "no thread to share the processors out when all are busy"); + } +} + +/// `VICTORY_CPU_CAP_PERCENT` (off by default): the share of all the PC's +/// processor time this process may take, held by Windows (a job object's hard +/// cap), whatever its threads' priorities. Off unless asked: the first run +/// with a 90 % cap froze the whole PC 3 s in (input, hot keys, a log written +/// straight to disk, all stopped at once), at a point every run before it had +/// passed; a throttled thread holding what the system waits for is the +/// suspicion. `None` for unset, 0, 100 or more (no cap) or a value that is not +/// a number. In the job object's units: 1/100 of a percent. +#[cfg(any(windows, test))] +fn cpu_rate(asked: Option<&str>) -> Option<u32> { + let percent = asked?.trim().parse::<u32>().ok()?; + (1..100).contains(&percent).then_some(percent * 100) +} + +/// The most this process may commit: what the PC had free to commit at the +/// start, less `headroom` (`VICTORY_COMMIT_HEADROOM_GB`, off by default: a +/// run near the limit would end where it could have gone on) kept for other +/// programs. `None` without a headroom (0), or when less than 4 GiB +/// would be left to the run: a limit then would only end it at once. +#[cfg(any(windows, test))] +fn commit_cap(free: u64, headroom: u64) -> Option<u64> { + const LEAST: u64 = 4 << 30; + (headroom > 0).then(|| free.saturating_sub(headroom)).filter(|&cap| cap >= LEAST) +} + +/// Puts this process in a job object of its own with the limits of +/// [`cpu_rate`] and, when asked, [`commit_cap`], so that a run that takes +/// every processor (or, with the limit, all of the memory Windows can +/// commit) cannot take the PC with it: past the processor share its threads +/// wait for the next interval, past the memory its next allocation fails +/// (the run ends; the PC goes on). +/// Programs it starts are not in the job (the F1 menu's restart starts the +/// next run from here). +#[cfg(windows)] +fn contain_the_run() { + use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_CPU_RATE_CONTROL_ENABLE, + JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP, JOB_OBJECT_LIMIT_PROCESS_MEMORY, + JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK, JOBOBJECT_CPU_RATE_CONTROL_INFORMATION, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectCpuRateControlInformation, + JobObjectExtendedLimitInformation, SetInformationJobObject, + }; + use windows_sys::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let rate = cpu_rate(std::env::var("VICTORY_CPU_CAP_PERCENT").ok().as_deref()); + let headroom_gb = std::env::var("VICTORY_COMMIT_HEADROOM_GB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(0); + let free = { + // SAFETY: zeroed is a valid PERFORMANCE_INFORMATION; filled by the call. + let mut info: PERFORMANCE_INFORMATION = unsafe { std::mem::zeroed() }; + info.cb = size_of::<PERFORMANCE_INFORMATION>() as u32; + // SAFETY: `info` is ours, `cb` its size. + let ok = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; + ok.then(|| (info.CommitLimit.saturating_sub(info.CommitTotal) as u64).saturating_mul(info.PageSize as u64)) + }; + let cap = free.and_then(|free| commit_cap(free, headroom_gb << 30)); + if rate.is_none() && cap.is_none() { + tracing::info!("the run is not held to a processor share (VICTORY_CPU_CAP_PERCENT not set) or a memory limit (VICTORY_COMMIT_HEADROOM_GB not set)"); + return; + } + // SAFETY: a new, unnamed job object; its handle is kept for the whole run (never closed). + let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; + if job.is_null() { + tracing::warn!("no job object: the run is not held to a processor share or a memory limit"); + return; + } + // SAFETY: zeroed is a valid JOBOBJECT_EXTENDED_LIMIT_INFORMATION (no limits). + let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK; + if let Some(cap) = cap { + limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY; + limits.ProcessMemoryLimit = cap as usize; + } + // SAFETY: our job, and the structure the class names, alive for the call. + let limited = unsafe { + SetInformationJobObject( + job, + JobObjectExtendedLimitInformation, + (&raw const limits).cast(), + size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, + ) + } != 0; + let mut capped = false; + if let Some(rate) = rate { + // SAFETY: zeroed is a valid JOBOBJECT_CPU_RATE_CONTROL_INFORMATION. + let mut control: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION = unsafe { std::mem::zeroed() }; + control.ControlFlags = JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP; + control.Anonymous.CpuRate = rate; + // SAFETY: as above. + capped = unsafe { + SetInformationJobObject( + job, + JobObjectCpuRateControlInformation, + (&raw const control).cast(), + size_of::<JOBOBJECT_CPU_RATE_CONTROL_INFORMATION>() as u32, + ) + } != 0; + } + // SAFETY: our job and our own process. + let assigned = unsafe { AssignProcessToJobObject(job, GetCurrentProcess()) } != 0; + tracing::info!( + assigned, + limited, + capped, + cpu_percent = rate.map(|r| r / 100), + commit_mb = cap.map(|c| c >> 20), + "the run is held to what VICTORY_CPU_CAP_PERCENT and VICTORY_COMMIT_HEADROOM_GB ask for, so the PC stays usable" + ); +} + +/// Ctrl+Alt+Shift+End ends this process at once, from a thread of its own +/// that waits for nothing but the key: it needs neither the title's window +/// nor a new program (Task Manager, a console), which a stuck PC may no +/// longer start. A thread stuck in a driver can still hold the process until +/// the driver lets go. `VICTORY_ESCAPE_KEY=0`: no key. +#[cfg(windows)] +fn escape_key() { + use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_TIME_CRITICAL, TerminateProcess, + }; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, RegisterHotKey, VK_END, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{GetMessageW, MSG, WM_HOTKEY}; + if std::env::var_os("VICTORY_ESCAPE_KEY").is_some_and(|v| v == "0") { + return; + } + let started = std::thread::Builder::new().name("victory-escape-key".to_owned()).spawn(|| { + // SAFETY: a plain call on this thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + const ID: i32 = 0x5643; // any id of this thread's + // SAFETY: a hot key for this thread's own queue (no window). + let registered = unsafe { + RegisterHotKey(std::ptr::null_mut(), ID, MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT, u32::from(VK_END)) + } != 0; + if !registered { + tracing::warn!("Ctrl+Alt+Shift+End is taken by another program: no key to end the game with"); + return; + } + tracing::info!("Ctrl+Alt+Shift+End ends the game at once (VICTORY_ESCAPE_KEY=0: no key)"); + // SAFETY: zeroed is a valid MSG; filled by each call. + let mut msg: MSG = unsafe { std::mem::zeroed() }; + // SAFETY: this thread's queue; > 0 while there are messages. + while unsafe { GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) } > 0 { + if msg.message == WM_HOTKEY && msg.wParam == ID as usize { + eprintln!("VIctory: Ctrl+Alt+Shift+End: the game ends now"); + // SAFETY: ends this process; nothing of it is waited for. + unsafe { TerminateProcess(GetCurrentProcess(), 1) }; + } + } + }); + if let Err(error) = started { + tracing::warn!(%error, "no thread for Ctrl+Alt+Shift+End: no key to end the game with"); + } } #[cfg(test)] mod tests { use super::*; + /// The processor share: none unless asked, none for 0, 100 or more, or + /// for what is not a number. + #[test] + fn the_processor_share_is_asked_in_percent() { + assert_eq!(cpu_rate(None), None); + assert_eq!(cpu_rate(Some("90")), Some(9000)); + assert_eq!(cpu_rate(Some(" 75 ")), Some(7500)); + assert_eq!(cpu_rate(Some("0")), None); + assert_eq!(cpu_rate(Some("100")), None); + assert_eq!(cpu_rate(Some("half")), None); + } + + /// The memory limit leaves the headroom free, and is not set at all + /// without a headroom or with too little left for the run. + #[test] + fn the_memory_limit_leaves_room_for_other_programs() { + const GB: u64 = 1 << 30; + assert_eq!(commit_cap(50 * GB, 6 * GB), Some(44 * GB)); + assert_eq!(commit_cap(50 * GB, 0), None); + assert_eq!(commit_cap(9 * GB, 6 * GB), None); + assert_eq!(commit_cap(2 * GB, 6 * GB), None); + } + + /// A second with every processor busy, one with a little room, and one + /// with plenty: only the first counts toward stepping down, only the + /// last toward stepping back. + #[test] + fn busy_and_calm_seconds_are_told_apart() { + // 16 processors for a second: 160,000,000 ticks of 100 ns. + let total = 160_000_000; + assert!(saturated(total / 100, total)); + assert!(!calm(total / 100, total)); + assert!(!saturated(total / 10, total)); + assert!(!calm(total / 10, total)); + assert!(!saturated(total / 4, total)); + assert!(calm(total / 4, total)); + // No time passed (a clock that did not move): neither. + assert!(!saturated(0, 0)); + assert!(!calm(0, 0)); + } + #[test] fn a_quoted_angle_bracket_does_not_end_its_tag() { let text = "<Game><ShellVisuals DefaultDisplayName=\"A > B\" Description='x>y'/>\ diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index d2f03b4..87b1a01 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -120,11 +120,51 @@ fn title_output() -> String { said.iter().map(|l| format!(" title said: {l}\n")).collect() } +/// Whether a crash, once reported, is left to Windows Error Reporting +/// (`VICTORY_ERROR_REPORTING=1`), read when the handlers are installed so +/// that the crash itself reads no environment. +static TO_WINDOWS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Ends the process an unhandled exception is about to end, at once, with +/// the exception's code, once [`report_unhandled`] has logged it. Left to +/// Windows, the crash waits for Windows Error Reporting, which starts a +/// program of its own (WerFault): on a PC that can no longer start one (a +/// stuck run's services timed out for 40 minutes, the Error Reporting +/// service among them) the crashed process stood there instead of ending. +/// The title's 30 s watchdog ends a stopped frame loop this way. +/// `VICTORY_ERROR_REPORTING=1`: left to Windows (its dialog and dumps), as +/// before. +/// +/// # Safety +/// +/// `info` is null or the exception pointers passed to an unhandled-exception +/// filter. +pub unsafe fn end_unhandled(info: *const EXCEPTION_POINTERS) { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + if TO_WINDOWS.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + let code = if info.is_null() { + 1 + } else { + // SAFETY: the caller passes the filter's exception pointers. + unsafe { (*(*info).ExceptionRecord).ExceptionCode as u32 } + }; + // SAFETY: ends this process; nothing of it is waited for. + unsafe { TerminateProcess(GetCurrentProcess(), code) }; +} + /// Installs the handlers; call once before running title code. pub fn report_crashes() { + TO_WINDOWS.store( + std::env::var_os("VICTORY_ERROR_REPORTING").is_some_and(|v| v == "1"), + std::sync::atomic::Ordering::Relaxed, + ); unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 { // SAFETY: the system passes the exception being dispatched. unsafe { report_unhandled(info) }; + // SAFETY: as above. + unsafe { end_unhandled(info) }; EXCEPTION_CONTINUE_SEARCH } // SAFETY: registers handlers that only read the exception they are diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 1f301af..2253bb4 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -54,7 +54,8 @@ mod windows; #[cfg(windows)] pub use crash::{ - locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, + end_unhandled, locate, log_crash, log_crashes_to, note_title_output, report_crashes, + report_unhandled, }; #[cfg(all(windows, feature = "diagnostics"))] pub use crash::save_on_crash; diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1 index 11a45ee..9f75fd9 100644 --- a/scripts/play-foxhound.ps1 +++ b/scripts/play-foxhound.ps1 @@ -70,7 +70,11 @@ param( # cannot be written — Steam's launch options hand every argument over as it was typed, and # anything else starting this with -File does too, and no parameter can be given twice — # `NAME=VALUE`, several of them comma-separated in one `-More`; `NAME=` unsets a switch. - [object[]]$More = @() + [object[]]$More = @(), + # A victory.exe left behind by an earlier run is not ended before the start (see Stop-VictoryLeftovers). + [switch]$KeepLeftovers, + # The game is ended when its window has not answered for this many seconds (Start-HangWatch); 0: never. + [ValidateRange(0, 86400)][int]$HangSeconds = 120 ) $repo = Split-Path $PSScriptRoot -Parent . (Join-Path $PSScriptRoot 'preload-window.ps1') @@ -113,8 +117,13 @@ if ($menu['VICTORY_MENU_FPS'] -match '^\d+$' -and [int]$menu['VICTORY_MENU_FPS'] # Pipeline workers raise shader-build throughput but also increase the startup memory peak. # Use fewer on 16 GiB hosts; `-More` can still override this for a specific run. $physicalRam = (Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction SilentlyContinue).TotalPhysicalMemory -$pipelineWorkers = '8' -if ($physicalRam) { $pipelineWorkers = if ($physicalRam -le 16GB) { '4' } else { '12' } } +# Also never more than a quarter of the logical processors (2 to 6): 12 on a 64 GB PC, with the title's own +# threads beside them, left nothing for other programs; Task Manager, a console and services could not start. +# A preload (-Preload) makes the pipelines ahead, so few are left to make while playing. +$logical = [Environment]::ProcessorCount +$byCores = [Math]::Max(2, [Math]::Min(6, [int][Math]::Floor($logical / 4))) +$pipelineWorkers = "$byCores" +if ($physicalRam -and $physicalRam -le 16GB) { $pipelineWorkers = "$([Math]::Min(4, $byCores))" } $settings = @{ # Submission and copy machinery # Left off: VICTORY_RELAY=2, as fast as off on an RTX 5070 Ti (26.9 against 27.4 fps, the first cutscene's diner @@ -369,6 +378,74 @@ $paths = 'VICTORY_MENU_PAD', 'VICTORY_HOME', 'VICTORY_ADAPTER', 'VICTORY_CONFIG' Get-ChildItem Env:VICTORY_* -ErrorAction SilentlyContinue | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" } foreach ($k in $settings.Keys) { Set-Item "Env:$k" $settings[$k] } +# Cleanup before the start: a victory.exe left behind by an earlier run is ended. The F1 menu's SAVE AND RESTART +# can leave the old game without a window, and a closed preload can leave its pipeline workers (`victory warm`); +# either holds its memory and its processors. Only those started over a minute ago: a game that is still opening +# its window is left alone. A game with a window, or a preload or warm run whose parent still runs, is listed +# but left alone too. -KeepLeftovers: none ended. +function Stop-VictoryLeftovers { + $all = @(Get-CimInstance Win32_Process -Filter "Name='victory.exe'" -ErrorAction SilentlyContinue) + if (-not $all.Count) { return } + $alive = @{}; foreach ($p in Get-Process -ErrorAction SilentlyContinue) { $alive[[int]$p.Id] = $p } + foreach ($w in $all) { + $proc = $alive[[int]$w.ProcessId] + if (-not $proc) { continue } + $cmd = [string]$w.CommandLine + $kind = if ($cmd -match '\spreload(\s|$)') { 'preload' } elseif ($cmd -match '\swarm(\s|$)') { 'warm' } elseif ($cmd -match '\s(play|run)(\s|$)') { 'game' } else { 'other' } + $window = $proc.MainWindowHandle -ne [IntPtr]::Zero + # A parent id can be reused after the parent ended: it only counts if that process started before this one. + $parent = $alive[[int]$w.ParentProcessId] + $parentAlive = $false + if ($parent) { try { $parentAlive = $parent.StartTime -le $proc.StartTime } catch { $parentAlive = $true } } + $age = try { ((Get-Date) - $proc.StartTime).TotalSeconds } catch { 0 } + $left = switch ($kind) { 'game' { -not $window } { $_ -in 'preload', 'warm' } { -not $parentAlive } default { $false } } + $mb = [Math]::Round($proc.PrivateMemorySize64 / 1MB) + if ($left -and $age -ge 60 -and -not $KeepLeftovers) { + Write-Host ("Ending a victory.exe left behind: pid {0}, {1}, {2:N0} MB committed" -f $w.ProcessId, $kind, $mb) + # Not /T: after the F1 menu's restart this launcher is itself a child of the old game. + & taskkill.exe /PID $w.ProcessId /F 2>&1 | Out-Null + } else { + Write-Host ("victory.exe already running, left alone: pid {0}, {1}, {2:N0} MB committed{3}" -f $w.ProcessId, $kind, $mb, $(if ($window) { ', with a window' } else { '' })) + } + } +} +Stop-VictoryLeftovers + +# Hang watch: the game started from here is ended when its window has not answered Windows for -HangSeconds +# in a row. It runs on a thread of this window's own process, started before the game: when the PC is stuck it +# needs no new program (Task Manager, taskkill and consoles were what could not start), and it ends the game +# through .NET, not taskkill. A window still being made, or none (a preload's workers), is never counted. A +# thread stuck in a driver can still hold the process until the driver lets go. Ctrl+Alt+Shift+End in the game +# does the same at once. +function Start-HangWatch([datetime]$since, [int]$seconds) { + if ($seconds -le 0) { return $null } + $ps = [powershell]::Create() + $null = $ps.AddScript({ + param($since, $seconds) + [Threading.Thread]::CurrentThread.Priority = [Threading.ThreadPriority]::Highest + $first = @{} # pid -> when its window was first seen not answering + while ($true) { + Start-Sleep -Seconds 5 + foreach ($g in [Diagnostics.Process]::GetProcessesByName('victory')) { + try { if ($g.StartTime -lt $since) { continue } } catch { continue } + $g.Refresh() + # Responding asks the main window (a few seconds at most); a process without one answers yes. + if ($g.MainWindowHandle -eq [IntPtr]::Zero -or $g.Responding) { $first.Remove($g.Id); continue } + if (-not $first.ContainsKey($g.Id)) { $first[$g.Id] = [DateTime]::UtcNow; continue } + $stuck = ([DateTime]::UtcNow - $first[$g.Id]).TotalSeconds + if ($stuck -ge $seconds) { + [Console]::WriteLine(("Hang watch: the game's window has not answered for {0:N0} s: ending victory.exe (pid {1}). -HangSeconds 0: never." -f $stuck, $g.Id)) + try { $g.Kill() } catch { [Console]::WriteLine("Hang watch: it could not be ended: $_") } + $first.Remove($g.Id) + } + } + } + }).AddArgument($since).AddArgument($seconds) + $null = $ps.BeginInvoke() + return $ps +} +$hangWatch = $null + $logs = Join-Path $homeDir 'logs'; New-Item -ItemType Directory -Force $logs | Out-Null $log = Join-Path $logs ('victory-nvidia-{0:yyyyMMdd-HHmmss}.log' -f (Get-Date)) $writer = [IO.StreamWriter]::new($log, $false, [Text.UTF8Encoding]::new($false)); $writer.AutoFlush = $true @@ -412,11 +489,16 @@ try { $psi = [Diagnostics.ProcessStartInfo]::new('cmd.exe', ('/d /s /c ""%VFG_BIN%" run "%VFG_EXE%" --console {0} --execute 2>&1"' -f $console)) $psi.UseShellExecute = $false; $psi.CreateNoWindow = $true; $psi.RedirectStandardOutput = $true $psi.StandardOutputEncoding = [Text.UTF8Encoding]::new($false); $psi.WorkingDirectory = $repo + $hangWatch = Start-HangWatch (Get-Date) $HangSeconds + if ($hangWatch) { Write-Host "Hang watch: the game is ended if its window stops answering for $HangSeconds s; the game's own watchdog ends a frame loop stopped for 30 s (Ctrl+Alt+Shift+End: at once)." } $p = [Diagnostics.Process]::Start($psi) while ($null -ne ($line = $p.StandardOutput.ReadLine())) { $writer.WriteLine($line); $line } $p.WaitForExit() $global:LASTEXITCODE = $p.ExitCode } -finally { Pop-Location; $writer.Dispose(); Close-PreloadWindow $preloadWindow } +finally { + if ($hangWatch) { try { $hangWatch.Stop(); $hangWatch.Dispose() } catch {} } + Pop-Location; $writer.Dispose(); Close-PreloadWindow $preloadWindow +} # What `victory run` returned: a title that failed is a failed start for whoever called this script. exit $LASTEXITCODE ```
Author
Owner

@⁠Smoodie7 on GitHub · 2026-11-30 06:25 UTC · original

@⁠victorious-gh please tell your agent to open a pull request with the following "fix", if you can test it on your machine and provide the logs before/after it would be perfect. Thanks for contributing again.

**@⁠Smoodie7** on GitHub · 2026-11-30 06:25 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7270637325) @⁠victorious-gh please tell your agent to open a pull request with the following "fix", if you can test it on your machine and provide the logs before/after it would be perfect. Thanks for contributing again.
Author
Owner

@⁠victorious-gh on GitHub · 2026-11-30 06:28 UTC · original

I made this account to avoid using my actual gh account. Local setup is all tied to my main account... if someone else can apply it and test it that would be great. :)

**@⁠victorious-gh** on GitHub · 2026-11-30 06:28 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7270689681) I made this account to avoid using my actual gh account. Local setup is all tied to my main account... if someone else can apply it and test it that would be great. :)
Author
Owner

@⁠Smoodie7 on GitHub · 2026-11-30 06:32 UTC · original

@⁠victorious-gh Got it. I suppose that @⁠sansj24k is on it. And btw thanks again for your contribution!

**@⁠Smoodie7** on GitHub · 2026-11-30 06:32 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7270747541) @⁠victorious-gh Got it. I suppose that @⁠sansj24k is on it. And btw thanks again for your contribution!
Author
Owner

@⁠victorious-gh on GitHub · 2026-11-30 06:44 UTC · original

Yeah my context said it looks better than what it'd had come up w/... so all good :) thanks @⁠sansj24k

**@⁠victorious-gh** on GitHub · 2026-11-30 06:44 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7270970399) Yeah my context said it looks better than what it'd had come up w/... so all good :) thanks @⁠sansj24k
Author
Owner

@⁠sansj24k on GitHub · 2026-11-30 06:46 UTC · original

You're welcome twin

**@⁠sansj24k** on GitHub · 2026-11-30 06:46 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7271004913) You're welcome twin
Author
Owner

@⁠sdpiter on GitHub · 2026-11-30 07:48 UTC · original

I can confirm this on the same card, and I can add the second half of the symptom: the PC itself becomes unusable, not just the game window.

PC: RTX 4070 Ti 12 GB (driver 32.0.16.2140), Ryzen 7 5700G 8c/16t, 32 GB RAM, Windows 11 26H2 build 26300.9974, desktop 3440x1440 (21:9), HAGS off, VBS on. Series X profile, --res 1440, DLSS off.

Run 1: v2026.11.29.02, launched with no preload

The game starts and renders, then a minute in the window stops responding. What follows matches your report exactly: no new program could be started on the PC, Task Manager could not kill the process (neither End task nor End process tree), and the machine only came back after a power cycle. Nothing was in an error state in the log, it just stopped mid-run (last line 00:46:30Z, 152 shader translated, 9218 MB private).

Run 2: v2026.11.29.05, this time with a complete preload first

victory.exe warm
83881 pipelines known, 0 made before (f967e2df018f2a34), 0 bad; 83881 to make, 10 processes
... 83881 of 83881, 1830 s, exit code 0

So the saved pipeline cache was complete and it is still the second start with a saved cache that goes wrong. The window reaches the loading screen (153 fps 1 draws/frame), then stops presenting. In the log:

06:15:48.177 WARN victory_hle::modules::xmem: XMemVirtualAlloc: no room at first in the
title's window size=6538919936 kind=0x42000 flags=0x23 os error 8
largest_free_mb=6143 free_runs=5 spare_given_back=true at=0x1c00000000
06:15:53.261 INFO victory_gpu::pipeline: shader translated stage="compute" hash=8e9fa5ede09d77c5 ms=25
06:15:54.233 compiles: 9 running (most at once 10), 216 started, 207 finished, ...
06:27:20.009 compiles: 9 running (most at once 10), 216 started, 207 finished, ... (identical)

11.5 minutes with the compile counters frozen at exactly the same numbers, window "Not responding", 8942 MB private / 5158 MB resident, the PC had 16 GB free and 66 GB of commit left, so this is not RAM exhaustion. This time I could close it with Alt+F4 after those 11.5 minutes, but nothing it was doing had progressed at all.

Two things this adds to your dump:

  1. largest_free_mb=6143 against a 6236 MB request — the spare_given_back=true path of .04/.05 does run here, and it still does not fit, so the constrained search is entered anyway. If #3767 places the reservation by walking the window instead, this case is covered too.
  2. The window is 3440x1440 (21:9), and the title's UI pool is sized for the 16:9 1440p targets, which is the shape where .02's fix landed — so the 3.9 GB placeholder is the same size here, but the address space around it is busier on a 21:9 output.

If a build with #3767 is available to test, I will run it on this PC and report back — the reproduction is reliable here: complete preload, start the game, it hangs within seconds and (on .02) took the whole machine with it.

**@⁠sdpiter** on GitHub · 2026-11-30 07:48 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7272137544) I can confirm this on the same card, and I can add the second half of the symptom: **the PC itself becomes unusable**, not just the game window. **PC:** RTX 4070 Ti 12 GB (driver 32.0.16.2140), Ryzen 7 5700G 8c/16t, 32 GB RAM, Windows 11 26H2 build 26300.9974, desktop 3440x1440 (21:9), HAGS off, VBS on. Series X profile, `--res 1440`, DLSS off. ### Run 1: v2026.11.29.02, launched with no preload The game starts and renders, then a minute in the window stops responding. What follows matches your report exactly: no new program could be started on the PC, Task Manager could not kill the process (neither End task nor End process tree), and the machine only came back after a **power cycle**. Nothing was in an error state in the log, it just stopped mid-run (last line 00:46:30Z, 152 `shader translated`, 9218 MB private). ### Run 2: v2026.11.29.05, this time with a complete preload first ``` victory.exe warm 83881 pipelines known, 0 made before (f967e2df018f2a34), 0 bad; 83881 to make, 10 processes ... 83881 of 83881, 1830 s, exit code 0 ``` So the saved pipeline cache was complete and it is still the *second start with a saved cache* that goes wrong. The window reaches the loading screen (`153 fps 1 draws/frame`), then stops presenting. In the log: ``` 06:15:48.177 WARN victory_hle::modules::xmem: XMemVirtualAlloc: no room at first in the title's window size=6538919936 kind=0x42000 flags=0x23 os error 8 largest_free_mb=6143 free_runs=5 spare_given_back=true at=0x1c00000000 06:15:53.261 INFO victory_gpu::pipeline: shader translated stage="compute" hash=8e9fa5ede09d77c5 ms=25 06:15:54.233 compiles: 9 running (most at once 10), 216 started, 207 finished, ... 06:27:20.009 compiles: 9 running (most at once 10), 216 started, 207 finished, ... (identical) ``` 11.5 minutes with the compile counters frozen at exactly the same numbers, window "Not responding", 8942 MB private / 5158 MB resident, the PC had 16 GB free and 66 GB of commit left, so this is not RAM exhaustion. This time I could close it with Alt+F4 after those 11.5 minutes, but nothing it was doing had progressed at all. Two things this adds to your dump: 1. `largest_free_mb=6143` against a 6236 MB request — the `spare_given_back=true` path of .04/.05 does run here, and it still does not fit, so the constrained search is entered anyway. If #3767 places the reservation by walking the window instead, this case is covered too. 2. The window is 3440x1440 (21:9), and the title's UI pool is sized for the 16:9 1440p targets, which is the shape where .02's fix landed — so the 3.9 GB placeholder is the same size here, but the address space around it is busier on a 21:9 output. If a build with #3767 is available to test, I will run it on this PC and report back — the reproduction is reliable here: complete preload, start the game, it hangs within seconds and (on .02) took the whole machine with it.
Author
Owner

@⁠Smoodie7 on GitHub · 2026-11-30 07:52 UTC · original · edited 2026-11-30 07:53 UTC

@⁠sdpiter you can test it with #3767 since it provides an experimental fix (you can ask your ai agent to set it up for you). If you do, don't forget to leave a comment + your logs under the pull request.

**@⁠Smoodie7** on GitHub · 2026-11-30 07:52 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/3765#issuecomment-7272221876) · edited 2026-11-30 07:53 UTC @⁠sdpiter you can test it with #3767 since it provides an experimental fix (you can ask your ai agent to set it up for you). If you do, don't forget to leave a comment + your logs under the pull request.
This discussion has been locked. Commenting is limited to contributors.
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.

Dependencies

No dependencies set

Reference
github/trustno1-coder--VIctory-NVIDIA#3765
No description provided.