Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 127 additions & 6 deletions crates/xcl/src/hle/dstorage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,13 @@ impl Request {
}

/// Snapshot a `PULONG_PTR` physical page array at enqueue time (callers often stack-allocate it).
/// `[p, p + len)` overlaps the calling thread's stack.
fn on_callers_stack(p: usize, len: usize) -> bool {
let (mut lo, mut hi) = (0usize, 0usize);
unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits(&mut lo, &mut hi) };
p < hi && p.saturating_add(len.max(1)) > lo
}

unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result<Vec<usize>, HRESULT> {
if byte_len == 0 {
return Ok(Vec::new());
Expand Down Expand Up @@ -870,7 +877,7 @@ fn note_request(r: &Request) {
}

/// Run a request; the destination gets the bytes or nothing.
unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, src_pages: Option<&[usize]>) -> Result<(), HRESULT> {
unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, dest_on_stack: bool, src_pages: Option<&[usize]>) -> Result<(), HRESULT> {
let n = r.destination_size as usize;
note_request(r);
if !r.dest_physical_pages() && !writable(r.destination as usize, n) {
Expand Down Expand Up @@ -927,6 +934,28 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us

if r.dest_physical_pages() {
let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?;
// The console reads the page list when it runs the request. A retail title keeps its
// lists in slots of its own table and writes a slot's pages after EnqueueRequest, so at
// enqueue a slot can still name the pages of its previous request: written there, the
// data lands in memory the title has since used for something else, or in freed pages.
// The list as it is now is taken when all its pages are allocated. A list that was on the
// enqueuing thread's stack keeps the snapshot: that memory is reused once the call
// returns, and a page ID written there since can belong to another allocation.
let mut current = vec![0usize; pages.len()];
let pages = if !dest_on_stack
&& read_own(r.destination as usize, current.as_mut_ptr() as *mut u8, std::mem::size_of_val(pages))
&& current[..] != pages[..]
&& crate::hle::kernelx::physical_pages_live(&current)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This proves only that the replacement page IDs are currently allocated; it does not prove the list is a persistent title table. If a stack-backed list is overwritten after enqueue with the ID of another still-live allocation, read_own succeeds and this check redirects the request from the snapshotted page p1 to unrelated page p2, potentially corrupting its owner. This conflicts with the stated fallback for overwritten stack arrays. Could the late reread require a positively identified persistent page-table range, and otherwise keep the snapshot? AI-assisted review; I verified this with the existing page-list flow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right: being allocated now does not make the list a persistent table. Fixed in bb27ed6 (squashed, rebased onto main with #509): queue_enqueue_request records whether the destination page list lies on the calling thread's stack (GetCurrentThreadStackLimits), and such a list keeps its snapshot at execution. a_destination_page_rewritten_after_enqueue now has your case – a list on the test thread's stack, rewritten after enqueue with the ID of another live page, keeps its snapshot page and leaves the other alone; it fails without the check.

I could not find a way to positively identify a title's persistent table, so this rules out the stack, the case the snapshot fallback was for. A heap array the title frees and reuses before its request runs would still be read late; that limit is now under Not tested.

(AI-assisted: Claude Code with Claude Opus 5.5 wrote the change and this reply; I checked the test fails without it.)

{
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let k = N.fetch_add(1, Ordering::Relaxed) + 1;
if k == 1 || k.is_power_of_two() {
crate::xlog_info!("DirectStorage: {k} page lists written after their request was enqueued: the pages named at execution are used");
}
&current[..]
} else {
pages
};
// A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is
// read again now. A retail title keeps its page arrays in its own tables and fills an
// entry after EnqueueRequest – its streaming requests were refused by the thousand
Expand Down Expand Up @@ -988,6 +1017,8 @@ enum Entry {
req: Request,
file: Option<Arc<FileInner>>,
dest_pages: Option<Vec<usize>>,
/// the destination page list was on the enqueuing thread's stack (`on_callers_stack`)
dest_on_stack: bool,
src_pages: Option<Vec<usize>>,
},
/// refused at enqueue: reported in queue order by the worker (unless cancelled, as a request)
Expand Down Expand Up @@ -1136,12 +1167,12 @@ impl QueueInner {
return;
}
match e {
Entry::Request { seq, req, file, dest_pages, src_pages } => {
Entry::Request { seq, req, file, dest_pages, dest_on_stack, src_pages } => {
if self.is_cancelled(seq, req.tag) {
// Cancelled requests are skipped without affecting status or error record.
return;
}
if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), src_pages.as_deref()) } {
if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), dest_on_stack, src_pages.as_deref()) } {
self.update_error(hr, req, file.as_deref(), since_status);
}
}
Expand Down Expand Up @@ -1192,8 +1223,8 @@ impl QueueInner {
}
}

fn enqueue_request(self: &Arc<Self>, req: Request, file: Option<Arc<FileInner>>, dest_pages: Option<Vec<usize>>, src_pages: Option<Vec<usize>>) {
self.enqueue_numbered(|seq| Entry::Request { seq, req, file, dest_pages, src_pages });
fn enqueue_request(self: &Arc<Self>, req: Request, file: Option<Arc<FileInner>>, dest_pages: Option<Vec<usize>>, dest_on_stack: bool, src_pages: Option<Vec<usize>>) {
self.enqueue_numbered(|seq| Entry::Request { seq, req, file, dest_pages, dest_on_stack, src_pages });
}

/// A request refused at enqueue, numbered as a request so `CancelRequestsWithTag` covers it.
Expand Down Expand Up @@ -1376,7 +1407,8 @@ unsafe extern "system" fn queue_enqueue_request(p: *mut c_void, req: *const u8)
} else {
None
};
q.enqueue_request(r, file, dest_pages, src_pages);
let dest_on_stack = dest_pages.as_ref().is_some_and(|p| on_callers_stack(r.destination as usize, std::mem::size_of_val(&p[..])));
q.enqueue_request(r, file, dest_pages, dest_on_stack, src_pages);
}

unsafe extern "system" fn queue_enqueue_status(p: *mut c_void, array: *mut c_void, index: u32) {
Expand Down Expand Up @@ -2314,6 +2346,95 @@ mod tests {
}
}

/// A title's table slot still names its previous request's page at enqueue and gets this
/// request's page before Submit: the data goes to the page named at execution, and the old
/// page (in use for something else by then) is left alone. A list on the enqueuing thread's
/// stack keeps its snapshot: a page written there since, though allocated, is not taken.
#[test]
fn a_destination_page_rewritten_after_enqueue() {
use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE};
if crate::gpu::uma::get().is_none() {
return;
}
unsafe {
let mut count = 2usize;
let mut pages = [0usize; 2];
assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1);

let mut f = std::ptr::null_mut();
assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK);
let vt = *(f as *const *const usize);
let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3));
let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5));
let mut desc = [0u8; 0x18];
desc[0..4].copy_from_slice(&1u32.to_le_bytes());
desc[8..10].copy_from_slice(&16u16.to_le_bytes());
desc[10] = 2;
let mut q = std::ptr::null_mut();
assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK);
let mut s = std::ptr::null_mut();
assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK);
let qv = *(q as *const *const usize);
let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3));
let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4));
let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6));
let sv = *(s as *const *const usize);
let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3));
let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4));

let reserved = windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
2 * PHYS_PAGE_SIZE,
windows_sys::Win32::System::Memory::MEM_RESERVE,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
);
assert!(!reserved.is_null());
assert_eq!(MapTitlePhysicalPages(reserved, 2, 0, 4, pages.as_mut_ptr()), reserved);
let old_page = std::slice::from_raw_parts_mut(reserved as *mut u8, 0x100);
old_page.fill(0xAB);

let data: Vec<u8> = (0..0x100u32).map(|i| (i * 7 + 1) as u8).collect();
let mut slot = Box::new([pages[0]]);
enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, slot.as_ptr() as u64, 0, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr());
std::ptr::write_volatile(&mut slot[0], pages[1]);
status(q, s, 0);
submit(q);
let t = std::time::Instant::now();
while !complete(s, 0) && t.elapsed().as_secs() < 5 {
std::thread::yield_now();
}
assert_eq!(hresult(s, 0), S_OK);
let new_page = std::slice::from_raw_parts((reserved as *const u8).add(PHYS_PAGE_SIZE), data.len());
assert_eq!(new_page, &data[..], "the data goes to the page the slot names at execution");
assert!(old_page.iter().all(|&b| b == 0xAB), "the slot's previous page is left alone");

// the same on the enqueuing thread's stack: rewritten after enqueue with another live
// page, the list keeps its snapshot
let other = std::slice::from_raw_parts_mut((reserved as *mut u8).add(PHYS_PAGE_SIZE), data.len());
other.fill(0xCD);
let data2: Vec<u8> = (0..0x100u32).map(|i| (i * 3 + 5) as u8).collect();
let mut on_stack = [pages[0]];
enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, on_stack.as_ptr() as u64, 0, data2.len() as u32, data2.as_ptr() as u64, 0, data2.len() as u32, 0, 0).as_ptr());
std::ptr::write_volatile(&mut on_stack[0], pages[1]);
status(q, s, 1);
submit(q);
let t = std::time::Instant::now();
while !complete(s, 1) && t.elapsed().as_secs() < 5 {
std::thread::yield_now();
}
assert_eq!(hresult(s, 1), S_OK);
assert_eq!(&old_page[..], &data2[..], "a list on the stack: the page of its snapshot");
assert!(other.iter().all(|&b| b == 0xCD), "the page written on the stack since is left alone");

MapTitlePhysicalPages(reserved, 2, 0, 4, std::ptr::null_mut());
windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE);
assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1);
queue_close(q);
queue_release(q);
status_release(s);
}
}

#[test]
fn physical_page_destinations_and_sources() {
use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE};
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/hle/kernelx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,11 @@ fn page_home(page: usize) -> Option<usize> {
(live > 0 && index < first.checked_add(count)?).then(|| home.checked_add((index - first).checked_mul(PHYS_PAGE)?)).flatten()
}

/// Whether every page of `pages` (at least one) is a physical page allocated now.
pub fn physical_pages_live(pages: &[usize]) -> bool {
!pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some())
}

/// Whether a home is only reserved until it is used (a sparse window's, or plain memory's –
/// the coherent window is committed as a whole).
fn lazy_home(home: usize) -> bool {
Expand Down
Loading