diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 3b85cfac35..9c32d28f8d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -528,10 +528,12 @@ fn is_writable(va: usize, bytes: usize) -> bool { } let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const std::ffi::c_void, &mut m, std::mem::size_of_val(&m)) } != 0; - found + (found && m.State == MEM_COMMIT && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && m.BaseAddress as usize + m.RegionSize >= va + bytes + && m.BaseAddress as usize + m.RegionSize >= va + bytes) + // (pages XCL made read-only: the zeroing faults and is let through, `XCL_GUEST_WRITE_GUARD=1`) + || crate::hle::kernelx::guest_write::writable(va, bytes) } const ILLEGAL_INSTRUCTION: u32 = 0xC000_001D; diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index f92fc5dafd..cf3e30bde9 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -141,10 +141,12 @@ unsafe fn write_now_in(va: usize, words: &[u32], run: &dyn Fn(usize, usize) -> O if !crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); - if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { - return; - } - if m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize + m.RegionSize) < va + bytes { + let rw = VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 + && (m.BaseAddress as usize + m.RegionSize) >= va + bytes; + // (pages XCL made read-only: the store faults and is let through, `XCL_GUEST_WRITE_GUARD=1`) + if !rw && !crate::hle::kernelx::guest_write::writable(va, bytes) { return; } } @@ -181,9 +183,10 @@ unsafe fn u64_writable_now(va: usize) -> bool { if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { return false; } - m.Protect & PAGE_GUARD == 0 + (m.Protect & PAGE_GUARD == 0 && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && (m.BaseAddress as usize).saturating_add(m.RegionSize) >= end + && (m.BaseAddress as usize).saturating_add(m.RegionSize) >= end) + || crate::hle::kernelx::guest_write::writable(va, 8) } /// An 8-byte aligned 64-bit value at `va`, if the memory is still there and writable. @@ -220,10 +223,11 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; - found + (found && m.State == MEM_COMMIT && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && m.BaseAddress as usize + m.RegionSize >= va + bytes + && m.BaseAddress as usize + m.RegionSize >= va + bytes) + || crate::hle::kernelx::guest_write::writable(va, bytes) } /// Receipt published only after the worker has applied every deferred store in a submission. diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 11f2c9efa9..bbf7a2798e 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -376,7 +376,9 @@ unsafe fn note_signaled(block: *const u8, index: i32) { return; } let out = (block.add(0x10) as *const usize).read_unaligned(); - if writable(out, 4) { + // (pages XCL made read-only or no-access count too, `XCL_GUEST_WRITE_GUARD=1`: the store + // faults and is opened by the protector's handler) + if writable(out, 4) || crate::hle::kernelx::guest_write::writable(out, 4) { (out as *mut i32).write_unaligned(index); } } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 64fdcd35a7..462dc3f47a 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -893,8 +893,11 @@ unsafe fn write_title(p: usize, bytes: &[u8]) -> bool { fn NtWriteVirtualMemory(process: HANDLE, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> i32; } let mut done = 0usize; - let st = NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), p as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done); - st >= 0 && done == bytes.len() + crate::hle::kernelx::guest_write::kernel_write("DirectStorage", p, bytes.len(), || { + // SAFETY: the kernel copy returns a status instead of faulting + let st = unsafe { NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), p as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done) }; + st >= 0 && done == bytes.len() + }) } /// Where the CPU reads or writes `[p, p + n)` of the title's memory for a request: a GPU view of @@ -934,7 +937,8 @@ fn writable(p: usize, n: usize) -> bool { } let rw = 0x04 | 0x08 | 0x40 | 0x80; // PAGE_READWRITE / WRITECOPY / EXECUTE_READWRITE / EXECUTE_WRITECOPY if m.State != MEM_COMMIT || m.Protect & rw == 0 || m.Protect & 0x100 != 0 { - return false; + // (pages XCL made read-only count, `XCL_GUEST_WRITE_GUARD=1`) + return crate::hle::kernelx::guest_write::writable(p, n); } at = m.BaseAddress as usize + m.RegionSize; } diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index c645beb572..950b179cd4 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -488,10 +488,10 @@ extern "system" { fn write_destination(at: usize, bytes: &[u8]) -> bool { let mut done = 0; // Use the current-process handle so an access fault is returned as a status. - let status = unsafe { - NtWriteVirtualMemory(GetCurrentProcess(), at as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done) - }; - status >= 0 && done == bytes.len() + crate::hle::kernelx::guest_write::kernel_write("DirectStorage", at, bytes.len(), || { + let status = unsafe { NtWriteVirtualMemory(GetCurrentProcess(), at as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done) }; + status >= 0 && done == bytes.len() + }) } #[cfg(test)] diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 27f1489099..d9e1cc30f6 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -112,6 +112,7 @@ pub mod alias; pub mod guards; mod sections; pub mod lazy; +pub mod guest_write; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; /// Standard Win32 page access + PAGE_GUARD (0x100). Strips console PAGE_GRAPHICS_* bits as well diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs index 309adc18df..0c7f1b7856 100644 --- a/crates/xcl/src/hle/kernelx/guards.rs +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -95,6 +95,12 @@ fn writable(view: usize) -> bool { n != 0 && m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE } +/// Whether the 64 KiB page at `at` is a guarded view (`guest_write`: XCL may have made it +/// read-only, and its handler opens it on a write fault). One atomic load while nothing is watched. +pub(super) fn is_view(at: usize) -> bool { + WATCHING.load(Ordering::Acquire) && with(|s| s.at.contains_key(&(at & !(PAGE - 1)))) +} + /// Physical page `page` is shown at `view` (64 KiB aligned): writes there are caught from now on. /// A view not committed yet cannot be guarded; `committed` notes it when it is. pub fn watch(page: usize, view: usize) { @@ -224,7 +230,7 @@ pub fn open_until_done(opened: Opened, ov: usize) { /// Whether the overlapped I/O at `ov` is still going on (its `Internal` is STATUS_PENDING). The /// title may have freed the OVERLAPPED once it is done, so it is read without faulting. -fn still_pending(ov: usize) -> bool { +pub(super) fn still_pending(ov: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; const STATUS_PENDING: usize = 0x103; diff --git a/crates/xcl/src/hle/kernelx/guest_write.rs b/crates/xcl/src/hle/kernelx/guest_write.rs new file mode 100644 index 0000000000..81cca1a119 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guest_write.rs @@ -0,0 +1,547 @@ +//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the +//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off). +//! +//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do +//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store +//! there faults and the protector's handler opens the page. A kernel call does not fault: on a +//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and +//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION, +//! `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY and `recv`/`recvfrom` with WSAEFAULT; nothing +//! lands and no handler runs (`tests/guest_write_probe.rs`, Windows 11). So, behind the switch: +//! +//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a +//! writable protection: a page XCL protected counts as writable (a store faults and is opened); +//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views +//! opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered +//! are pinned (the protector must not protect them again) and touched by a no-op atomic RMW, +//! so the protector's fault handler runs before the kernel writes; +//! - `kernel_write` is `open` around a write that returns a status, with one retry; +//! - `bounce` lets a call that writes a buffer write XCL's own buffer first (sockets). +//! +//! A protector (the future read-only cold blocks) calls `register` / `unregister` for the ranges +//! whose pages it may protect, asks `is_pinned` before protecting a page again, and makes a page +//! writable from its vectored handler on a write fault (access 1) there. Off, every function +//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE}; + +/// the protection granule (`VirtualProtect` works on 4 KiB pages) +pub const STEP: usize = 0x1000; + +/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1")) +} + +/// ranges a protector registered: start → end +static RANGES: RwLock> = RwLock::new(BTreeMap::new()); +/// Whether any range was ever registered: `open` takes no lock before then. +static ANY: AtomicBool = AtomicBool::new(false); +/// 4 KiB pages pinned writable by a write going on → how many writes +static PINS: Mutex>> = Mutex::new(None); +/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done +static PENDING: Mutex)>> = Mutex::new(Vec::new()); +/// calls a retry repaired, and calls that still failed (logged, a few each) +static REPAIRED: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); + +/// `[p, p + len)` may hold pages a protector makes read-only or no-access. +pub fn register(p: usize, len: usize) { + if len == 0 { + return; + } + ANY.store(true, Ordering::Release); + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + insert_range(&mut g, p, p.saturating_add(len)); +} + +/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted). +pub fn unregister(p: usize, len: usize) { + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + remove_range(&mut g, p, p.saturating_add(len)); +} + +fn insert_range(m: &mut BTreeMap, mut lo: usize, mut hi: usize) { + // merge with every range that touches [lo, hi) + let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in touching { + m.remove(&s); + lo = lo.min(s); + hi = hi.max(e); + } + m.insert(lo, hi); +} + +fn remove_range(m: &mut BTreeMap, lo: usize, hi: usize) { + let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in hit { + m.remove(&s); + if s < lo { + m.insert(s, lo); + } + if e > hi { + m.insert(hi, e); + } + } +} + +fn in_ranges(m: &BTreeMap, at: usize) -> bool { + m.range(..=at).next_back().is_some_and(|(_, &e)| at < e) +} + +/// Whether XCL may have protected the page at `at` (a registered range or a guarded view). +pub fn xcl_protected(at: usize) -> bool { + (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at) +} + +/// Whether a protector must leave the 4 KiB page at `at` writable: a write is going on there. +pub fn is_pinned(at: usize) -> bool { + release_done(); + PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1)))) +} + +/// One region `VirtualQuery` describes: [base, end), committed?, protection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Region { + pub base: usize, + pub end: usize, + pub committed: bool, + pub protect: u32, +} + +fn query(at: usize) -> Option { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + let base = m.BaseAddress as usize; + Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect }) +} + +const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY +const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ; + +/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL +/// protected (`xcl`). `query` describes the region at an address. +pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option, xcl: impl Fn(usize) -> bool) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + let mut at = p; + while at < end { + let Some(r) = query(at) else { return false }; + if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at { + return false; + } + let stop = r.end.min(end); + if r.protect & WRITES == 0 { + if r.protect & PROTECTED == 0 { + return false; + } + let mut page = at & !(STEP - 1); + while page < stop { + if !xcl(page) { + return false; + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + } + at = stop; + } + true +} + +/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected +/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so +/// a pre-check `old || writable(..)` is the old one. +pub fn writable(p: usize, n: usize) -> bool { + enabled() && n > 0 && covers(p, n, query, xcl_protected) +} + +/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`), +/// pins on pages of registered ranges. Dropped when the write is over. +#[must_use = "the pages stay open only while this lives"] +pub struct Bracket { + opened: Option, + pins: Vec, +} + +impl Drop for Bracket { + fn drop(&mut self) { + unpin(std::mem::take(&mut self.pins)); + } +} + +impl Bracket { + /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done. + pub fn keep_until_done(mut self, ov: usize) { + if let Some(o) = self.opened.take() { + super::guards::open_until_done(o, ov); + } + let pins = std::mem::take(&mut self.pins); + if !pins.is_empty() { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins)); + } + } + + /// pages of registered ranges this write holds open + pub fn pinned(&self) -> usize { + self.pins.len() + } +} + +fn unpin(pins: Vec) { + if pins.is_empty() { + return; + } + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for p in pins { + if let Some(c) = m.get_mut(&p) { + *c -= 1; + if *c == 0 { + m.remove(&p); + } + } + } +} + +fn release_done() { + let done: Vec> = { + let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov)); + *g = pending; + done.into_iter().map(|(_, p)| p).collect() + }; + for p in done { + unpin(p); + } +} + +/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins` +/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it. +unsafe fn touch(p: usize, n: usize, pins: &[usize]) { + for &page in pins { + let Some(r) = query(page) else { continue }; + if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 { + let at = page.max(p); + debug_assert!(at < p + n); + (*(at as *const AtomicU8)).fetch_add(0, Ordering::Relaxed); + } + } +} + +/// `[p, p + n)` is about to be written by a kernel call or by XCL (see the module's comment). +pub fn open(p: usize, n: usize) -> Bracket { + open_with(enabled(), p, n) +} + +pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket { + let opened = Some(super::lazy::ensure(p, n)); + if !on || n == 0 || !ANY.load(Ordering::Acquire) { + return Bracket { opened, pins: Vec::new() }; + } + release_done(); + let end = p.saturating_add(n); + let pins: Vec = { + let g = RANGES.read().unwrap_or_else(|e| e.into_inner()); + let mut v = Vec::new(); + let mut page = p & !(STEP - 1); + while page < end { + if in_ranges(&g, page) { + v.push(page); + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + v + }; + if !pins.is_empty() { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for &page in &pins { + *m.entry(page).or_default() += 1; + } + } + // pinned first: the protector cannot protect a page again between its fault and the write + unsafe { touch(p, n, &pins) }; + Bracket { opened, pins } +} + +/// A write into `[p, p + n)` that returns whether it worked (`NtWriteVirtualMemory`). With the +/// switch on it is bracketed by `open` (which also closes the window in which `guards` could +/// guard a view again between a caller's `writable` check and the write), and a failure over +/// pages XCL protected is retried once after touching them again, and logged. Off: `write()`. +pub fn kernel_write(what: &str, p: usize, n: usize, mut write: impl FnMut() -> bool) -> bool { + kernel_write_with(enabled(), what, p, n, &mut write) +} + +pub(crate) fn kernel_write_with(on: bool, what: &str, p: usize, n: usize, write: &mut dyn FnMut() -> bool) -> bool { + if !on { + // (off: the call alone, as before the switch) + return write(); + } + let b = open_with(on, p, n); + if write() { + return true; + } + if !((p & !(STEP - 1))..p.saturating_add(n)).step_by(STEP).any(xcl_protected) { + return false; + } + unsafe { touch(p, n, &b.pins) }; + let ok = write(); + let count = if ok { &REPAIRED } else { &FAILED }; + if count.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("guest write: {what} into {p:#x}+{n:#x} failed over pages XCL protected; retried: {}", if ok { "written" } else { "failed again" }); + } + drop(b); + ok +} + +/// A call that writes up to `n` bytes at `buf` (a socket receive): when the buffer lies on pages +/// XCL protected, `call` writes XCL's own buffer instead and the bytes it reports are copied in +/// by a user-mode store (which faults and is opened). Returns `call`'s result. +pub unsafe fn bounce(buf: *mut u8, n: usize, call: impl FnOnce(*mut u8) -> i32) -> i32 { + bounce_with(enabled(), buf, n, call) +} + +pub(crate) unsafe fn bounce_with(on: bool, buf: *mut u8, n: usize, call: impl FnOnce(*mut u8) -> i32) -> i32 { + let p = buf as usize; + if !on || buf.is_null() || n == 0 || !((p & !(STEP - 1))..p.saturating_add(n)).step_by(STEP).any(xcl_protected) { + return call(buf); + } + let mut own = vec![0u8; n]; + let r = call(own.as_mut_ptr()); + if r > 0 { + let got = (r as usize).min(n); + let _b = open_with(on, p, got); + std::ptr::copy_nonoverlapping(own.as_ptr(), buf, got); + } + r +} + +static O_RECV: AtomicUsize = AtomicUsize::new(0); +static O_RECVFROM: AtomicUsize = AtomicUsize::new(0); + +type Recv = unsafe extern "system" fn(usize, *mut u8, i32, i32) -> i32; +type RecvFrom = unsafe extern "system" fn(usize, *mut u8, i32, i32, *mut c_void, *mut i32) -> i32; + +/// ws2_32!recv (the title imports it by ordinal 16): into XCL's buffer over protected pages. +unsafe extern "system" fn hk_recv(s: usize, buf: *mut u8, len: i32, flags: i32) -> i32 { + let orig: Recv = std::mem::transmute::(O_RECV.load(Ordering::Acquire)); + if len <= 0 { + return orig(s, buf, len, flags); + } + bounce(buf, len as usize, |b| unsafe { orig(s, b, len, flags) }) +} + +/// ws2_32!recvfrom (ordinal 17), as `hk_recv`. +unsafe extern "system" fn hk_recvfrom(s: usize, buf: *mut u8, len: i32, flags: i32, from: *mut c_void, fromlen: *mut i32) -> i32 { + let orig: RecvFrom = std::mem::transmute::(O_RECVFROM.load(Ordering::Acquire)); + if len <= 0 { + return orig(s, buf, len, flags, from, fromlen); + } + bounce(buf, len as usize, |b| unsafe { orig(s, b, len, flags, from, fromlen) }) +} + +/// With the switch on: hook `recv` / `recvfrom` process-wide (the socket receives the title +/// imports straight from ws2_32; a kernel write into a protected page fails with WSAEFAULT). +/// Call once, before the title runs. Off: nothing. +pub fn install() { + if !enabled() { + return; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| unsafe { + let mut failed = Vec::new(); + for (name, detour, orig) in [("recv", hk_recv as usize, &O_RECV), ("recvfrom", hk_recvfrom as usize, &O_RECVFROM)] { + if let Err(e) = crate::hooks::hook("ws2_32.dll", name, detour, orig) { + failed.push(e); + } + } + if failed.is_empty() { + crate::xlog_info!("XCL_GUEST_WRITE_GUARD=1: XCL's and the kernel's writes into pages XCL protected are bracketed; recv/recvfrom bounce through XCL's buffer there"); + } else { + crate::xlog_warn!("XCL_GUEST_WRITE_GUARD=1: socket receive hooks missing – {}", failed.join("; ")); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler, EXCEPTION_POINTERS}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_RELEASE, MEM_RESERVE}; + + /// the registry is one per process: the tests that register run one at a time + static SERIAL: Mutex<()> = Mutex::new(()); + + fn r(base: usize, end: usize, protect: u32) -> Region { + Region { base, end, committed: true, protect } + } + + fn regions(list: Vec) -> impl FnMut(usize) -> Option { + move |at| list.iter().copied().find(|r| (r.base..r.end).contains(&at)) + } + + #[test] + fn writable_memory_counts_and_read_only_counts_only_where_xcl_protected_it() { + let rw = || regions(vec![r(0x10000, 0x20000, PAGE_READWRITE)]); + assert!(covers(0x10000, 0x10000, rw(), |_| false)); + assert!(!covers(0x10000, 0x10001, rw(), |_| false), "past the region: nothing there"); + let mixed = || regions(vec![r(0x10000, 0x12000, PAGE_READWRITE), r(0x12000, 0x14000, PAGE_READONLY), r(0x14000, 0x15000, PAGE_NOACCESS)]); + assert!(!covers(0x11000, 0x2000, mixed(), |_| false), "read-only, not XCL's"); + assert!(covers(0x11000, 0x4000, mixed(), |a| (0x12000..0x15000).contains(&a))); + assert!(!covers(0x11000, 0x4000, mixed(), |a| a == 0x12000), "one 4 KiB page of the read-only run is not XCL's"); + let guard = regions(vec![r(0x10000, 0x20000, PAGE_READWRITE | PAGE_GUARD)]); + assert!(!covers(0x10000, 8, guard, |_| true), "a guard page is never written for the title"); + let reserved = regions(vec![Region { base: 0x10000, end: 0x20000, committed: false, protect: 0 }]); + assert!(!covers(0x10000, 8, reserved, |_| true), "not committed: unmapped stays unmapped"); + assert!(!covers(usize::MAX - 2, 8, |_| None, |_| true)); + } + + #[test] + fn ranges_merge_and_split() { + let mut m = BTreeMap::new(); + insert_range(&mut m, 0x1000, 0x3000); + insert_range(&mut m, 0x3000, 0x5000); + insert_range(&mut m, 0x8000, 0x9000); + assert_eq!(m.iter().map(|(&a, &b)| (a, b)).collect::>(), vec![(0x1000, 0x5000), (0x8000, 0x9000)]); + remove_range(&mut m, 0x2000, 0x8800); + assert_eq!(m.iter().map(|(&a, &b)| (a, b)).collect::>(), vec![(0x1000, 0x2000), (0x8800, 0x9000)]); + assert!(in_ranges(&m, 0x1fff) && !in_ranges(&m, 0x2000) && in_ranges(&m, 0x8800) && !in_ranges(&m, 0x9000)); + } + + /// A stand-in protector: read-only pages in `[LO, LO + SIZE)`, opened by a write fault. + static LO: AtomicUsize = AtomicUsize::new(0); + static FAULTS: AtomicUsize = AtomicUsize::new(0); + const SIZE: usize = 0x1_0000; + + unsafe extern "system" fn protector(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + let lo = LO.load(Ordering::Acquire); + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 && lo != 0 && (lo..lo + SIZE).contains(&r.ExceptionInformation[1]) { + FAULTS.fetch_add(1, Ordering::AcqRel); + let mut old = 0; + VirtualProtect((r.ExceptionInformation[1] & !(STEP - 1)) as *const c_void, STEP, PAGE_READWRITE, &mut old); + return -1; + } + 0 + } + + struct Protected(usize, *mut c_void); + impl Protected { + unsafe fn new(p: u32) -> Protected { + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let mut old = 0; + VirtualProtect(base as *const c_void, SIZE, p, &mut old); + FAULTS.store(0, Ordering::Release); + LO.store(base, Ordering::Release); + register(base, SIZE); + Protected(base, AddVectoredExceptionHandler(1, Some(protector))) + } + } + impl Drop for Protected { + fn drop(&mut self) { + unregister(self.0, SIZE); + LO.store(0, Ordering::Release); + unsafe { + RemoveVectoredExceptionHandler(self.1); + VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE); + } + } + } + + #[link(name = "ntdll", kind = "raw-dylib")] + extern "system" { + fn NtWriteVirtualMemory(process: *mut c_void, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> i32; + } + + unsafe fn nt_write(at: usize, bytes: &[u8]) -> bool { + let mut done = 0; + let st = NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done); + st >= 0 && done == bytes.len() + } + + #[test] + fn a_kernel_write_into_a_protected_page_lands_once_bracketed() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + for prot in [PAGE_READONLY, PAGE_NOACCESS] { + let pg = Protected::new(prot); + let at = pg.0 + 0x2010; + let bytes = [0x5Au8; 0x1800]; // two 4 KiB pages + assert!(!nt_write(at, &bytes), "the probe: a kernel write into a protected page fails"); + assert!(!kernel_write_with(false, "test", at, bytes.len(), &mut || nt_write(at, &bytes)), "off: as before"); + assert!(!writable(at, 8), "off (no env): the old answer"); + assert!(covers(at, bytes.len(), query, xcl_protected), "on: XCL's protected pages count as writable"); + assert!(kernel_write_with(true, "test", at, bytes.len(), &mut || nt_write(at, &bytes))); + assert_eq!(FAULTS.load(Ordering::Acquire), 2, "one touch per 4 KiB page, in user mode"); + assert_eq!(std::slice::from_raw_parts(at as *const u8, bytes.len()), &bytes[..]); + } + } + } + + #[test] + fn pages_stay_pinned_while_the_write_goes_on() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_READONLY); + let b = open_with(true, pg.0 + 0x1000, 0x2000); + assert_eq!(b.pinned(), 2); + assert!(is_pinned(pg.0 + 0x1000) && is_pinned(pg.0 + 0x2fff) && !is_pinned(pg.0 + 0x3000) && !is_pinned(pg.0)); + let c = open_with(true, pg.0 + 0x2000, 0x10); + drop(b); + assert!(is_pinned(pg.0 + 0x2000) && !is_pinned(pg.0 + 0x1000), "counted per write"); + drop(c); + assert!(!is_pinned(pg.0 + 0x2000)); + assert_eq!(open_with(false, pg.0, SIZE).pinned(), 0, "off: no pins"); + } + } + + #[test] + fn a_pin_of_an_overlapped_write_lasts_until_it_is_done() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_READONLY); + // an OVERLAPPED whose Internal is STATUS_PENDING, then done + let mut ov = [0x103usize, 0, 0, 0]; + open_with(true, pg.0, 0x10).keep_until_done(ov.as_mut_ptr() as usize); + assert!(is_pinned(pg.0)); + std::ptr::write_volatile(&mut ov[0], 0); + assert!(!is_pinned(pg.0), "released once the read is done"); + } + } + + #[test] + fn a_receive_into_protected_pages_goes_through_xcl_s_buffer() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_NOACCESS); + let at = (pg.0 + 0x0ff0) as *mut u8; + let r = bounce_with(true, at, 0x40, |b| { + assert_ne!(b, at, "the call writes XCL's buffer"); + assert!(nt_write(b as usize, &[7u8; 0x30])); + 0x30 + }); + assert_eq!(r, 0x30); + assert_eq!(std::slice::from_raw_parts(at, 0x30), &[7u8; 0x30][..]); + let unprotected = vec![0u8; 16]; + let p = unprotected.as_ptr() as *mut u8; + assert_eq!(bounce_with(true, p, 16, |b| if b == p { 1 } else { -1 }), 1, "elsewhere: straight through"); + let r = bounce_with(false, at.add(0x1000), 0x10, |b| if b == at.add(0x1000) { -1 } else { 1 }); + assert_eq!(r, -1, "off: straight through"); + } + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 1b0dfd86a8..d0a8bd1231 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -293,6 +293,7 @@ pub fn host_main(boot_path: &Path) -> i32 { if let Err(e) = crate::vfs_hooks::install() { crate::xlog_error!("VFS: not all hooks installed: {e}"); } + crate::hle::kernelx::guest_write::install(); if let Err(e) = crate::eh::install_pc_hook() { crate::xlog_error!("hook RtlPcToFileHeader: {e} – C++ exceptions in the game may not work"); } diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index c6a87a9101..c87bf23b94 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -532,11 +532,13 @@ unsafe extern "system" fn hk_remove_dir_w(n: *const u16) -> i32 { unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, read: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE as F); - let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + // (pages XCL protected are opened and pinned too, `XCL_GUEST_WRITE_GUARD=1`: the kernel's + // write, a copy or the disk's DMA for NO_BUFFERING, fails there rather than faulting) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::guest_write::open(buf as usize, n as usize)); let r = orig(h, buf, n, read, ov); let error = windows_sys::Win32::Foundation::GetLastError(); if !ov.is_null() && r == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { - if let Some(opened) = opened { crate::hle::kernelx::guards::open_until_done(opened, ov as usize); } + if let Some(opened) = opened { opened.keep_until_done(ov as usize); } } crate::hle::d3d12x::file_reads::returned(r != 0, error, buf, n, read, ov); SetLastError(error); diff --git a/crates/xcl/tests/guest_write_probe.rs b/crates/xcl/tests/guest_write_probe.rs new file mode 100644 index 0000000000..0c2ac49aba --- /dev/null +++ b/crates/xcl/tests/guest_write_probe.rs @@ -0,0 +1,407 @@ +//! What Windows does when the kernel (or the GPU) writes into a page the process made read-only +//! or no-access: the evidence the T6 layering rests on (`hle::kernelx::guest_write`). +//! +//! For each destination state (read-write, read-only, no-access, read-write under the write +//! watch) every call below writes one 4 KiB page; the table records its return value, error / +//! NTSTATUS, whether the bytes landed, whether a vectored handler saw a fault there (it would +//! repair one: a user-mode copy inside the call), the page's protection afterwards, and for the +//! write-watched page whether the write watch saw the write. +//! +//! Run with `cargo test --test guest_write_probe -- --nocapture --test-threads=1`. The D3D12 case +//! (`gpu_copy_into_an_imported_heap`) needs a GPU and is ignored by default. + +use std::ffi::c_void; +use std::io::Write as _; +use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::AsRawSocket; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows_sys::Win32::Foundation::{CloseHandle, GetLastError, SetLastError, EXCEPTION_ACCESS_VIOLATION, GENERIC_READ, HANDLE, INVALID_HANDLE_VALUE, NTSTATUS}; +use windows_sys::Win32::Storage::FileSystem::{CreateFileW, ReadFile, FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, OPEN_EXISTING}; +use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; +use windows_sys::Win32::System::IO::{CancelIo, GetOverlappedResult, OVERLAPPED}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler, WriteProcessMemory, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + GetWriteWatch, ResetWriteWatch, VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, + PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// (not in windows-sys: a VIRTUAL_ALLOCATION_TYPE flag) +const MEM_WRITE_WATCH: u32 = 0x20_0000; +const REGION: usize = 0x1_0000; +const N: usize = 4096; +const FILL: u8 = 0xEE; + +#[link(name = "ntdll", kind = "raw-dylib")] +extern "system" { + fn NtWriteVirtualMemory(process: HANDLE, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> NTSTATUS; + fn NtReadFile(h: HANDLE, event: HANDLE, apc: *const c_void, ctx: *const c_void, iosb: *mut [usize; 2], buf: *mut c_void, len: u32, offset: *const i64, key: *const u32) -> NTSTATUS; +} + +#[link(name = "ws2_32", kind = "raw-dylib")] +extern "system" { + fn recv(s: usize, buf: *mut u8, len: i32, flags: i32) -> i32; + fn recvfrom(s: usize, buf: *mut u8, len: i32, flags: i32, from: *mut u8, fromlen: *mut i32) -> i32; + fn WSAGetLastError() -> i32; +} + +/// the probed page: faults there are counted and repaired (made read-write), as a tracker would +static LO: AtomicUsize = AtomicUsize::new(0); +static FAULTS: AtomicUsize = AtomicUsize::new(0); +static SERIAL: Mutex<()> = Mutex::new(()); + +unsafe extern "system" fn veh(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + let lo = LO.load(Ordering::Acquire); + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && lo != 0 { + let at = r.ExceptionInformation[1]; + if (lo..lo + REGION).contains(&at) { + FAULTS.fetch_add(1, Ordering::AcqRel); + let mut old = 0; + VirtualProtect((at & !0xFFF) as *const c_void, 0x1000, PAGE_READWRITE, &mut old); + return -1; // EXCEPTION_CONTINUE_EXECUTION + } + } + 0 +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum State { + Rw, + Ro, + NoAccess, + WatchedRw, +} + +struct Page { + base: usize, + watched: bool, +} + +impl Page { + unsafe fn new(state: State) -> Page { + let watched = state == State::WatchedRw; + let flags = MEM_RESERVE | MEM_COMMIT | if watched { MEM_WRITE_WATCH } else { 0 }; + let base = VirtualAlloc(std::ptr::null(), REGION, flags, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + std::ptr::write_bytes(base as *mut u8, FILL, REGION); + if watched { + ResetWriteWatch(base as *const c_void, REGION); + } + let p = match state { + State::Ro => PAGE_READONLY, + State::NoAccess => PAGE_NOACCESS, + _ => PAGE_READWRITE, + }; + let mut old = 0; + assert_ne!(VirtualProtect(base as *const c_void, REGION, p, &mut old), 0); + FAULTS.store(0, Ordering::Release); + LO.store(base, Ordering::Release); + Page { base, watched } + } + + fn ptr(&self) -> *mut u8 { + self.base as *mut u8 + } + + unsafe fn protect_now(&self) -> u32 { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(self.base as *const c_void, &mut m, std::mem::size_of_val(&m)); + m.Protect + } + + /// (landed, protection after, write-watch hits) – read after making the page readable + unsafe fn outcome(&self, want: &[u8]) -> (String, u32, Option) { + LO.store(0, Ordering::Release); + let prot = self.protect_now(); + let mut ww = None; + if self.watched { + let mut hits = [std::ptr::null_mut::(); 16]; + let mut count = hits.len(); + let mut gran = 0u32; + GetWriteWatch(0, self.base as *const c_void, REGION, hits.as_mut_ptr(), &mut count, &mut gran); + ww = Some(count); + } + let mut old = 0; + VirtualProtect(self.base as *const c_void, REGION, PAGE_READWRITE, &mut old); + let got = std::slice::from_raw_parts(self.ptr(), N); + let same = got.iter().zip(want).filter(|(a, b)| a == b).count(); + let landed = if same == N { + "all".to_string() + } else if got.iter().all(|&b| b == FILL) { + "none".to_string() + } else { + format!("partial {same}") + }; + (landed, prot, ww) + } +} + +impl Drop for Page { + fn drop(&mut self) { + LO.store(0, Ordering::Release); + unsafe { VirtualFree(self.base as *mut c_void, 0, MEM_RELEASE) }; + } +} + +fn pattern() -> Vec { + (0..N).map(|i| (i * 7 + 3) as u8).collect() +} + +fn prot_name(p: u32) -> &'static str { + match p { + PAGE_READWRITE => "RW", + PAGE_READONLY => "RO", + PAGE_NOACCESS => "NA", + 0x40 => "XRW", + _ => "?", + } +} + +fn wide(s: &std::path::Path) -> Vec { + s.as_os_str().encode_wide().chain([0]).collect() +} + +struct Probe { + file: std::path::PathBuf, + rows: Vec, +} + +impl Probe { + unsafe fn row(&mut self, api: &str, state: State, call: impl FnOnce(&Page) -> String) { + let page = Page::new(state); + let ret = call(&page); + let faults = FAULTS.load(Ordering::Acquire); + let (landed, prot, ww) = page.outcome(&pattern()); + let ww = ww.map_or("-".to_string(), |n| if n > 0 { format!("yes ({n})") } else { "no".into() }); + let row = format!("| {api} | {state:?} | {ret} | {landed} | {faults} | {} | {ww} |", prot_name(prot)); + eprintln!("{row}"); + self.rows.push(row); + } + + unsafe fn open(&self, flags: u32) -> HANDLE { + let h = CreateFileW(wide(&self.file).as_ptr(), GENERIC_READ, FILE_SHARE_READ, std::ptr::null(), OPEN_EXISTING, flags, std::ptr::null_mut()); + assert_ne!(h, INVALID_HANDLE_VALUE); + h + } +} + +unsafe fn read_file(h: HANDLE, at: *mut u8) -> String { + let mut got = 0u32; + SetLastError(0); + let r = ReadFile(h, at, N as u32, &mut got, std::ptr::null_mut()); + let e = GetLastError(); + CloseHandle(h); + format!("ret {r}, err {e}, got {got}") +} + +#[test] +fn kernel_writes_into_protected_pages() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("xcl-guest-write-probe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("data.bin"); + let mut whole = pattern(); + whole.resize(REGION, 0); + std::fs::File::create(&file).unwrap().write_all(&whole).unwrap(); + let mut p = Probe { file, rows: Vec::new() }; + let src = pattern(); + unsafe { + let h = AddVectoredExceptionHandler(1, Some(veh)); + for state in [State::Rw, State::Ro, State::NoAccess, State::WatchedRw] { + p.row("memcpy (user mode, in process)", state, |pg| { + std::ptr::copy_nonoverlapping(src.as_ptr(), pg.ptr(), N); + "done".to_string() + }); + let fh = p.open(FILE_FLAG_OVERLAPPED); + p.row("ReadFile (OVERLAPPED)", state, |pg| { + let mut ov: OVERLAPPED = std::mem::zeroed(); + ov.hEvent = CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()); + SetLastError(0); + let r = ReadFile(fh, pg.ptr(), N as u32, std::ptr::null_mut(), &mut ov); + let e = GetLastError(); + let mut got = 0u32; + // (bounded: a read that never completes is a result too) + let waited = WaitForSingleObject(ov.hEvent, 2000); + let w = if waited == 0 { GetOverlappedResult(fh, &ov, &mut got, 0) } else { CancelIo(fh); -1 }; + let e2 = GetLastError(); + CloseHandle(ov.hEvent); + CloseHandle(fh); + format!("ret {r}, err {e}; result {w}, err {e2}, got {got}") + }); + let fh = p.open(0); + p.row("ReadFile (buffered)", state, |pg| read_file(fh, pg.ptr())); + let fh = p.open(FILE_FLAG_NO_BUFFERING); + p.row("ReadFile (NO_BUFFERING)", state, |pg| read_file(fh, pg.ptr())); + let fh = p.open(0); + p.row("NtReadFile", state, |pg| { + let mut iosb = [0usize; 2]; + let off = 0i64; + let st = NtReadFile(fh, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut iosb, pg.ptr().cast(), N as u32, &off, std::ptr::null()); + CloseHandle(fh); + format!("0x{:08X}, iosb.info {}", st as u32, iosb[1]) + }); + let fh = p.open(FILE_FLAG_NO_BUFFERING); + p.row("NtReadFile (NO_BUFFERING)", state, |pg| { + let mut iosb = [0usize; 2]; + let off = 0i64; + let st = NtReadFile(fh, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut iosb, pg.ptr().cast(), N as u32, &off, std::ptr::null()); + CloseHandle(fh); + format!("0x{:08X}, iosb.info {}", st as u32, iosb[1]) + }); + p.row("WriteProcessMemory (self)", state, |pg| { + let mut done = 0usize; + SetLastError(0); + let r = WriteProcessMemory(GetCurrentProcess(), pg.ptr().cast(), src.as_ptr().cast(), N, &mut done); + format!("ret {r}, err {}, done {done}", GetLastError()) + }); + p.row("NtWriteVirtualMemory (self)", state, |pg| { + let mut done = 0usize; + let st = NtWriteVirtualMemory(GetCurrentProcess(), pg.ptr().cast(), src.as_ptr().cast(), N, &mut done); + format!("0x{:08X}, done {done}", st as u32) + }); + p.row("recv (TCP loopback)", state, |pg| { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let mut tx = TcpStream::connect(l.local_addr().unwrap()).unwrap(); + let (rx, _) = l.accept().unwrap(); + rx.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap(); + tx.write_all(&src).unwrap(); + tx.flush().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + let r = recv(rx.as_raw_socket() as usize, pg.ptr(), N as i32, 0x8 /* MSG_WAITALL */); + let e = if r < 0 { WSAGetLastError() } else { 0 }; + format!("ret {r}, wsa {e}") + }); + p.row("recvfrom (UDP loopback)", state, |pg| { + let rx = UdpSocket::bind("127.0.0.1:0").unwrap(); + rx.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap(); + let tx = UdpSocket::bind("127.0.0.1:0").unwrap(); + tx.send_to(&src, rx.local_addr().unwrap()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + let mut from = [0u8; 32]; + let mut fl = from.len() as i32; + let r = recvfrom(rx.as_raw_socket() as usize, pg.ptr(), N as i32, 0, from.as_mut_ptr(), &mut fl); + let e = if r < 0 { WSAGetLastError() } else { 0 }; + format!("ret {r}, wsa {e}") + }); + } + RemoveVectoredExceptionHandler(h); + } + let _ = std::fs::remove_dir_all(&dir); + println!("| call | destination | result | bytes landed | VEH faults | protection after | write watch saw it |"); + println!("|---|---|---|---|---|---|---|"); + for r in &p.rows { + println!("{r}"); + } + // the read-write rows are the control: every call must have landed its bytes there + for r in p.rows.iter().filter(|r| r.contains("| Rw |")) { + assert!(r.contains("| all |"), "{r}"); + } +} + +/// A GPU copy into a heap imported from process memory (`OpenExistingHeapFromAddress`, as +/// `gpu::uma` imports the coherent window), with the CPU pages made read-only or no-access +/// before the import, or after it and before the copy. +#[test] +#[ignore = "needs a D3D12 GPU: cargo test --test guest_write_probe -- --ignored --nocapture"] +fn gpu_copy_into_an_imported_heap() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let src = pattern(); + let mut rows = Vec::new(); + unsafe { + let mut dev: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("D3D12 device"); + let dev = dev.unwrap(); + let dev3: ID3D12Device3 = dev.cast().unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let buf_desc = |w: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: w, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut up: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &buf_desc(N as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut up, + ) + .unwrap(); + let up = up.unwrap(); + let mut m = std::ptr::null_mut(); + up.Map(0, None, Some(&mut m)).unwrap(); + std::ptr::copy_nonoverlapping(src.as_ptr(), m as *mut u8, N); + up.Unmap(0, None); + let mut value = 0u64; + for state in [State::Rw, State::Ro, State::NoAccess] { + for after_import in [false, true] { + if state == State::Rw && after_import { + continue; + } + let page = Page::new(if after_import { State::Rw } else { state }); + let when = if after_import { "protected after import" } else { "protected before import" }; + let heap: Result = dev3.OpenExistingHeapFromAddress(page.base as *const c_void); + let heap = match heap { + Ok(h) => h, + Err(e) => { + let (landed, prot, _) = page.outcome(&src); + rows.push(format!("| GPU copy, imported heap | {state:?}, {when} | import failed {e} | {landed} | 0 | {} | - |", prot_name(prot))); + continue; + } + }; + let mut vp_note = String::new(); + if after_import { + let p = if state == State::Ro { PAGE_READONLY } else { PAGE_NOACCESS }; + let mut old = 0; + SetLastError(0); + let ok = VirtualProtect(page.base as *const c_void, REGION, p, &mut old); + vp_note = format!("vp ret {ok} err {}; ", GetLastError()); + } + let mut dst: Option = None; + let placed = dev.CreatePlacedResource(&heap, 0, &buf_desc(REGION as u64, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER), D3D12_RESOURCE_STATE_COMMON, None, &mut dst); + let ret = match placed { + Err(e) => format!("placed failed {e}"), + Ok(()) => { + let dst = dst.unwrap(); + alloc.Reset().unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.CopyBufferRegion(&dst, 0, &up, 0, N as u64); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + value += 1; + queue.Signal(&fence, value).unwrap(); + let t = std::time::Instant::now(); + while fence.GetCompletedValue() < value && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + let removed = dev.GetDeviceRemovedReason(); + format!("fence {}, removed {:?}", fence.GetCompletedValue() >= value, removed) + } + }; + let faults = FAULTS.load(Ordering::Acquire); + let (landed, prot, _) = page.outcome(&src); + rows.push(format!("| GPU copy, imported heap | {state:?}, {when} | {vp_note}{ret} | {landed} | {faults} | {} | - |", prot_name(prot))); + } + } + } + for r in &rows { + println!("{r}"); + } +}