diff --git a/README.md b/README.md index f55cad72e..fc4d6485b 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ next steps: | **PE loader** | ✅ | relocations, imports by name / ordinal / delay-load, TLS callbacks, exception tables, game DLLs, data-driven import routing (HLE / Windows / stub) | the game's 16 console DLLs load with 0 unresolved imports | | **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | | **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | +| **DirectStorage memory inputs** | ✅ | deferred zero-filled mappings are readable as memory sources and physical-page arrays; read preparation leaves other reservations and existing protections unchanged | CPU regressions for deferred sources, owned page snapshots and protected ranges | | **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | ### System services diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2a6300541..680e11fc1 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -713,11 +713,27 @@ unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result bool, prepare: impl FnOnce() -> bool) -> bool { + if read() { return true; } + // Another thread may have committed the page before preparation gets its lock. + // Retry the read itself even when this caller did not materialize a page. + prepare(); + read() +} + +fn readable_source(at: usize, len: usize) -> bool { + len <= 256 << 20 && read_prepared(|| crate::gpu::shader::readable(at, len), || crate::hle::kernelx::lazy::prepare_read(at, len)) +} + unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut done = 0usize; - at != 0 && ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out as *mut c_void, len, &mut done) != 0 && done == len + if at == 0 { return false; } + read_prepared( + || ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out as *mut c_void, len, &mut done) != 0 && done == len, + || crate::hle::kernelx::lazy::prepare_read(at, len), + ) } /// Whether `n` bytes at `p` are committed, writable memory. @@ -798,7 +814,7 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us return Err(E_ACCESS_VIOLATION); } } else { - if !crate::gpu::shader::readable(r.source as usize, r.source_size as usize) { + if !readable_source(r.source as usize, r.source_size as usize) { return Err(E_ACCESS_VIOLATION); } if !b.is_empty() { @@ -1392,6 +1408,10 @@ unsafe extern "system" fn queue_query(p: *mut c_void, out: *mut u8) { std::ptr::copy_nonoverlapping(info.as_ptr(), out, info.len()); } +#[cfg(test)] +#[path = "dstorage_lazy_input_tests.rs"] +mod lazy_input_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/xcl/src/hle/dstorage_lazy_input_tests.rs b/crates/xcl/src/hle/dstorage_lazy_input_tests.rs new file mode 100644 index 000000000..06782f7e6 --- /dev/null +++ b/crates/xcl/src/hle/dstorage_lazy_input_tests.rs @@ -0,0 +1,250 @@ +use super::*; +use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, + MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, + PAGE_READWRITE, +}; + +const PAGE: usize = crate::hle::kernelx::PHYS_PAGE_SIZE; + +struct Region(usize, usize); + +impl Region { + unsafe fn reserve(pages: usize, deferred: bool) -> Self { + let at = VirtualAlloc(std::ptr::null(), pages * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(at, 0); + if deferred { + for k in 0..pages { + crate::hle::kernelx::lazy::mark(at + k * PAGE); + } + } + Self(at, pages * PAGE) + } + + unsafe fn info(&self) -> MEMORY_BASIC_INFORMATION { + let mut info = std::mem::zeroed(); + assert_ne!( + VirtualQuery( + self.0 as *const c_void, + &mut info, + std::mem::size_of_val(&info) + ), + 0 + ); + info + } +} + +impl Drop for Region { + fn drop(&mut self) { + unsafe { + // Clear any retained lazy mark while this owned reservation still exists. + VirtualFree(self.0 as *mut c_void, self.1, MEM_DECOMMIT); + crate::hle::kernelx::lazy::ensure(self.0, self.1); + assert_ne!(VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE), 0); + } + } +} + +unsafe fn copy_from(at: usize, destination: &mut [u8]) -> Result<(), HRESULT> { + let request = Request { + options: SOURCE_MEMORY_BIT, + destination: destination.as_mut_ptr() as u64, + destination_size: destination.len() as u32, + source: at as u64, + source_size: destination.len() as u32, + ..Default::default() + }; + assert_eq!(request.check(true), Ok(())); + execute(&request, None, None, None) +} + +#[test] +fn a_deferred_zero_memory_source_is_readable_to_directstorage() { + unsafe { + let region = Region::reserve(1, true); + assert_eq!(region.info().State, MEM_RESERVE); + let mut destination = [0xCCu8; 64]; + assert_eq!(copy_from(region.0 + 8, &mut destination), Ok(())); + assert_eq!(destination, [0; 64]); + assert_eq!(region.info().State, MEM_COMMIT); + } +} + +#[test] +fn a_deferred_page_array_snapshot_owns_the_initial_zero_entries() { + unsafe { + let region = Region::reserve(2, true); + let table = region.0 + PAGE - std::mem::size_of::(); + assert_eq!(region.info().State, MEM_RESERVE); + let snapshot = snapshot_page_array(table as u64, (PAGE - 4) as u16, 8) + .expect("a mapped lazy page array logically holds zeros"); + assert_eq!(snapshot, [0, 0]); + (table as *mut usize).write(16); + ((table + std::mem::size_of::()) as *mut usize).write(32); + assert_eq!(snapshot, [0, 0], "the enqueue snapshot remains owned"); + assert_eq!( + snapshot_page_array(table as u64, 0, PAGE as u32 * 2), + Ok(vec![16, 32]) + ); + } +} + +#[test] +fn an_untracked_reservation_stays_unreadable_and_unmodified() { + unsafe { + let region = Region::reserve(1, false); + let mut destination = [0xCCu8; 64]; + assert_eq!( + copy_from(region.0, &mut destination), + Err(E_ACCESS_VIOLATION) + ); + assert_eq!(destination, [0xCC; 64]); + assert_eq!( + snapshot_page_array(region.0 as u64, 0, 8), + Err(E_ACCESS_VIOLATION) + ); + assert_eq!(region.info().State, MEM_RESERVE); + assert_eq!( + snapshot_page_array((usize::MAX - 3) as u64, 0, 8), + Err(E_ACCESS_VIOLATION) + ); + } +} + +#[test] +fn deferred_read_preparation_does_not_widen_a_partly_committed_page() { + unsafe { + let region = Region::reserve(1, true); + assert!( + !VirtualAlloc(region.0 as *const c_void, 4096, MEM_COMMIT, PAGE_READONLY).is_null() + ); + let mut destination = [0xCCu8; 64]; + assert_eq!( + copy_from(region.0 + 4096, &mut destination), + Err(E_ACCESS_VIOLATION) + ); + assert_eq!( + snapshot_page_array((region.0 + 4096) as u64, 0, 8), + Err(E_ACCESS_VIOLATION) + ); + assert_eq!(destination, [0xCC; 64]); + let first = region.info(); + assert_eq!( + (first.State, first.Protect, first.RegionSize), + (MEM_COMMIT, PAGE_READONLY, 4096) + ); + let mut rest = std::mem::zeroed(); + assert_ne!( + VirtualQuery( + (region.0 + 4096) as *const c_void, + &mut rest, + std::mem::size_of_val(&rest) + ), + 0 + ); + assert_eq!(rest.State, MEM_RESERVE); + } +} + +#[test] +fn deferred_read_preparation_preserves_explicit_page_protections() { + unsafe { + for protect in [PAGE_READONLY, PAGE_NOACCESS, PAGE_READWRITE | PAGE_GUARD] { + let region = Region::reserve(1, true); + assert!( + !VirtualAlloc(region.0 as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE) + .is_null() + ); + let mut old = 0; + assert_ne!( + VirtualProtect(region.0 as *const c_void, PAGE, protect, &mut old), + 0 + ); + let mut destination = [0xCCu8; 64]; + let expected = if protect == PAGE_READONLY { + Ok(()) + } else { + Err(E_ACCESS_VIOLATION) + }; + assert_eq!(copy_from(region.0, &mut destination), expected); + if expected.is_ok() { + assert_eq!(destination, [0; 64]); + assert_eq!(snapshot_page_array(region.0 as u64, 0, 8), Ok(vec![0])); + } else { + assert_eq!(destination, [0xCC; 64]); + assert_eq!( + snapshot_page_array(region.0 as u64, 0, 8), + Err(E_ACCESS_VIOLATION) + ); + } + assert_eq!(region.info().Protect, protect); + } + } +} + +#[test] +fn a_read_retries_when_another_thread_materializes_the_deferred_page() { + use std::sync::{Arc, Barrier}; + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + + unsafe { + for native in [false, true] { + let region = Region::reserve(1, true); + let at = region.0; + let begin = Arc::new(Barrier::new(2)); + let done = Arc::new(Barrier::new(2)); + let other = { + let begin = Arc::clone(&begin); + let done = Arc::clone(&done); + std::thread::spawn(move || { + begin.wait(); + assert_eq!((at as *const u8).read_volatile(), 0); + done.wait(); + }) + }; + let mut attempts = 0; + let mut bytes = [0xCCu8; 16]; + let ok = read_prepared( + || { + attempts += 1; + if native { + let mut copied = 0; + ReadProcessMemory( + GetCurrentProcess(), + at as *const c_void, + bytes.as_mut_ptr() as *mut c_void, + bytes.len(), + &mut copied, + ) != 0 + && copied == bytes.len() + } else { + crate::gpu::shader::readable(at, bytes.len()) + } + }, + || { + begin.wait(); + done.wait(); + let materialized = crate::hle::kernelx::lazy::prepare_read(at, 16); + assert!( + !materialized, + "the other thread already removed the lazy mark" + ); + materialized + }, + ); + other.join().unwrap(); + assert!( + ok, + "readable/native reads must recheck after a competing first touch" + ); + assert_eq!(attempts, 2); + if native { + assert_eq!(bytes, [0; 16]); + } + assert_eq!(copy_from(at, &mut bytes), Ok(())); + assert_eq!(bytes, [0; 16]); + } + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a4..7004ea263 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -17,7 +17,7 @@ use std::sync::{Once, RwLock}; use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; use windows_sys::Win32::System::Memory::{ - VirtualAlloc, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, + VirtualAlloc, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, }; @@ -100,6 +100,33 @@ pub fn ensure(p: usize, len: usize) { } } +/// Materialize tracked zero pages for a native read, which cannot invoke our fault handler. +/// Existing committed protections and untracked reservations must remain unchanged. +/// True means at least one page was committed; the caller must still validate/read its range. +pub fn prepare_read(p: usize, len: usize) -> bool { + let Some(end) = p.checked_add(len) else { return false }; + if len == 0 { return false; } + let mut lazy = LAZY.write().unwrap_or_else(|e| e.into_inner()); + let pages: Vec = lazy.range((p & !(PAGE - 1))..end).copied().collect(); + let mut committed = false; + for page in pages { + let Some(page_end) = page.checked_add(PAGE) else { continue }; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + unsafe { + if VirtualQuery(page as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 + || m.State != MEM_RESERVE || m.BaseAddress as usize > page + || !(m.BaseAddress as usize).checked_add(m.RegionSize).is_some_and(|end| end >= page_end) { + continue; + } + if !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() { + lazy.remove(&page); + committed = true; + } + } + } + committed +} + #[cfg(test)] mod tests { use super::*;