diff --git a/HANDOFF.md b/HANDOFF.md index 62998ebda1..f0d1b1ede7 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1775,6 +1775,56 @@ to an outside server at every crash (`hle/netoff.rs`: the title's WinHTTP / Wins 4 GiB window – a redesign of how shaders reach title memory. - XDefiant, Fortnite, Unicorn Overlord and Minecraft were **not** run after these changes (only the test suites). +## Console CPU instructions the PC lacks (2026-11-23) +A title on an Intel CPU before Ice Lake / Alder Lake dies with 0xC000001D (illegal instruction) in its own code +right after its first `CreateShaderResourceView` (the first descriptor written into title memory). `insn.rs` decodes +the Zen 2 instructions such a CPU lacks – `clwb` (Intel: Ice Lake+), `clzero`, `rdpru`, `monitorx` / `mwaitx` +(AMD only), `rdpid` – and the vectored handler (`eh::emulate_console_only`) emulates them and steps over +(`clwb` / `monitorx` / `mwaitx`: nothing, the PC's memory is coherent; `clzero`: 64 zero bytes at rAX; `rdpru`: +QueryPerformanceCounter; `rdpid`: the processor number). Logged once per instruction. Any other illegal instruction +(and `ud2`, a title's own trap) is logged with its 16 code bytes, in the first-chance handler and in the crash line. +SHA-NI is not emulated (also missing on those CPUs): add it if a title's code bytes show `0F 38 C8..CD`. +- With both emulated a title shows its first frame on an i5/i7 Coffee Lake + RTX 3060 too (`first game frame + shown (3840x2160)`), then dies on an assert right after `chad.dll!XDspConnectWithMaximumStreamLimit` returned the + stub's E_NOTIMPL. `chad.dll` (the console's audio DSP offload, `XDsp*`) is routed to `acphal` now: every XDsp + function is acknowledged (S_OK; Connect writes a fake handle into its last pointer argument – the signatures are not + published, the first call of each is logged with its arguments). `XCL_TRACE_IMPORTS=chad` traces stubs named by + prefix too (arguments and result), for the next unknown DLL. + +## The memory wall, and the texture computer's slot 10 (2026-11-23) +With chad.dll acknowledged the title on the i5/i7 + RTX 3060 (32 GB) runs far past its first frame (local user, +~2000 graphics pipelines, mesh shaders, the video-memory arena), then dies writing to address 0 in its thread start-up +code (`+0x2215c35`, `rbx = rbp = 0`) – a path every other thread took. Its own crash reporter says why: `memory.load_percent +84`, `system.memory.swap.free 801176` of `48801508` KB. The page file (48 GB) is full, the commit charge about 75 GB; the +three `graphics PSO rejected (0x8007000e)` just before are the driver's E_OUTOFMEMORY. An allocation returned NULL. +- `memstat.rs`: one line, `memory: process commit … (working set …); system commit … of …, … of RAM free (… % load); + video … of … local, … of … shared; the title asked for graphics …, Windows …, heaps …, physical pages …; sparse windows + … tiles (…) in … pools`, logged at every crash (`eh::unhandled_filter`), when the process ends with an error, and from + a thread whenever the process's commit grew by a GiB (every 30 s at most). "The title asked for" are gross counters + (`memstat::note` in kernelx's commit paths: sparse / UMA graphics memory, Windows commits, XMemAlloc heaps, the + homes of physical pages); video memory is `IDXGIAdapter3::QueryVideoMemoryInfo` (local, and the non-local segment: + system memory the driver spills into when the pools of title memory outgrow the card – on a 12 GB card every GiB of + title memory beyond it costs a second GiB of commit). The next run says whose memory it is. +- The crash line has the code bytes at RIP for every exception now (`(code bytes: …)`), not only illegal instructions. +- `xg_xs.dll` of a GDK (an older one: no `XGSuggestSwizzleMode`), disassembled: `XGCreateTextureComputer` is + `(desc, out)` → the factory at `+0x5dd0`; the computer's vtable (at `+0x50b68`, referenced from `+0x1852`) has 13 slots. + #10 is **GetResourceTiling** – `ID3D12Device::GetResourceTiling`'s six arguments, for the computer's resource: it reads + `*pNumSubresourceTilings`, writes a `D3D12_PACKED_MIP_INFO` (12 bytes), a `D3D12_TILE_SHAPE` (12), `D3D12_SUBRESOURCE_TILING`s + (12 each, indexed by D3D12 subresource skipping the packed levels). E_FAIL "Resource does not have a 64KB swizzle mode + compatible with tiled resources" unless the mode is 8–11 / 16–19 / 24–27; E_NOTIMPL "Texture1D and Texture3D is not + implemented yet"; the standard tile in elements by their size (256×256 … 64×64 for 1 … 16 bytes, halved per MSAA + doubling), reported in texels; a level's tiling is its padded size over the tile, its start tile the level's offset + in 64 KiB tiles plus the slice's; the packed levels one tile at the first one's offset. `xg::get_resource_tiling` + does this (test `resource_tiling_of_a_64kb_texture`). The guess merged from ivall/xcl#169 (GetSubresourceLayout / + Offset, sniffing which arguments are pointers) is gone: with the real arguments it answered E_INVALIDARG by luck (the + "plane" was the low half of a pointer) and would have written 0x70 bytes over a 12-byte tile shape otherwise. + #11 is `GetDescriptor(UINT plane, void* descriptor)`: "pDescriptor cannot be NULL", "PlaneIndex must be less than 3", + copies the plane's 32-byte hardware texture descriptor (not modelled, still a stub). #12 returns a flag byte of the + resource (bit 27 of a dword at `+0x2818`). A title's texture streaming calls #10 for every texture it places in a + tiled pool (179 calls in one run). +- Scripts for the DLL (in the session's scratch, not the repo): a PE reader (`fo(va)`, `q(va)`), a scan of `.rdata` for + runs of code pointers (vtables), `x86_64-w64-mingw32-objdump -d -M intel --start-address … --stop-address …`. + ## Next steps (priority) Little is left to do without the exe – the rest needs an actual run of the game. 1. Once the user has a legal game exe: `xcl inspect`, `xcl run`, analysis of `report.json` diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 0102a29d74..566a677c8c 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -61,6 +61,12 @@ pub fn set_title_filter(f: usize) -> usize { TITLE_FILTER.swap(f, Ordering::AcqRel) } +/// The first 16 code bytes at `rip`, as hex (as far as they are readable). +unsafe fn code_at(rip: usize) -> String { + let n = (1..=16).rev().find(|&n| crate::gpu::shader::readable(rip, n)).unwrap_or(0); + std::slice::from_raw_parts(rip as *const u8, n).iter().map(|b| format!("{b:02x}")).collect::>().join(" ") +} + unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i32 { crate::hle::d3d12x::real::log_device_removed(); if !info.is_null() && !(*info).ExceptionRecord.is_null() { @@ -76,6 +82,9 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i }; extra = format!(" ({op} at address {:#x})", rec.ExceptionInformation[1]); } + // the faulting instruction, for any exception: the registers alone rarely say what was + // dereferenced (an access violation in a title's thread start-up: which field of what) + extra.push_str(&format!(" (code bytes: {})", code_at(addr))); let ctx = (*info).ContextRecord; let regs = if ctx.is_null() { String::new() @@ -101,6 +110,7 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i modules::describe_address(addr) ); crate::xlog_error!("{msg}"); + crate::memstat::log(); crate::report::write_final(Some(msg)); crate::log::flush(); } @@ -123,6 +133,7 @@ unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 let (tid, stack) = (windows_sys::Win32::System::Threading::GetCurrentThreadId(), stack_callers_n(&probe as *const usize as usize, 16)); if status != 0 { crate::xlog_error!("process ends with status {status:#x} (thread {tid}); on the stack: {stack}"); + crate::memstat::log(); dump_threads(); } else { crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}"); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index ff20199bef..974a49fe46 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1207,6 +1207,14 @@ impl State { } } +/// (tiles of title memory with video memory, pool heaps holding them) for the memory line +/// (None: no sparse windows, or the state is busy – a crash report must not wait for it). +pub fn stats() -> Option<(usize, usize)> { + let g = STATE.try_lock().ok()?; + let s = g.as_ref()?; + Some((s.mapped.len(), s.pools.len())) +} + /// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write /// has to reach the GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 18a61ddc49..7f85ccff10 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -164,6 +164,7 @@ const MEM_64K_PAGES: u32 = 0x2040_0000; unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); if !q.is_null() { + crate::memstat::note(crate::memstat::GRAPHICS, n); crate::hle::d3d12x::sparse::committed(q as usize, n); } q @@ -202,10 +203,12 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: }; let rounded = size.max(1).div_ceil(align) * align; if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("VirtualAlloc (graphics, sparse VRAM)", 0, rounded, t as u64, p, q); return q as *mut c_void; } if let Some(q) = uma.and_then(|u| u.alloc(rounded, align)) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("VirtualAlloc (graphics, UMA)", 0, rounded, t as u64, p, q as usize); return q as *mut c_void; } @@ -235,7 +238,11 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: return q; } } - let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); + let kind = sanitize_alloc_type(t); + let q = mem::VirtualAlloc(addr, size, kind, sanitize_protect(p)); + if !q.is_null() && kind & mem::MEM_COMMIT != 0 { + crate::memstat::note(crate::memstat::WINDOWS, size); + } trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); q } @@ -401,6 +408,9 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut let a = XAllocAttrs::decode(attrs); if a.memory_type == 0 { let q = aligned_heap_alloc(size, 1usize << a.alignment.clamp(4, usize::BITS - 2)); + if !q.is_null() { + crate::memstat::note(crate::memstat::HEAP, size); + } trace_mem("XMemAlloc", 0, size, attrs, 0, q as usize); return q; } @@ -410,14 +420,20 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut }; // Graphics memory types live in the sparse VRAM pool (fallback to coherent UMA, then Windows). if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("XMemAlloc (graphics, sparse VRAM)", 0, rounded, attrs, 0, q); return q as *mut c_void; } if let Some(q) = crate::gpu::uma::get().and_then(|u| u.alloc(rounded, align)) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("XMemAlloc (graphics, UMA)", 0, rounded, attrs, 0, q as usize); return q as *mut c_void; } - mem::VirtualAlloc(std::ptr::null(), rounded, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE) + let q = mem::VirtualAlloc(std::ptr::null(), rounded, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE); + if !q.is_null() { + crate::memstat::note(crate::memstat::WINDOWS, rounded); + } + q } pub unsafe extern "system" fn XMemFreeDefault(p: *mut c_void, attrs: u64) { @@ -800,6 +816,7 @@ unsafe fn home_again(home: usize) -> Option { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; } + crate::memstat::note(crate::memstat::PHYSICAL, PHYS_PAGE); crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); } Some(home) @@ -819,6 +836,7 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); return false; } + crate::memstat::note(crate::memstat::PHYSICAL, len); crate::hle::d3d12x::sparse::committed(home, len); true } @@ -975,6 +993,9 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } + if fresh { + crate::memstat::note(crate::memstat::PHYSICAL, PHYS_PAGE); + } let home = page_home(p).unwrap(); if committed_page(home) { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 22b9c82d6c..4471e82a1e 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -100,6 +100,7 @@ pub fn host_main(boot_path: &Path) -> i32 { } crate::eh::install_crash_handler(); crate::eh::start_probes(); + crate::memstat::start(); HOST_MODE.store(true, Ordering::Release); let main = match crate::loader::load_main(&boot.exe_path) { diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index c0290744db..c5dd5e99ba 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -8,6 +8,7 @@ #[macro_use] pub mod log; pub mod manifest; +pub mod memstat; pub mod config; pub mod disasm; pub mod eh; diff --git a/crates/xcl/src/memstat.rs b/crates/xcl/src/memstat.rs new file mode 100644 index 0000000000..b085da5cc9 --- /dev/null +++ b/crates/xcl/src/memstat.rs @@ -0,0 +1,129 @@ +//! Where the process's memory goes: one line for the log – at a crash, when the process ends +//! with an error, and while the title runs whenever its commit charge has grown by a GiB +//! (at most every 30 s). A title that runs out of memory dies in an allocation of its own, +//! far from the cause (a write to address 0 in a thread's start-up, a PSO the driver refuses +//! with E_OUTOFMEMORY); the line says whose memory it is: the process's commit against the +//! system's limit, the video memory in use (local, and the system memory the driver spills +//! into), what the title asked kernelx for (graphics memory, Windows allocations, heaps) and +//! the tiles of title memory that have video memory. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::ID3D12Device; +use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter3, IDXGIFactory4, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, DXGI_QUERY_VIDEO_MEMORY_INFO}; +use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; +use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// Kinds of memory the title asks kernelx for (`note`). +pub const GRAPHICS: usize = 0; +pub const WINDOWS: usize = 1; +pub const HEAP: usize = 2; +pub const PHYSICAL: usize = 3; + +/// Bytes the title asked for since the start, by kind (gross: frees are not taken off). +static TITLE: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// The title committed `bytes` of `kind` (`GRAPHICS`: memory that gets video memory – the +/// sparse windows, UMA; `WINDOWS`: an ordinary VirtualAlloc commit; `HEAP`: XMemAlloc; +/// `PHYSICAL`: the homes of its physical pages). +pub fn note(kind: usize, bytes: usize) { + TITLE[kind].fetch_add(bytes as u64, Ordering::Relaxed); +} + +fn gib(b: u64) -> String { + format!("{:.1} GiB", b as f64 / (1u64 << 30) as f64) +} + +/// (commit charge, working set) of the process +fn process() -> Option<(u64, u64)> { + unsafe { + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of::() as u32; + (K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0).then_some((c.PrivateUsage as u64, c.WorkingSetSize as u64)) + } +} + +/// (commit in use, commit limit, physical memory free, load %) of the system +fn system() -> Option<(u64, u64, u64, u32)> { + unsafe { + let mut m: MEMORYSTATUSEX = std::mem::zeroed(); + m.dwLength = std::mem::size_of::() as u32; + (GlobalMemoryStatusEx(&mut m) != 0).then_some((m.ullTotalPageFile.saturating_sub(m.ullAvailPageFile), m.ullTotalPageFile, m.ullAvailPhys, m.dwMemoryLoad)) + } +} + +static ADAPTER: Mutex> = Mutex::new(None); + +/// The device's adapter, found once (None: no device yet, or the lock is held – a crash in a +/// thread that holds it must not wait on it). +fn adapter() -> Option { + let mut g = ADAPTER.try_lock().ok()?; + if g.is_none() { + let raw = crate::hle::d3d12x::real::device_raw(); + if raw.is_null() { + return None; + } + let dev: &ID3D12Device = unsafe { ID3D12Device::from_raw_borrowed(&raw)? }; + let luid = unsafe { dev.GetAdapterLuid() }; + let factory: IDXGIFactory4 = unsafe { CreateDXGIFactory1() }.ok()?; + *g = unsafe { factory.EnumAdapterByLuid::(luid) }.ok(); + } + g.clone() +} + +/// ((in use, budget) local video memory, (in use, budget) non-local: system memory the driver uses) +fn video() -> Option<((u64, u64), (u64, u64))> { + let a = adapter()?; + let mut local = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + unsafe { a.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut local) }.ok()?; + unsafe { a.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) }.ok()?; + Some(((local.CurrentUsage, local.Budget), (shared.CurrentUsage, shared.Budget))) +} + +/// The line: `memory: process commit 61.2 GiB (working set 24.1 GiB); system commit 74.9 of +/// 79.5 GiB, 5.1 GiB of RAM free (84 % load); video 11.3 of 11.6 GiB local, 18.0 of 15.9 GiB +/// shared; the title asked for graphics 20.1 GiB, Windows 1.2 GiB, heaps 3.4 GiB; sparse +/// windows 180224 tiles (11.0 GiB) in 176 pools`. +pub fn line() -> String { + let mut parts = Vec::new(); + if let Some((commit, ws)) = process() { + parts.push(format!("process commit {} (working set {})", gib(commit), gib(ws))); + } + if let Some((used, limit, free, load)) = system() { + parts.push(format!("system commit {} of {}, {} of RAM free ({load} % load)", gib(used), gib(limit), gib(free))); + } + if let Some(((lu, lb), (su, sb))) = video() { + parts.push(format!("video {} of {} local, {} of {} shared", gib(lu), gib(lb), gib(su), gib(sb))); + } + let t = TITLE.each_ref().map(|a| a.load(Ordering::Relaxed)); + parts.push(format!("the title asked for graphics {}, Windows {}, heaps {}, physical pages {}", gib(t[GRAPHICS]), gib(t[WINDOWS]), gib(t[HEAP]), gib(t[PHYSICAL]))); + if let Some((tiles, pools)) = crate::hle::d3d12x::sparse::stats() { + parts.push(format!("sparse windows {tiles} tiles ({}) in {pools} pools", gib((tiles as u64) << 16))); + } + format!("memory: {}", parts.join("; ")) +} + +/// The log line now (a crash, the process ending with an error). +pub fn log() { + crate::xlog_info!("{}", line()); +} + +/// A thread that logs the line whenever the process's commit charge has grown by a GiB since +/// the last line, looking every 30 s. +pub fn start() { + let _ = std::thread::Builder::new().name("xcl-memstat".into()).spawn(|| { + let mut last = 0u64; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + let Some((commit, _)) = process() else { continue }; + if commit >= last + (1 << 30) { + last = commit; + log(); + } + } + }); +}