From 95910ecb50cef755d2073c62e86044f79bcd74d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ABDULKAD=C4=B0R=20ATE=C5=9E?= Date: Sat, 5 Dec 2026 19:43:34 +0300 Subject: [PATCH 1/8] Stacks: unwind a copy of each thread's stack; the live walk stops at a frame register off the stack LARP_STACKS walked each suspended thread's live stack with RtlVirtualUnwind, which reads through a frame register that can hold anything where the thread was stopped, or stack pages the thread never committed: in VIctory-NVIDIA the same walk ended the process with an access violation inside ntdll (its sampling profiler, 43e89ba1). frames_of now copies the stack (from rsp up, at most 512 KiB, zeros after) with ReadProcessMemory while the thread is suspended, resumes it, and unwinds the copy (crash::unwind_copy). unwind_into, the crash handler's live walk, stops where a frame register lies outside the thread's stack. Ported from VIctory-NVIDIA 43e89ba1. --- crates/larp-loader/src/crash.rs | 134 +++++++++++++++++++++++++++++++ crates/larp-loader/src/stacks.rs | 63 ++++++++++++--- 2 files changed, 184 insertions(+), 13 deletions(-) diff --git a/crates/larp-loader/src/crash.rs b/crates/larp-loader/src/crash.rs index 073ee92..15f1a42 100644 --- a/crates/larp-loader/src/crash.rs +++ b/crates/larp-loader/src/crash.rs @@ -570,6 +570,24 @@ pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mu context.Rip = unsafe { (rsp as *const u64).read() }; context.Rsp += 8; } else { + // A function that keeps a frame register is unwound through it: + // RtlVirtualUnwind reads the stack at that register. Walking a + // thread that was stopped anywhere (`stacks::dump_stacks`), the + // register can hold anything, and the read faulted inside ntdll. + // Stop where it does not point into this thread's stack. + // SAFETY: `entry` is the table entry the lookup gave for `image`; + // its unwind information lies in that image, the frame register + // in the low four bits of its fourth byte. + let frame_register = unsafe { + let info = image as usize + (*entry).Anonymous.UnwindInfoAddress as usize; + (info as *const u8).add(3).read() & 0x0F + }; + if frame_register != 0 { + let value = register(context, frame_register) as usize; + if value < low || value >= high { + break; + } + } let (mut data, mut frame) = (null_mut(), 0); // SAFETY: `entry` belongs to `image`; the context is our copy. unsafe { @@ -592,6 +610,122 @@ pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mu } } +/// The general register an unwind code numbers `n` (0 rax .. 15 r15). +fn register(context: &CONTEXT, n: u8) -> u64 { + match n { + 1 => context.Rcx, + 2 => context.Rdx, + 3 => context.Rbx, + 4 => context.Rsp, + 5 => context.Rbp, + 6 => context.Rsi, + 7 => context.Rdi, + 8 => context.R8, + 9 => context.R9, + 10 => context.R10, + 11 => context.R11, + 12 => context.R12, + 13 => context.R13, + 14 => context.R14, + 15 => context.R15, + _ => context.Rax, + } +} + +/// [`unwind_into`] over a copy of a thread's stack: `copy` holds the bytes +/// from `context.Rsp` up (`len` of them, then zeros), taken while the +/// thread was suspended. Every address the unwind data makes it read is +/// then in the copy, never in a live stack the thread may have grown or +/// left (walking live threads read reserved stack pages and faulted). +/// Registers that point into the copied range are moved into the copy; a +/// frame register that points elsewhere ends the walk. +pub(crate) fn unwind_copy(context: CONTEXT, copy: &[u8], len: usize, frames: &mut Vec) { + let mut aligned = Aligned16(context); + let context = &mut aligned.0; + frames.push(context.Rip); + let (real_lo, buf_lo) = (context.Rsp as usize, copy.as_ptr() as usize); + let (real_hi, buf_hi) = (real_lo + len, buf_lo + len); + let moved = |x: u64| -> u64 { + let x = x as usize; + (if x >= real_lo && x < real_hi { x - real_lo + buf_lo } else { x }) as u64 + }; + let move_all = |c: &mut CONTEXT| { + for r in [ + &mut c.Rbx, &mut c.Rbp, &mut c.Rsi, &mut c.Rdi, &mut c.R12, &mut c.R13, &mut c.R14, + &mut c.R15, + ] { + *r = moved(*r); + } + }; + context.Rsp = buf_lo as u64; + move_all(context); + while frames.len() < MAX_FRAMES { + let rsp = context.Rsp as usize; + if rsp < buf_lo || rsp + 8 > buf_hi { + break; + } + let mut image = 0; + // SAFETY: looks up the function table entry covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // SAFETY: `rsp` is inside the copy. + context.Rip = unsafe { (rsp as *const u64).read_unaligned() }; + context.Rsp += 8; + } else { + // SAFETY: as in `unwind_into`. + let frame_register = unsafe { + let info = image as usize + (*entry).Anonymous.UnwindInfoAddress as usize; + (info as *const u8).add(3).read() & 0x0F + }; + if frame_register != 0 { + let register = match frame_register { + 1 => &mut context.Rcx, + 2 => &mut context.Rdx, + 3 => &mut context.Rbx, + 5 => &mut context.Rbp, + 6 => &mut context.Rsi, + 7 => &mut context.Rdi, + 8 => &mut context.R8, + 9 => &mut context.R9, + 10 => &mut context.R10, + 11 => &mut context.R11, + 12 => &mut context.R12, + 13 => &mut context.R13, + 14 => &mut context.R14, + 15 => &mut context.R15, + _ => break, + }; + *register = moved(*register); + let at = *register as usize; + if at < buf_lo || at >= buf_hi { + break; + } + } + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our copy and + // its stack registers point into `copy`, whose zeros after `len` + // take reads past the frames copied. + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; + move_all(context); + } + if context.Rip == 0 { + break; + } + frames.push(context.Rip); + } +} + /// `module+rva`, or the bare address. pub fn locate(address: usize) -> String { module_of(address).unwrap_or_else(|| format!("{address:#x}")) diff --git a/crates/larp-loader/src/stacks.rs b/crates/larp-loader/src/stacks.rs index f88d907..6ea75bc 100644 --- a/crates/larp-loader/src/stacks.rs +++ b/crates/larp-loader/src/stacks.rs @@ -9,17 +9,26 @@ use windows_sys::Wdk::System::Threading::{ }; use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree}; use windows_sys::Win32::System::Diagnostics::Debug::{ - CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, + CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, ReadProcessMemory, }; use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; use windows_sys::Win32::System::Threading::{ - GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread, + GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, }; -use crate::crash::{MAX_FRAMES, locate, unwind_into}; +use crate::crash::{MAX_FRAMES, locate, unwind_copy}; + +/// The most of a stack copied for a walk ([`frames_of`]), and the zeros after. +const COPY_BYTES: usize = 512 << 10; +const COPY_SLACK: usize = 64 << 10; + +thread_local! { + /// A walking thread's copy of the stack it walks, made before any suspend. + static COPY: std::cell::RefCell> = std::cell::RefCell::new(vec![0; COPY_BYTES + COPY_SLACK]); +} /// Reads `LARP_STACKS` and, if set, starts a thread that prints every /// thread's stack at each listed time (seconds from now). @@ -117,6 +126,9 @@ pub fn dump_stacks() { /// The thread's frames and its current and base scheduling priority (0-31). fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { let mut frames = Vec::with_capacity(MAX_FRAMES); + // The copy's buffer is made now, before the suspend below (a suspended + // thread may hold the heap's lock). + COPY.with(|_| ()); let mut info: BasicInfo = BasicInfo { exit_status: 0, teb: std::ptr::null(), @@ -144,18 +156,43 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { // SAFETY: zeroed is a valid CONTEXT. let mut context = Aligned(unsafe { std::mem::zeroed() }); context.0.ContextFlags = CONTEXT_FULL_AMD64; - // SAFETY: suspends, reads and resumes a thread that is not this one; - // nothing between suspend and resume allocates or takes a lock the - // thread could hold besides the unwinder's own. - unsafe { - if SuspendThread(thread) == u32::MAX { - return (frames, (info.priority, info.base_priority)); + // The stack is copied while the thread is suspended and unwound after + // the resume, in the copy (`unwind_copy`): unwinding the live stack can + // read pages the thread never committed and fault. The read goes through + // the kernel, which fails where memory is missing instead of faulting; + // the buffer was made before the suspend. + COPY.with(|copy| { + let mut copy = copy.borrow_mut(); + let mut got = None; + // SAFETY: suspends, reads and resumes a thread that is not this one; + // nothing between suspend and resume allocates or takes a lock the + // thread could hold. + unsafe { + if SuspendThread(thread) == u32::MAX { + return; + } + if GetThreadContext(thread, &mut context.0) != 0 { + let rsp = context.0.Rsp as usize; + let want = high.saturating_sub(rsp).min(COPY_BYTES); + let mut read = 0usize; + let ok = rsp >= low + && want > 0 + && ReadProcessMemory( + GetCurrentProcess(), + rsp as *const c_void, + copy.as_mut_ptr().cast(), + want, + &mut read, + ) != 0; + got = Some(if ok { want } else { read }); + } + ResumeThread(thread); } - if GetThreadContext(thread, &mut context.0) != 0 { - unwind_into(context.0, low, high, &mut frames); + if let Some(len) = got { + copy[len..].fill(0); + unwind_copy(context.0, ©, len, &mut frames); } - ResumeThread(thread); - } + }); (frames, (info.priority, info.base_priority)) } From d46c566757e3bfb641629c82d3bfec743a2653f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ABDULKAD=C4=B0R=20ATE=C5=9E?= Date: Sat, 5 Dec 2026 19:43:34 +0300 Subject: [PATCH 2/8] Crash: LARP_STACKS_AT_KILL=1 prints every thread's stack when the title writes to address 0 The title's watchdog ends a run whose frame loop stopped for 30 s by writing to address 0 (+0x23cf683, docs/troubleshooting-and-crashes.md). The first-chance report names only the watchdog thread; with the switch the first such write also dumps every other thread's stack, to name what the frame loop was stuck in. Off by default. Ported from VIctory-NVIDIA c6d5c4d7 (there diagnostics-only; larp's dump_stacks is in every build). --- crates/larp-loader/src/crash.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/larp-loader/src/crash.rs b/crates/larp-loader/src/crash.rs index 15f1a42..8afdd46 100644 --- a/crates/larp-loader/src/crash.rs +++ b/crates/larp-loader/src/crash.rs @@ -364,10 +364,33 @@ unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) { // SAFETY: as above. unsafe { report("first-chance exception", info, false) }; + // SAFETY: as above. + if unsafe { writes_zero(&*(*info).ExceptionRecord) } && stacks_at_kill() { + crate::stacks::dump_stacks(); + } } EXCEPTION_CONTINUE_SEARCH } +/// A write to address 0: how the title kills itself on purpose. Its +/// watchdog (`hooks::HEARTBEAT`) writes there 30 s after the frame loop +/// stops (`+0x23cf683`). +fn writes_zero(record: &windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_RECORD) -> bool { + record.ExceptionCode == EXCEPTION_ACCESS_VIOLATION + && record.NumberParameters >= 2 + && record.ExceptionInformation[0] == 1 + && record.ExceptionInformation[1] == 0 +} + +/// `LARP_STACKS_AT_KILL=1`: on the first such write, every other thread's +/// stack, to name what the frame loop was stuck in. +fn stacks_at_kill() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + static DONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + *ON.get_or_init(|| std::env::var_os("LARP_STACKS_AT_KILL").is_some_and(|v| v == "1")) + && !DONE.swap(true, std::sync::atomic::Ordering::Relaxed) +} + /// For an unhandled-exception filter: reports the exception that is about /// to end the process, and appends it to the crash log. /// From 59bffbbcf34be38657363339bb6cb3163541b694 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ABDULKAD=C4=B0R=20ATE=C5=9E?= Date: Sat, 5 Dec 2026 19:43:57 +0300 Subject: [PATCH 3/8] Title watchdog: LARP_TITLE_WATCHDOG=0 tells it to quit, so a 30 s stall is not ended as a crash at +0x23cf683 The watchdog's quit flag (bit 0 at title+0x71b6340) is set every half second, only on 1.0.2.1 and only when the trap bytes are where they were found. larp already feeds the heartbeat while draws wait for pipelines; this covers stalls outside those waits. Opt-in. Ported from VIctory-NVIDIA aee4c45a (default-on there). --- apps/larp/src/run.rs | 31 +++++++++++++++++++++++++++++++ crates/larp-loader/src/hooks.rs | 24 ++++++++++++++++++++++++ crates/larp-loader/src/lib.rs | 2 +- 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/apps/larp/src/run.rs b/apps/larp/src/run.rs index b96ad7b..78c76ea 100644 --- a/apps/larp/src/run.rs +++ b/apps/larp/src/run.rs @@ -42,6 +42,7 @@ pub fn run( if let Some(heartbeat) = larp_loader::watchdog_heartbeat(image.base(), &prepared.original_hash) { larp_hle::modules::d3d12x::feed_watchdog_at(heartbeat); } + quiet_title_watchdog(image.base(), &prepared.original_hash); // The program is mapped from the copy `load` wrote: the file's bytes // and their patched copy are not read again, and were held for the // whole run (two blocks of 114.7 MB each for the title, in @@ -464,3 +465,33 @@ impl LoaderLock { result } } + +/// `LARP_TITLE_WATCHDOG=0`: the title's watchdog is told to quit. It ends +/// the process when its heartbeat has not changed for 30 one-second ticks, +/// by writing to address 0 (`+0x23cf683`, which reads as a crash); larp +/// feeds the heartbeat while a draw waits for its pipeline, but a stall +/// elsewhere (stream-in, a long driver call) still trips it. In +/// VIctory-NVIDIA every run on an RTX 5060 Laptop that ended at +/// `+0x23cf683` had stood 30 s with its frames stopped first. The flag is +/// set again every half second, as the title may clear it while it starts. +/// Off by default: with it a real hang stays a hang instead of ending. +fn quiet_title_watchdog(base: usize, hash: &blake3::Hash) { + if !std::env::var("LARP_TITLE_WATCHDOG").is_ok_and(|v| v.trim() == "0") { + return; + } + let Some(flag) = larp_loader::watchdog_quit_flag(base, hash) else { + eprintln!("LARP_TITLE_WATCHDOG=0: the title's watchdog is not where it is in 1.0.2.1; left alone"); + return; + }; + eprintln!("LARP_TITLE_WATCHDOG=0: the title's 30 s watchdog is told to quit"); + let started = std::thread::Builder::new().name("larp-watchdog-off".to_owned()).spawn(move || loop { + // SAFETY: a byte of the image's writable data (the flag the + // watchdog reads), found by `watchdog_quit_flag`. + let byte = unsafe { &*(flag as *const std::sync::atomic::AtomicU8) }; + byte.fetch_or(1, std::sync::atomic::Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_millis(500)); + }); + if let Err(error) = started { + eprintln!("LARP_TITLE_WATCHDOG=0: the title's watchdog could not be told to quit: {error}"); + } +} diff --git a/crates/larp-loader/src/hooks.rs b/crates/larp-loader/src/hooks.rs index 5c46341..86aeb8a 100644 --- a/crates/larp-loader/src/hooks.rs +++ b/crates/larp-loader/src/hooks.rs @@ -22,3 +22,27 @@ const HEARTBEAT: usize = 0x71b6338; pub fn watchdog_heartbeat(base: usize, hash: &blake3::Hash) -> Option { hash.to_hex().starts_with(BUILD_1_0_2_1).then_some(base + HEARTBEAT) } + +/// The watchdog's quit flag (bit 0 of the byte at title+0x71b6340): set, +/// its thread leaves before it counts (found in VIctory-NVIDIA #1428). +const WATCHDOG_QUIT: usize = 0x71b6340; + +/// Where the watchdog kills the process (title+0x23cf683): +/// `mov dword ptr [0], 0x4d8bd421`. +const WATCHDOG_TRAP: usize = 0x23cf683; +const WATCHDOG_TRAP_BYTES: [u8; 11] = [0xc7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x21, 0xd4, 0x8b, 0x4d]; + +/// The address of the title's watchdog quit flag ([`WATCHDOG_QUIT`]) in the +/// image at `base` whose original BLAKE3 is `hash`, when the watchdog's trap +/// is where it was found; `None` for another build. +pub fn watchdog_quit_flag(base: usize, hash: &blake3::Hash) -> Option { + if !hash.to_hex().starts_with(BUILD_1_0_2_1) { + return None; + } + // SAFETY: inside the mapped image of the build the offsets were read + // from; code is readable. + let found = unsafe { + std::slice::from_raw_parts((base + WATCHDOG_TRAP) as *const u8, WATCHDOG_TRAP_BYTES.len()) + }; + (found == WATCHDOG_TRAP_BYTES).then_some(base + WATCHDOG_QUIT) +} diff --git a/crates/larp-loader/src/lib.rs b/crates/larp-loader/src/lib.rs index 328d0a3..0bc948d 100644 --- a/crates/larp-loader/src/lib.rs +++ b/crates/larp-loader/src/lib.rs @@ -47,7 +47,7 @@ pub use detour::{DetourError, call_site, call_stub, detour, near_data, patch, re pub use prepare::{PrepareError, PreparedImage, prepare}; pub use relocate::{MoveError, Moved, function_ends, move_data}; pub use replay::{MAX_ADDED, detour_found, replay_bytes, replay_dirty, replay_for, replay_install, replayed}; -pub use hooks::watchdog_heartbeat; +pub use hooks::{watchdog_heartbeat, watchdog_quit_flag}; pub use resolve::{ImportResolver, Provenance, Resolution}; pub use stacks::{dump_stacks, dump_stacks_on_schedule}; pub use threads::disable_thread_calls; From 35d5c0185376c751d8283b7bf644adfe667d46ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ABDULKAD=C4=B0R=20ATE=C5=9E?= Date: Sat, 5 Dec 2026 21:52:51 +0300 Subject: [PATCH 4/8] Docs: LARP_STACKS_AT_KILL and LARP_TITLE_WATCHDOG --- docs/environment-variables.md | 2 ++ docs/troubleshooting-and-crashes.md | 1 + 2 files changed, 3 insertions(+) diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 71e00ff..624ef77 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -63,5 +63,7 @@ Set these in `Larp\bin\launch.ps1` (or in your shell before running `larp.exe ru | `LARP_LANGUAGE` | `auto`, `en`, `de`, `fr`, `es`, `pl`, `pt-BR`, `tr`, `zh-CN`, `zh-TW` | `auto` (OS UI) | UI/overlay/CLI language (also switchable live in the `F10` menu or via `--lang`). | | `LARP_DSTORAGE_WORKERS` | `<1..64>` | logical cores | Worker thread count for DirectStorage decompression. | | `LARP_DSTORAGE_STAGING_MB` | `<16..512>` | `32` | DirectStorage staging buffer size in MiB for fast NVMe drives. | +| `LARP_STACKS_AT_KILL` | `0`, `1` | `0` | `1` prints every thread's stack when the title's 30 s watchdog kills the run (write to address 0, `+0x23cf683`), to name what the frame loop was stuck in. | +| `LARP_TITLE_WATCHDOG` | `0` | unset (left alone) | `0` tells the title's 30 s watchdog to quit (1.0.2.1 only), so a long stall is not ended as a crash at `+0x23cf683`. A real hang then stays a hang. | | `LARP_NO_ADVISOR` | `0`, `1` | `0` | Silences startup NVIDIA shader heap and XMP/EXPO RAM speed warnings. | | `LARP_D3D12_DEBUG` | `0`, `1` | `0` | Enables the Windows D3D12 debug layer (requires Graphics Tools optional feature). | diff --git a/docs/troubleshooting-and-crashes.md b/docs/troubleshooting-and-crashes.md index ae74daa..2a94130 100644 --- a/docs/troubleshooting-and-crashes.md +++ b/docs/troubleshooting-and-crashes.md @@ -95,6 +95,7 @@ Match the **`+0x...`** offset after `dll` to the table below: ### `+0x2215c35` or `+0x23cf683` — Freeze for 30 Seconds Followed by Crash - **Exact Cause:** The title's 30-second hang watchdog fired because the main loop stalled (usually heavy first-time shader compilation or disk I/O stall). +- **To see what stalled:** `set LARP_STACKS_AT_KILL=1` prints every thread's stack at the kill. **To ride out a stall:** `set LARP_TITLE_WATCHDOG=0` tells the watchdog to quit (a real hang then no longer ends by itself). - **Fix:** Simply relaunch — already-compiled pipeline blobs in `Larp\cache` are kept, so the next start picks up right where it left off. --- From c3f96fc62681582b329d142a1fe4517a53b4193b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ABDULKAD=C4=B0R=20ATE=C5=9E?= Date: Sat, 5 Dec 2026 19:25:33 +0300 Subject: [PATCH 5/8] Agility SDK: LARP_AGILITY=0 runs on Windows' own D3D12 runtime; d3d12.dll loads on first use D3D12SDKVersion becomes writable and agility::choose sets it first thing in main; build.rs delay-loads d3d12.dll so Windows reads the value set there (imported the usual way it is loaded before main and reads the constant). - LARP_AGILITY=0: System32's runtime, by the version its D3D12Core.dll exports, to tell a device removal that goes with the 1.620 runtime (and byte-offset views, which then fall back to by-element) from one that does not. - No D3D12\D3D12Core.dll beside larp.exe: Windows' own runtime instead of a loader that makes no device. - A D3D12Core.dll of another version: that version, instead of 0x887E0003. Ported from VIctory-NVIDIA (0f0ada19, e69e39c5), where an RTX 3080 Ti and an RTX 5080 on Windows 11 were refused Direct3D 12 with a mismatched file. --- apps/larp/build.rs | 3 + apps/larp/src/agility.rs | 126 ++++++++++++++++++++++++++++++++++++++- apps/larp/src/main.rs | 1 + 3 files changed, 128 insertions(+), 2 deletions(-) diff --git a/apps/larp/build.rs b/apps/larp/build.rs index a613d25..d7ab30c 100644 --- a/apps/larp/build.rs +++ b/apps/larp/build.rs @@ -35,6 +35,9 @@ fn main() { // not while Windows starts the process: mods that read the host's // name then see `LARP_HOST_NAME` (`src/host_name.rs`). println!("cargo:rustc-link-arg-bins=/DELAYLOAD:winmm.dll"); + // Windows reads `D3D12SDKVersion` when `d3d12.dll` is loaded: on + // its first use, after `agility::choose` set it in `main`. + println!("cargo:rustc-link-arg-bins=/DELAYLOAD:d3d12.dll"); println!("cargo:rustc-link-arg-bins=delayimp.lib"); } replacements(); diff --git a/apps/larp/src/agility.rs b/apps/larp/src/agility.rs index 4466469..9bd96e3 100644 --- a/apps/larp/src/agility.rs +++ b/apps/larp/src/agility.rs @@ -13,11 +13,100 @@ //! `build/native/bin/x64`; both redistributable) go into `D3D12\` beside //! `larp.exe`. vkd3d-proton reads neither export. +use std::sync::atomic::{AtomicU32, Ordering}; + /// The version of the runtime in `D3D12\` (`D3D12_SDK_VERSION` of package -/// 1.620.2). +/// 1.620.2), or what [`choose`] puts in its place before Direct3D 12 is +/// loaded. (An atomic: the same bytes as a `u32`, in memory that can be +/// written.) #[unsafe(no_mangle)] #[used] -pub static D3D12SDKVersion: u32 = 620; +pub static D3D12SDKVersion: AtomicU32 = AtomicU32::new(620); + +/// Windows reads [`D3D12SDKVersion`] when `d3d12.dll` is loaded; `build.rs` +/// has that load wait for its first use, so this, first thing in `main`, +/// sets the version Windows reads: +/// +/// - `LARP_AGILITY=0`: Windows' own runtime (System32's `D3D12Core.dll`, +/// by the version it exports), so a device removal that goes with the +/// Agility SDK's runtime can be told from one that does not. Buffer views +/// are then made by element (that runtime has no `ID3D12Device15`). +/// - no `D3D12\D3D12Core.dll` beside the program: Windows' own, in place +/// of a loader that makes no device. +/// - a `D3D12Core.dll` there of another version than 620: that version +/// (asking for 620 of a 1.618 or 1.614 file makes Windows refuse +/// Direct3D 12 altogether, 0x887E0003). +pub fn choose() { + let off = std::env::var("LARP_AGILITY").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "system")); + let core = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join("D3D12").join("D3D12Core.dll"))); + let bytes = core.as_ref().and_then(|c| std::fs::read(c).ok()); + let (version, why) = match (off, bytes.as_deref().map(agility_version)) { + (true, _) => (os_runtime(), "LARP_AGILITY=0"), + (false, None) => (os_runtime(), "no D3D12\\D3D12Core.dll beside larp.exe"), + (false, Some(None)) => (os_runtime(), "D3D12\\D3D12Core.dll is no Agility SDK runtime"), + (false, Some(Some(620))) => return, + (false, Some(Some(v))) => (v, "the version of D3D12\\D3D12Core.dll"), + }; + D3D12SDKVersion.store(version, Ordering::Relaxed); + eprintln!("D3D12 runtime: asking Windows for SDK version {version} ({why})"); +} + +/// The Agility SDK version of a `D3D12Core.dll` (its file version is +/// `1...0`, e.g. 1.620.2.0): from its `VS_FIXEDFILEINFO`. +fn agility_version(dll: &[u8]) -> Option { + let signature = 0xFEEF_04BD_u32.to_le_bytes(); + let at = dll.windows(4).position(|w| w == signature)?; + let most = u32::from_le_bytes(dll.get(at + 8..at + 12)?.try_into().ok()?); + let (major, minor) = (most >> 16, most & 0xffff); + (major == 1 && minor >= 600).then_some(minor) +} + +/// The version Windows' own runtime exports (System32's `D3D12Core.dll`); +/// asking for it, or less, keeps that runtime. 4 (the first Agility SDK's) +/// where the file is missing or unreadable. +fn os_runtime() -> u32 { + let system = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()); + std::fs::read(system.join("System32").join("D3D12Core.dll")) + .ok() + .and_then(|dll| exported_sdk_version(&dll)) + // Wine's own exports the name as code, not as the version. + .filter(|v| (4..10_000).contains(v)) + .unwrap_or(4) +} + +/// The `D3D12SDKVersion` a `D3D12Core.dll` exports (a PE32+ data export). +fn exported_sdk_version(dll: &[u8]) -> Option { + let u16_at = |at: usize| Some(u16::from_le_bytes(dll.get(at..at + 2)?.try_into().ok()?)); + let u32_at = |at: usize| Some(u32::from_le_bytes(dll.get(at..at + 4)?.try_into().ok()?)); + let pe = u32_at(0x3c)? as usize; + (dll.get(pe..pe + 4)? == b"PE\0\0").then_some(())?; + let sections = usize::from(u16_at(pe + 6)?); + let optional = pe + 24; + let table = optional + usize::from(u16_at(pe + 20)?); + // PE32+ only: the export directory is the first data directory, at 112. + (u16_at(optional)? == 0x20b).then_some(())?; + let offset = |rva: u32| -> Option { + (0..sections).find_map(|i| { + let s = table + i * 40; + let (size, va, raw_size, raw) = (u32_at(s + 8)?, u32_at(s + 12)?, u32_at(s + 16)?, u32_at(s + 20)?); + (va <= rva && rva < va + size.max(raw_size)).then(|| (rva - va + raw) as usize) + }) + }; + let exports = offset(u32_at(optional + 112)?)?; + // NumberOfNames, AddressOfFunctions, AddressOfNames, AddressOfNameOrdinals. + let count = u32_at(exports + 24)? as usize; + let functions_at = offset(u32_at(exports + 28)?)?; + let names_at = offset(u32_at(exports + 32)?)?; + let ordinals_at = offset(u32_at(exports + 36)?)?; + (0..count).find_map(|i| { + let name = offset(u32_at(names_at + 4 * i)?)?; + if dll.get(name..name + 16)? != b"D3D12SDKVersion\0" { + return None; + } + let ordinal = usize::from(u16_at(ordinals_at + 2 * i)?); + u32_at(offset(u32_at(functions_at + 4 * ordinal)?)?) + }) +} /// A pointer to a constant string, as the export is declared in C /// (`const char*`). @@ -29,3 +118,36 @@ unsafe impl Sync for Path {} #[unsafe(no_mangle)] #[used] pub static D3D12SDKPath: Path = Path(c".\\D3D12\\".as_ptr().cast()); + +#[cfg(test)] +mod tests { + use super::*; + + /// A file version `1..2.0` as `VS_FIXEDFILEINFO` holds it. + fn fixed(major: u32, minor: u32) -> Vec { + let mut bytes = vec![0u8; 32]; + bytes.extend_from_slice(&0xFEEF_04BD_u32.to_le_bytes()); + bytes.extend_from_slice(&0x0001_0000_u32.to_le_bytes()); + bytes.extend_from_slice(&((major << 16) | minor).to_le_bytes()); + bytes.extend_from_slice(&0x0002_0000_u32.to_le_bytes()); + bytes + } + + #[test] + fn agility_runtimes_are_read_by_their_file_version() { + assert_eq!(agility_version(&fixed(1, 620)), Some(620)); + assert_eq!(agility_version(&fixed(1, 614)), Some(614)); + } + + #[test] + fn a_system_file_version_is_no_agility_runtime() { + assert_eq!(agility_version(&fixed(10, 0)), None); + assert_eq!(agility_version(b"no version here"), None); + } + + #[test] + fn a_file_that_is_no_pe_exports_no_version() { + assert_eq!(exported_sdk_version(&[0u8; 256]), None); + assert_eq!(exported_sdk_version(b"MZ"), None); + } +} diff --git a/apps/larp/src/main.rs b/apps/larp/src/main.rs index 70805ca..7880953 100644 --- a/apps/larp/src/main.rs +++ b/apps/larp/src/main.rs @@ -167,6 +167,7 @@ enum Console { } fn main() -> Result<()> { + agility::choose(); larp_core::logging::init(); larp_tracy::thread_name("larp-main"); larp_tracy::wait_for_profiler(); From a036783913ea87d99ab1e58fa53980b09b71590b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ABDULKAD=C4=B0R=20ATE=C5=9E?= Date: Sat, 5 Dec 2026 21:52:51 +0300 Subject: [PATCH 6/8] Docs: LARP_AGILITY and which D3D12 runtime larp.exe runs --- docs/environment-variables.md | 1 + docs/troubleshooting-and-crashes.md | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 71e00ff..84820bb 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -55,6 +55,7 @@ Set these in `Larp\bin\launch.ps1` (or in your shell before running `larp.exe ru |---|---|---|---| | `LARP_NO_MODS` | `0`, `1` | `0` | Skips loading `.dll`/`.asi` files from `mods\` when `1`. | | `LARP_HOST_NAME` | `` (e.g. `host.exe`) | unset | From the start of `run --execute` until the mods are loaded (a `winmm.dll` proxy beside `larp.exe`, MFG Unlocker, `mods\`; a library loaded early, such as NVIDIA's, can pull the proxy in on its own), the process' main module goes by this file name, in the same folder, for mods that only start in a host program they know (`GetModuleFileNameW(NULL)` in their `DllMain`). Put back right after, so larp's own path is unchanged. `winmm.dll` is delay-loaded, so a proxy beside `larp.exe` is loaded by full path at that point instead of at process start; the log and the run summary name the `winmm.dll` in use. | +| `LARP_AGILITY` | `0` | unset (Agility SDK 1.620 from `bin\D3D12\`) | `0` runs on Windows' own D3D12 runtime instead of the bundled Agility SDK; buffer views then fall back to by-element. Without a `bin\D3D12\D3D12Core.dll`, or with one of another version, larp also asks Windows for that runtime or version. For bisecting `0x887A0005`. | | `LARP_TRAINER` | `0`, `1` | `0` | Maps Z-ROX shared controller-hold page at `0x5A52_4F58_0000`. | | `LARP_AMD_GLASS_PREPASS` | `0`, `1` | `0` | Keeps breakable-glass shader `cad3ecfdcdcf2a7d` on AMD GPUs when `1` (skipped by default on AMD to prevent `amdxc64` crash). | | `LARP_LEAVE_OUT` | `,` | unset | Comma-separated 16-hex-char shader hashes whose pipelines should be skipped. | diff --git a/docs/troubleshooting-and-crashes.md b/docs/troubleshooting-and-crashes.md index ae74daa..b31bee2 100644 --- a/docs/troubleshooting-and-crashes.md +++ b/docs/troubleshooting-and-crashes.md @@ -29,6 +29,7 @@ Use this guide to diagnose any startup error, exit code, or mid-game crash in se - Launch with **`series-s.cmd`** first (Series X mode allocates significantly larger heaps and ray-tracing pools). - Delete `Larp\cache` after updating drivers or `larp.exe`. - In `options.ini`, set `stream_budget = 2500` (for 8–12 GB cards) to prevent VRAM eviction hangs during world entry. +- **Which D3D12 runtime runs:** larp.exe asks Windows for the Agility SDK runtime in `bin\D3D12\` (1.620). If that `D3D12Core.dll` is missing, or is another version, larp uses Windows' own runtime or the file's version, and says so in the log (`D3D12 runtime: asking Windows for SDK version ...`). To bisect a device removal, `set LARP_AGILITY=0` runs on Windows' own D3D12 runtime instead (it also turns byte-offset buffer views off). ### B. `exit -1073741819` (`0xC0000005`) on AMD RX 9060 XT / RX 9070 / RX 9070 XT - **Cause:** AMD's `amdxc64.dll` shader compiler had two null-pointer crashes on RDNA 3/4 drivers: From d2a79dd64005fba1215b990493e38564f0907beb Mon Sep 17 00:00:00 2001 From: gamingwithhomie Date: Sun, 6 Dec 2026 05:37:28 +0530 Subject: [PATCH 7/8] input: mouse buttons fully mappable (melee alias, Mouse1/2 binds, mouse-button trigger binds free LMB/RMB) --- .../larp-hle/src/modules/gameinput/mouse.rs | 50 +++++++++++++++++-- docs/controls.example.ini | 9 +++- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/larp-hle/src/modules/gameinput/mouse.rs b/crates/larp-hle/src/modules/gameinput/mouse.rs index a3b987c..ec7f881 100644 --- a/crates/larp-hle/src/modules/gameinput/mouse.rs +++ b/crates/larp-hle/src/modules/gameinput/mouse.rs @@ -358,6 +358,8 @@ fn parse_vk(name: &str) -> Option { } } match s.as_str() { + "MOUSE1" | "LMB" | "LEFTMOUSE" => Some(0x01), + "MOUSE2" | "RMB" | "RIGHTMOUSE" => Some(0x02), "MOUSE3" | "MMB" => Some(0x04), "MOUSE4" | "XBUTTON1" => Some(0x05), "MOUSE5" | "XBUTTON2" => Some(0x06), @@ -428,6 +430,8 @@ fn vk_name(vk: u8) -> String { return (vk as char).to_string(); } match vk { + 0x01 => "Mouse1".to_owned(), + 0x02 => "Mouse2".to_owned(), 0x04 => "Mouse3".to_owned(), 0x05 => "Mouse4".to_owned(), 0x06 => "Mouse5".to_owned(), @@ -583,7 +587,7 @@ fn build_bindings(custom: &HashMap) -> Bindings { push_bind(&["map"], b'M', MENU); push_bind(&["a", "sprint"], 0x10, A); push_bind(&["confirm"], 0x0D, A); - push_bind(&["x", "jump"], 0x20, X); + push_bind(&["x", "jump", "melee"], 0x20, X); push_bind(&["b", "reload"], b'R', B); push_bind(&["cancel"], 0x08, B); push_bind(&["y", "enter_vehicle"], b'F', Y); @@ -1517,6 +1521,8 @@ fn smooth_mouse_stick(dx: f32, dy: f32, sens: f32, invert_y: bool) -> (f32, f32) fn bound_vk_held(keys: &[KeyState], mb: u32, vk: u8) -> bool { match vk { + 0x01 => mb & MB_LEFT != 0, + 0x02 => mb & MB_RIGHT != 0, 0x04 => mb & MB_MIDDLE != 0, 0x05 => mb & MB_X1 != 0, 0x06 => mb & MB_X2 != 0, @@ -1524,6 +1530,11 @@ fn bound_vk_held(keys: &[KeyState], mb: u32, vk: u8) -> bool { } } +/// Whether `vk` names a mouse button (Mouse1..Mouse5), not a keyboard key. +fn is_mouse_vk(vk: u8) -> bool { + matches!(vk, 0x01 | 0x02 | 0x04 | 0x05 | 0x06) +} + /// `F5` temporarily overrides `keyboard_driving` back to on-foot bindings /// (useful in scripted vehicle seats where the game expects normal prompts). static FORCE_ON_FOOT_MODE: AtomicBool = AtomicBool::new(false); @@ -1569,6 +1580,8 @@ fn eval_buttons( || cfg.focus_vks.contains(&vk) || (handbrake_active && cfg.handbrake_vk == vk) || (direct_active && cfg.right_stick_mouse_vk == vk) + || cfg.left_trigger_vk == vk + || cfg.right_trigger_vk == vk }; if mb & MB_MIDDLE != 0 && !mouse_claimed(0x04) { buttons |= RIGHT_STICK; @@ -1667,8 +1680,21 @@ pub(super) fn mnk_pad(keys: &[KeyState]) -> PadState { buttons |= RIGHT; } - let mut left_trigger = if mb & MB_RIGHT != 0 { 1.0 } else { on(cfg.left_trigger_vk) }; - let mut right_trigger = if mb & MB_LEFT != 0 { 1.0 } else { on(cfg.right_trigger_vk) }; + // Triggers: a mouse-button bind (e.g. `rt = Mouse4`) is read from the + // mouse buttons; the hard LMB/RMB claims only stand while that trigger + // is not itself bound to a mouse button, so rebinding a trigger frees + // the mouse button it used to own. + let bound_trigger = |vk: u8, hard_bit: u32| -> f32 { + if bound_vk_held(keys, mb, vk) { + 1.0 + } else if !is_mouse_vk(vk) && mb & hard_bit != 0 { + 1.0 + } else { + 0.0 + } + }; + let mut left_trigger = bound_trigger(cfg.left_trigger_vk, MB_RIGHT); + let mut right_trigger = bound_trigger(cfg.right_trigger_vk, MB_LEFT); let mut left_y = on(cfg.move_up) - on(cfg.move_down); if driving { apply_driving_overrides( @@ -1900,6 +1926,24 @@ mod tests { assert_eq!(vk_name(0x06), "Mouse5"); } + #[test] + fn melee_alias_and_mouse_button_trigger_binds() { + assert_eq!(parse_vk("Mouse1"), Some(0x01)); + assert_eq!(parse_vk("LMB"), Some(0x01)); + assert_eq!(parse_vk("Mouse2"), Some(0x02)); + assert_eq!(vk_name(0x01), "Mouse1"); + assert_eq!(vk_name(0x02), "Mouse2"); + // `melee = Mouse4`: Mouse4 presses X (melee), not the LB fallback. + let map = parse_ini_text("melee = Mouse4\n"); + let b = build_bindings(&map); + assert_eq!(eval_buttons(&b, &[], MB_X1, false, false, false), X); + // `rt = Mouse4`: Mouse4 is claimed by the trigger, no LB fallback. + let map = parse_ini_text("rt = Mouse4\n"); + let b = build_bindings(&map); + assert_eq!(b.right_trigger_vk, 0x05); + assert_eq!(eval_buttons(&b, &[], MB_X1, false, false, false), 0); + } + #[test] fn driving_space_maps_to_a_handbrake_without_on_foot_binding() { let cfg = default_bindings(); diff --git a/docs/controls.example.ini b/docs/controls.example.ini index fb09972..4121428 100644 --- a/docs/controls.example.ini +++ b/docs/controls.example.ini @@ -18,9 +18,16 @@ move_left = A move_right = D ; Actions +; Mouse buttons are bindable everywhere: Mouse1 (LMB), Mouse2 (RMB), +; Mouse3 (wheel click), Mouse4 (back), Mouse5 (forward). Example: +; melee = Mouse4 +; A bound mouse button does ONLY that action (Mouse4 stops opening the +; weapon wheel, Mouse5 stops being RB, and binding a trigger to a mouse +; button, e.g. shoot_key = Mouse4, frees LMB/RMB from their hard claim). sprint = SHIFT confirm = ENTER jump = SPACE +; melee = Mouse4 reload = R cancel = BACKSPACE enter_vehicle = F @@ -34,7 +41,7 @@ menu = ESC pause = P map = M -; Keyboard trigger fallbacks (Mouse LMB = shoot/gas, RMB = aim/brake are always active when mouse is captured) +; Triggers (LMB = shoot/gas, RMB = aim/brake while that trigger is not bound to a mouse button) aim_key = Z shoot_key = X From 7a30255bb4c94f24dcb0a23716c367190d6fe1ad Mon Sep 17 00:00:00 2001 From: gamingwithhomie Date: Sun, 6 Dec 2026 05:38:10 +0530 Subject: [PATCH 8/8] Docs: pagefile/commit check for -1073740791; first-person-stuck fix --- docs/troubleshooting-and-crashes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/troubleshooting-and-crashes.md b/docs/troubleshooting-and-crashes.md index a667522..3faa5c0 100644 --- a/docs/troubleshooting-and-crashes.md +++ b/docs/troubleshooting-and-crashes.md @@ -47,6 +47,7 @@ Use this guide to diagnose any startup error, exit code, or mid-game crash in se 4. If a specific new shader hash still faults on an experimental AMD driver, you can skip it via `$env:LARP_LEAVE_OUT = '<16-char-hex-hash>'`. ### C. `exit -1073740791` (`WaterTarget: no host copy of the texture; stopping`) +- Also check your Windows **commit limit**: this title allocates far beyond physical RAM. Press `Win+R`, run `SystemPropertiesPerformance.exe` → Advanced → Virtual memory: use **System managed size**, or a custom pagefile of at least **2× your physical RAM**, on an SSD with free space. A small/disabled pagefile on 16–32 GB machines is a known cause of this exit (and of multi-second freezes while Windows expands commit). - **Cause:** `larp` could not allocate the host D3D12 texture/readback copy for `WaterTarget` at startup. - **Fix 1 (90% of cases — Laptops & Desktop CPUs with iGPUs like Ryzen 7000/9000 or Intel non-F):** - Windows routed `larp.exe` to your integrated Radeon/Intel graphics instead of your dedicated GPU! @@ -133,6 +134,8 @@ Match the **`+0x...`** offset after `dll` to the table below: - The log (`logs\play.log`) now tells you exactly: search `controls.ini` — either `loaded custom controls.ini path=... entries=N` or `no controls.ini found (default keybinds in use)` listing every path searched. Put `controls.ini` next to `options.ini` (the `Larp\` folder root), or set `LARP_CONTROLS_INI` to its full path. In-game, **F10 → Controls** (v1.1.3+) edits and saves it live. - **Pipelines Compile Again on Every Launch (Same Version):** - Check the release's **Shader/pipeline cache** label first (NONE updates never recompile). If it still recompiles: (1) you are launching from a different folder than last time — `cache\` lives in the `Larp\` folder, so don't alternate between two extracts; (2) something deletes `cache\` (antivirus cleanup, extracting updates over the folder with "delete extra files"); (3) you updated across a FULL-cache release. Copy `cache\` + `data\` + `game-dir.txt` when moving folders. +- **Stuck in First-Person View After an Update:** + - It's a saved setting, not your save file: press **F7** to toggle it back, or set `first_person = off` in `data\7952987A\settings.ini` (F10 → Picture → *First-person view* also shows its state). An accidental F7 press is the usual cause. - **Pixelated / Blocky Shadows (Worse Above 1080p):** - Try in order: in-game RT Local Shadows on **Low**, `series-s.cmd` (its shadow setup differs), and F10 *Texture detail* at full. If the blocks appear only while pipelines are still compiling at launch and clear after a minute, that's pipeline warm-up, not settings. Still blocky afterwards? Attach `zip-logs` — we need the first `refused`/`dropped` lines. - **Stutter Every Few Seconds (Good Average FPS):**