diff --git a/d3d12/crates/leonida-hle/src/modules/ffx.rs b/d3d12/crates/leonida-hle/src/modules/ffx.rs index c264f85991..0fa4e74ed2 100644 --- a/d3d12/crates/leonida-hle/src/modules/ffx.rs +++ b/d3d12/crates/leonida-hle/src/modules/ffx.rs @@ -16,7 +16,6 @@ use std::ffi::c_void; use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; - /// The DLL whose `ffxDispatch` is taken. pub const LOADER: &str = "amd_fidelityfx_loader_xbox.dll"; @@ -33,6 +32,18 @@ struct Header { next: *const Header, } +/// The header of a dispatch or creation description. The description is the +/// title's own buffer and need not be aligned for the struct, so it is read +/// unaligned; `None` when the title passes none. +fn read_header(desc: *const Header) -> Option
{ + if desc.is_null() { + return None; + } + // SAFETY: the title passes a description, whose header says what follows + // it. + Some(unsafe { std::ptr::read_unaligned(desc) }) +} + #[repr(C)] struct Resource { resource: *const c_void, @@ -88,14 +99,12 @@ const UPSCALE: u64 = 0x0001_0001; type Dispatch = extern "system" fn(*mut *mut c_void, *const Header) -> u32; extern "system" fn dispatch(context: *mut *mut c_void, desc: *const Header) -> u32 { - // SAFETY: the title passes a dispatch description, whose header says - // what follows it. - if let Some(header) = unsafe { desc.as_ref() } { + if let Some(header) = read_header(desc) { static SEEN: AtomicU32 = AtomicU32::new(0); let first = SEEN.fetch_add(1, Ordering::Relaxed) < 4; if header.kind == UPSCALE { // SAFETY: an upscale description, by its type. - let d = unsafe { &*desc.cast::() }; + let d = unsafe { std::ptr::read_unaligned(desc.cast::()) }; if first { tracing::info!( list = ?d.list, @@ -233,6 +242,18 @@ fn sizes_to_stand_in(render: [u32; 2], upscale: [u32; 2]) -> Option<([u32; 2], [ (size(render) && size(upscale) && upscale != SHIPPED.1).then_some(SHIPPED) } +/// The two sizes of the title's own creation description, written where the +/// public API has them. The description is the title's own buffer and need +/// not be aligned for the struct. +fn write_sizes(desc: *mut Header, sizes: ([u32; 2], [u32; 2])) { + let d = desc.cast::(); + // SAFETY: the title's description holds both sizes. + unsafe { + std::ptr::addr_of_mut!((*d).max_render).write_unaligned(sizes.0); + std::ptr::addr_of_mut!((*d).max_upscale).write_unaligned(sizes.1); + } +} + /// `ffxCreateContext` while the dispatch is ours ([`dispatch`]: DLSS or the stretch). /// /// On the Series X profile the title asks for a context of 2560x1440 to 3840x2160; the DLL @@ -241,29 +262,35 @@ fn sizes_to_stand_in(render: [u32; 2], upscale: [u32; 2]) -> Option<([u32; 2], [ /// (0xC0000094 at title+0x28f03e8). The context passes are never run here, only its queries /// (the jitter sequence, which is arithmetic on the sizes each query names), so the DLL is /// asked for the context it does make and the description of the title is put back. -extern "system" fn create(context: *mut *mut c_void, desc: *mut Header, memory: *const c_void) -> u32 { +extern "system" fn create( + context: *mut *mut c_void, + desc: *mut Header, + memory: *const c_void, +) -> u32 { let real = match REAL_CREATE.load(Ordering::Relaxed) { 0 => return ERROR, // SAFETY: the title's own `ffxCreateContext`, set from its DLL's export. real => unsafe { std::mem::transmute::(real) }, }; - // SAFETY: the title passes a creation description, whose header says what follows it. - if let Some(header) = unsafe { desc.as_ref() } + if let Some(header) = read_header(desc.cast_const()) && header.kind == CREATE_UPSCALE { // SAFETY: an upscale context's description, by its type; the title's own memory, // which nothing else reads during its call. - let d = unsafe { &mut *desc.cast::() }; + let d = unsafe { std::ptr::read_unaligned(desc.cast::()) }; let asked = (d.max_render, d.max_upscale); if let Some(stand_in) = sizes_to_stand_in(asked.0, asked.1) { - (d.max_render, d.max_upscale) = stand_in; + write_sizes(desc, stand_in); let result = real(context, desc, memory); - (d.max_render, d.max_upscale) = asked; + write_sizes(desc, asked); + // The title's own upscaler may have changed the flags while it + // made the context. + let flags = unsafe { std::ptr::read_unaligned(desc.cast::()).flags }; tracing::info!( render = ?asked.0, upscale = ?asked.1, made_for = ?stand_in, - flags = format_args!("{:#x}", d.flags), + flags = format_args!("{:#x}", flags), result, "upscale context: the title's upscaler makes one of its own sizes; the upscale itself is ours" ); @@ -291,6 +318,34 @@ mod tests { use super::*; use std::mem::offset_of; + /// A buffer at an address a title's own memory can be at: 8-byte + /// aligned, so that a byte into it is at an odd address for every type + /// the description holds. + #[repr(align(8))] + struct Aligned([u8; 512]); + + /// The title's own dispatch and create, for the tests that set them: + /// they are process-wide, so the tests that change them take this. + static REALS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// What the title's own create saw of the description. + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(None); + + /// The title's own `ffxCreateContext`, for the tests: it reads the + /// sizes the way the DLL would and leaves them as they are. + extern "system" fn fake_create( + _: *mut *mut c_void, + desc: *mut Header, + _: *const c_void, + ) -> u32 { + // SAFETY: the description the title's own DLL would read. + let d = unsafe { std::ptr::read_unaligned(desc.cast::()) }; + SEEN.lock() + .unwrap_or_else(|e| e.into_inner()) + .replace((d.max_render, d.max_upscale)); + 0 + } + /// The upscale description as the public API lays it out: what the /// stretch reads sits where the title wrote it. #[test] @@ -333,6 +388,7 @@ mod tests { /// pass it to, is an error and not a silent success. #[test] fn a_dispatch_nothing_answers_is_an_error() { + let _guard = REALS.lock().unwrap_or_else(|e| e.into_inner()); let before = REAL.swap(0, Ordering::Relaxed); let other = Header { kind: 0x0002_0001, @@ -342,4 +398,104 @@ mod tests { assert_eq!(dispatch(std::ptr::null_mut(), std::ptr::null()), ERROR); REAL.store(before, Ordering::Relaxed); } + + /// A dispatch description in the title's own buffer need not be aligned + /// for the struct: the aligned access this replaces panics in a debug + /// build. + #[test] + fn a_dispatch_description_at_an_odd_address_is_read() { + let _guard = REALS.lock().unwrap_or_else(|e| e.into_inner()); + let before = REAL.swap(0, Ordering::Relaxed); + + // The aligned description, for the misaligned one to match. + let mut aligned = Aligned([0u8; 512]); + // SAFETY: the buffer holds the description. + unsafe { + aligned + .0 + .as_mut_ptr() + .cast::() + .write_unaligned(UPSCALE) + }; + let expected = dispatch( + std::ptr::null_mut(), + aligned.0.as_mut_ptr().cast::
(), + ); + + // An 8-byte aligned buffer plus 1: the description is at an odd + // address. + let mut buffer = Aligned([0u8; 512]); + let at = unsafe { buffer.0.as_mut_ptr().add(1) }.cast::
(); + assert_eq!((at as usize) % std::mem::align_of::
(), 1); + // SAFETY: the buffer holds the description. + unsafe { at.cast::().write_unaligned(UPSCALE) }; + assert_eq!(dispatch(std::ptr::null_mut(), at), expected); + + REAL.store(before, Ordering::Relaxed); + } + + /// The creation description in the title's own buffer need not be aligned + /// for the struct: the aligned access this replaces panics in a debug + /// build. The sizes are written into it, so the write is unaligned too. + #[test] + fn a_creation_description_at_an_odd_address_is_read_and_written() { + let _guard = REALS.lock().unwrap_or_else(|e| e.into_inner()); + let before = REAL_CREATE.swap(fake_create as *const () as usize, Ordering::Relaxed); + *SEEN.lock().unwrap_or_else(|e| e.into_inner()) = None; + + // The aligned description, for the misaligned one to match. + let mut aligned = Aligned([0u8; 512]); + let at = aligned.0.as_mut_ptr().cast::(); + // SAFETY: the buffer holds the description. + unsafe { + at.write_unaligned(CreateUpscale { + header: Header { + kind: CREATE_UPSCALE, + next: std::ptr::null(), + }, + flags: 0, + max_render: [2560, 1440], + max_upscale: [3840, 2160], + }) + }; + let result = create(std::ptr::null_mut(), at.cast::
(), std::ptr::null()); + // The title's own upscaler was asked for the sizes it makes. + assert_eq!( + *SEEN.lock().unwrap_or_else(|e| e.into_inner()), + Some((SHIPPED.0, SHIPPED.1)) + ); + // The title's own sizes are back in its description. + // SAFETY: the buffer holds the description. + let d = unsafe { std::ptr::read_unaligned(at) }; + assert_eq!((d.max_render, d.max_upscale), ([2560, 1440], [3840, 2160])); + + // An 8-byte aligned buffer plus 1: the description is at an odd + // address. + let mut buffer = Aligned([0u8; 512]); + let odd = unsafe { buffer.0.as_mut_ptr().add(1) }.cast::(); + assert_eq!((odd as usize) % std::mem::align_of::(), 1); + // SAFETY: the buffer holds the description. + unsafe { + odd.write_unaligned(CreateUpscale { + header: Header { + kind: CREATE_UPSCALE, + next: std::ptr::null(), + }, + flags: 0, + max_render: [2560, 1440], + max_upscale: [3840, 2160], + }) + }; + let odd_result = create(std::ptr::null_mut(), odd.cast::
(), std::ptr::null()); + assert_eq!(odd_result, result); + assert_eq!( + *SEEN.lock().unwrap_or_else(|e| e.into_inner()), + Some((SHIPPED.0, SHIPPED.1)) + ); + // SAFETY: the buffer holds the description. + let d = unsafe { std::ptr::read_unaligned(odd) }; + assert_eq!((d.max_render, d.max_upscale), ([2560, 1440], [3840, 2160])); + + REAL_CREATE.store(before, Ordering::Relaxed); + } } diff --git a/d3d12/crates/leonida-hle/src/modules/xgameruntime.rs b/d3d12/crates/leonida-hle/src/modules/xgameruntime.rs index b3f5963fce..29c2491b4c 100644 --- a/d3d12/crates/leonida-hle/src/modules/xgameruntime.rs +++ b/d3d12/crates/leonida-hle/src/modules/xgameruntime.rs @@ -225,9 +225,12 @@ pub extern "system" fn QueryApiImpl( out: *mut *mut c_void, ) -> HRESULT { static QUERIED: Mutex> = Mutex::new(Vec::new()); - // SAFETY: the title passes pointers to GUIDs (null is tolerated). - let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() }) - else { + // SAFETY: the title passes pointers to GUIDs (null is tolerated); a GUID + // in a title's own buffer need not be aligned for `Guid`. + let (Some(provider), Some(iid)) = ( + (!provider.is_null()).then(|| unsafe { provider.read_unaligned() }), + (!iid.is_null()).then(|| unsafe { iid.read_unaligned() }), + ) else { return NOT_SUPPORTED; }; #[cfg(feature = "diagnostics")] @@ -341,4 +344,32 @@ mod tests { assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null()); } } + + /// A GUID in a title's own buffer need not be aligned for `Guid`: the + /// aligned access this replaces panics in a debug build. + #[test] + fn a_guid_at_an_odd_address_is_read_as_the_aligned_one_is() { + let guid = Guid::new( + 0x1234_abcd, + 0x00ef, + 0x4a5b, + [0x80, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde], + ); + // The aligned call, for the misaligned one to match. + let mut out = std::ptr::null_mut(); + assert_eq!(QueryApiImpl(&guid, &guid, &mut out), NOT_SUPPORTED); + assert!(out.is_null()); + + // An 8-byte aligned buffer plus 1: the GUID is at an odd address. + #[repr(align(8))] + struct Aligned([u8; 32]); + let mut buffer = Aligned([0u8; 32]); + let at = unsafe { buffer.0.as_mut_ptr().add(1) }.cast::(); + assert_eq!((at as usize) % std::mem::align_of::(), 1); + // SAFETY: the buffer holds the GUID. + unsafe { at.write_unaligned(guid) }; + let mut out = std::ptr::null_mut(); + assert_eq!(QueryApiImpl(at, at, &mut out), NOT_SUPPORTED); + assert!(out.is_null()); + } }