From 0b638b223e09c719cc2a42a03e7a2994aa65ce28 Mon Sep 17 00:00:00 2001 From: GustavoEllwanger <225090786+GustavoEllwanger@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:58:36 -0300 Subject: [PATCH] D3D12.X: guard null and unreadable pointers in graphics and compute PSO hooks Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/device_x.rs | 11 +- crates/xcl/src/hle/d3d12x/real.rs | 306 ++++++++++++++++++++++---- crates/xcl/tests/d3d12_pso_guards.rs | 192 ++++++++++++++++ 3 files changed, 464 insertions(+), 45 deletions(-) create mode 100644 crates/xcl/tests/d3d12_pso_guards.rs diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ff..30d271648 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -14,7 +14,7 @@ //! are mapped onto PC ones. use std::collections::HashMap; -use std::ffi::{c_char, c_void, CStr, CString}; +use std::ffi::{c_void, CString}; use std::sync::atomic::{AtomicI8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -375,8 +375,13 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b for i in 0..n { // D3D12_INPUT_ELEMENT_DESC { SemanticName @0; … } let mut e = ((p + 32 * i) as *const [u8; 32]).read_unaligned(); - let s = rd64(&e, 0) as *const c_char; - let name = if s.is_null() { CString::default() } else { CStr::from_ptr(s).to_owned() }; + let s = rd64(&e, 0) as *const u8; + let name = if s.is_null() { + CString::default() + } else { + let Some(c) = real::read_cstr_checked(s) else { return }; + c + }; e[0..8].copy_from_slice(&(name.as_ptr() as u64).to_le_bytes()); names.push(name); elems.push(e); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 7456239e1..13fb8f29d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4345,12 +4345,14 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if let Some(plan) = compiled.dispatch_chain { if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) { LAST_COMPUTE_RS.with(|c| c.set(rs)); - note_pso_rs(*ppv, rs as *mut c_void); - super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if !ppv.is_null() && !(*ppv).is_null() { + note_pso_rs(*ppv, rs as *mut c_void); + super::dred::label(*ppv as usize, &[("cs", Some(cs))]); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(0, ppv); } - note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); return Some(Ok(0)); } @@ -4377,12 +4379,14 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); - note_pso_rs(*ppv, rs); - super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if !ppv.is_null() && !(*ppv).is_null() { + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("cs", Some(cs))]); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(hr, ppv); } - note_translated_compute(hr, ppv); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", dxil.len(), @@ -4441,8 +4445,9 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL hr = retried; in_driver += took; } + let has_pso = !ppv.is_null() && !(*ppv).is_null(); let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; - if hr >= 0 && !reused { + if hr >= 0 && !reused && has_pso { keep_compute_blob(key, *ppv, dxil.len()); if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { driver_cache::keep(p, &b, in_driver); @@ -4864,11 +4869,10 @@ unsafe fn graphics_blob_key( feed_u32(&mut h, op.StencilFunc.0 as u32); } feed_u32(&mut h, copy.InputLayout.NumElements); - if copy.InputLayout.NumElements > 0 && !copy.InputLayout.pInputElementDescs.is_null() { - let elems = std::slice::from_raw_parts(copy.InputLayout.pInputElementDescs, copy.InputLayout.NumElements as usize); + if let Ok(elems) = input_layout_slice(©.InputLayout) { for e in elems { - if !e.SemanticName.0.is_null() { - feed(&mut h, std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes_with_nul()); + if let Some(name) = read_cstr_checked(e.SemanticName.0) { + feed(&mut h, name.as_bytes_with_nul()); } else { feed(&mut h, &[0]); } @@ -5205,7 +5209,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; - if build.cache_eligible { + let has_pso = !ppv.is_null() && !(*ppv).is_null(); + if build.cache_eligible && has_pso { keep_graphics_blob(gkey, *ppv, bytes); if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { driver_cache::keep(p, &b, build.in_driver); @@ -5225,22 +5230,25 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); - note_pso_rs(*ppv, rs); - super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); - note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); - if super::present::trace_frame() { + if has_pso { + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + } + if has_pso && super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); // the input layout (semantic index, format, slot, offset) – what the vertices are read as - let il = &d.InputLayout; - let elems: Vec = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { - std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) + let elems: Vec = match input_layout_slice(&d.InputLayout) { + Ok(slice) => slice .iter() - .map(|e| format!("{}{} fmt {} slot {} @{}", e.SemanticName.to_string().unwrap_or_default(), e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset as i32)) - .collect() - } else { - Vec::new() + .map(|e| { + let name = read_cstr_checked(e.SemanticName.0).and_then(|s| s.into_string().ok()).unwrap_or_default(); + format!("{name}{} fmt {} slot {} @{}", e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset as i32) + }) + .collect(), + Err(()) => Vec::new(), }; PSO_LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); static N: AtomicU64 = AtomicU64::new(0); @@ -5346,8 +5354,116 @@ impl OwnedDesc { } } -/// Copy a shader blob into `blobs` and point `b` at the copy. -unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { +/// Read a NUL-terminated C string up to 1024 bytes, checking page readability before each chunk. +/// None for null, unreadable or unterminated within 1024 bytes (callers reject the desc then). +pub(super) unsafe fn read_cstr_checked(p: *const u8) -> Option { + const MAX_LEN: usize = 1024; + if p.is_null() { + return None; + } + let mut cur = p as usize; + let mut out = Vec::new(); + while out.len() < MAX_LEN { + let page_left = 0x1000 - (cur & 0xFFF); + let step = page_left.min(MAX_LEN - out.len()); + if !crate::gpu::shader::readable(cur, step) { + return None; + } + let slice = std::slice::from_raw_parts(cur as *const u8, step); + if let Some(nul) = slice.iter().position(|&b| b == 0) { + out.extend_from_slice(&slice[..nul]); + return std::ffi::CString::new(out).ok(); + } + out.extend_from_slice(slice); + cur = cur.checked_add(step)?; + } + None +} + +fn unreadable_bytecode(b: &D3D12_SHADER_BYTECODE) -> bool { + let (p, n) = (b.pShaderBytecode as usize, b.BytecodeLength); + p != 0 && n != 0 && !crate::gpu::shader::readable(p, n) +} + +fn unreadable_cached_pso(c: &D3D12_CACHED_PIPELINE_STATE) -> bool { + let (p, n) = (c.pCachedBlob as usize, c.CachedBlobSizeInBytes); + p != 0 && n != 0 && !crate::gpu::shader::readable(p, n) +} + +/// Validate and slice `InputLayout`. Empty or null returns `Ok(&[])`; an overflowing or +/// unreadable element array returns `Err(())`. +unsafe fn input_layout_slice<'a>(il: &D3D12_INPUT_LAYOUT_DESC) -> Result<&'a [D3D12_INPUT_ELEMENT_DESC], ()> { + if il.NumElements == 0 || il.pInputElementDescs.is_null() { + return Ok(&[]); + } + let n = il.NumElements as usize; + let bytes = n.checked_mul(std::mem::size_of::()).ok_or(())?; + if !crate::gpu::shader::readable(il.pInputElementDescs as usize, bytes) { + return Err(()); + } + Ok(std::slice::from_raw_parts(il.pInputElementDescs, n)) +} + +unsafe fn compute_desc_has_unreadable_pointers(desc: *const c_void) -> bool { + if desc.is_null() { + return false; + } + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return true; + } + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + unreadable_bytecode(&d.CS) || unreadable_cached_pso(&d.CachedPSO) +} + +unsafe fn graphics_desc_has_unreadable_pointers(desc: *const c_void) -> bool { + if desc.is_null() { + return false; + } + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return true; + } + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + if [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS].into_iter().any(unreadable_bytecode) || unreadable_cached_pso(&d.CachedPSO) { + return true; + } + let Ok(elems) = input_layout_slice(&d.InputLayout) else { + return true; + }; + if elems.iter().any(|e| !e.SemanticName.0.is_null() && read_cstr_checked(e.SemanticName.0).is_none()) { + return true; + } + let so = &d.StreamOutput; + if so.NumEntries > 0 && !so.pSODeclaration.is_null() { + let n = so.NumEntries as usize; + let Some(bytes) = n.checked_mul(std::mem::size_of::()) else { + return true; + }; + if !crate::gpu::shader::readable(so.pSODeclaration as usize, bytes) { + return true; + } + let decls = std::slice::from_raw_parts(so.pSODeclaration, n); + if decls.iter().any(|e| !e.SemanticName.0.is_null() && read_cstr_checked(e.SemanticName.0).is_none()) { + return true; + } + } + if so.NumStrides > 0 && !so.pBufferStrides.is_null() { + let n = so.NumStrides as usize; + let Some(bytes) = n.checked_mul(std::mem::size_of::()) else { + return true; + }; + if !crate::gpu::shader::readable(so.pBufferStrides as usize, bytes) { + return true; + } + } + false +} + +/// Copy a shader blob into `blobs` and point `b` at the copy. Returns false when a non-null, +/// non-empty shader pointer is unreadable. +unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) -> bool { + if unreadable_bytecode(b) { + return false; + } if let Some(bytes) = shader_bytes(b) { blobs.push(bytes.to_vec()); let v = blobs.last().unwrap(); @@ -5355,36 +5471,46 @@ unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { } else { *b = D3D12_SHADER_BYTECODE::default(); } + true } unsafe fn own_compute(desc: *const c_void) -> Option { + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } let mut d: Box = Box::new(std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)); let mut blobs = Vec::new(); - own_shader(&mut d.CS, &mut blobs); + if !own_shader(&mut d.CS, &mut blobs) { + return None; + } d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); Some(OwnedDesc::Compute(d, blobs)) } -/// None with stream output (not copied; such pipelines are built in the call). +/// None when the desc or any referenced shader / input layout / semantic name is unreadable, or +/// with stream output (not copied; such pipelines are built in the call). unsafe fn own_graphics(desc: *const c_void) -> Option { + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } let mut d: Box = Box::new(std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC)); if d.StreamOutput.NumEntries > 0 { return None; } let mut blobs = Vec::new(); for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { - own_shader(b, &mut blobs); - } - let n = d.InputLayout.NumElements as usize; - let mut elems = Vec::new(); - let mut names = Vec::new(); - if n > 0 && !d.InputLayout.pInputElementDescs.is_null() { - elems = std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, n).to_vec(); - for e in &mut elems { - names.push(std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_owned()); - e.SemanticName = PCSTR(names.last().unwrap().as_ptr() as *const u8); + if !own_shader(b, &mut blobs) { + return None; } } + let slice = input_layout_slice(&d.InputLayout).ok()?; + let mut elems = slice.to_vec(); + let mut names = Vec::with_capacity(elems.len()); + for e in &mut elems { + let name = read_cstr_checked(e.SemanticName.0)?; + names.push(name); + e.SemanticName = PCSTR(names.last().unwrap().as_ptr() as *const u8); + } d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: if elems.is_empty() { std::ptr::null() } else { elems.as_ptr() }, NumElements: elems.len() as u32 }; d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); Some(OwnedDesc::Graphics(d, blobs, elems, names)) @@ -5606,6 +5732,9 @@ pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); + if graphics_desc_has_unreadable_pointers(desc) { + return E_INVALIDARG; + } let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; if missed { @@ -5651,6 +5780,9 @@ unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) { unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_compute_desc(desc as *const u8); + if compute_desc_has_unreadable_pointers(desc) { + return E_INVALIDARG; + } let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; if missed { @@ -8374,6 +8506,96 @@ mod mesh_stream_tests { } } +#[cfg(test)] +mod pso_pointer_guard_tests { + use super::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + + #[test] + fn read_cstr_checked_handles_null_unreadable_valid_and_guard_page() { + unsafe { + assert!(read_cstr_checked(std::ptr::null()).is_none()); + assert!(read_cstr_checked(0x1000 as *const u8).is_none()); + let s = read_cstr_checked(b"POSITION\0".as_ptr()).expect("valid C string"); + assert_eq!(s.to_str().unwrap(), "POSITION"); + + let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_NOACCESS); + assert!(!base.is_null()); + let page0 = VirtualAlloc(base, 0x1000, MEM_COMMIT, PAGE_READWRITE) as *mut u8; + assert!(!page0.is_null()); + std::ptr::write_bytes(page0.add(0xFF0), b'X', 16); + assert!(read_cstr_checked(page0.add(0xFF0)).is_none(), "unterminated string crossing into uncommitted page"); + *page0.add(0xFFF) = 0; + let bounded = read_cstr_checked(page0.add(0xFF0)).expect("terminated string at page end"); + assert_eq!(bounded.as_bytes().len(), 15); + VirtualFree(base, 0, MEM_RELEASE); + } + } + + #[test] + fn own_graphics_and_own_compute_reject_null_and_unreadable_pointers() { + unsafe { + assert!(own_compute(std::ptr::null()).is_none()); + assert!(own_compute(0x1000 as *const c_void).is_none()); + assert!(own_graphics(std::ptr::null()).is_none()); + assert!(own_graphics(0x1000 as *const c_void).is_none()); + + let bad_bc = D3D12_SHADER_BYTECODE { pShaderBytecode: 0x1000 as *const c_void, BytecodeLength: 64 }; + let mut cmp = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cmp.CS = bad_bc; + assert!(own_compute(&cmp as *const _ as *const c_void).is_none()); + assert!(compute_desc_has_unreadable_pointers(&cmp as *const _ as *const c_void)); + + let mut gfx = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + gfx.VS = bad_bc; + assert!(own_graphics(&gfx as *const _ as *const c_void).is_none()); + assert!(graphics_desc_has_unreadable_pointers(&gfx as *const _ as *const c_void)); + + // Null SemanticName in InputLayout must not dereference NULL + let null_elem = D3D12_INPUT_ELEMENT_DESC::default(); + let mut gfx_null_sem = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + gfx_null_sem.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &null_elem, NumElements: 1 }; + assert!(own_graphics(&gfx_null_sem as *const _ as *const c_void).is_none()); + + // Unreadable pInputElementDescs & overflowing NumElements + let mut gfx_bad_il = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + gfx_bad_il.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: 0x1000 as *const D3D12_INPUT_ELEMENT_DESC, NumElements: 1 }; + assert!(own_graphics(&gfx_bad_il as *const _ as *const c_void).is_none()); + assert!(graphics_desc_has_unreadable_pointers(&gfx_bad_il as *const _ as *const c_void)); + + let valid_elem = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(b"TEXCOORD\0".as_ptr()), + SemanticIndex: 2, + ..Default::default() + }; + let mut gfx_huge_il = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + gfx_huge_il.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &valid_elem, NumElements: u32::MAX }; + assert!(own_graphics(&gfx_huge_il as *const _ as *const c_void).is_none()); + assert!(graphics_desc_has_unreadable_pointers(&gfx_huge_il as *const _ as *const c_void)); + + // graphics_blob_key tolerates unreadable InputLayout without crashing + let _ = graphics_blob_key(&gfx_bad_il, &[1, 2, 3, 4], None, None, &[]); + + // Valid graphics desc clones shaders and semantic names cleanly + let shader = vec![0x44u8, 0x58, 0x42, 0x43, 1, 2, 3, 4]; + let mut gfx_ok = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + gfx_ok.VS = bytecode(&shader); + gfx_ok.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &valid_elem, NumElements: 1 }; + assert!(!graphics_desc_has_unreadable_pointers(&gfx_ok as *const _ as *const c_void)); + let OwnedDesc::Graphics(owned_d, blobs, elems, names) = own_graphics(&gfx_ok as *const _ as *const c_void).expect("valid graphics desc") else { + panic!("expected Graphics"); + }; + assert_eq!(blobs.len(), 1); + assert_eq!(blobs[0], shader); + assert_eq!(elems.len(), 1); + assert_eq!(names.len(), 1); + assert_eq!(names[0].to_str().unwrap(), "TEXCOORD"); + assert_eq!(owned_d.InputLayout.NumElements, 1); + assert_eq!(owned_d.InputLayout.pInputElementDescs, elems.as_ptr()); + } + } +} + #[cfg(test)] mod uav_companion_srv_tests { use super::*; diff --git a/crates/xcl/tests/d3d12_pso_guards.rs b/crates/xcl/tests/d3d12_pso_guards.rs new file mode 100644 index 000000000..76256d0bb --- /dev/null +++ b/crates/xcl/tests/d3d12_pso_guards.rs @@ -0,0 +1,192 @@ +//! Robustness checks for `ID3D12Device::CreateGraphicsPipelineState` and +//! `ID3D12Device::CreateComputePipelineState` (`d3d12x::real`), with no game data. +//! +//! Runs on any D3D12 adapter (AMD, NVIDIA, Intel, or WARP) with zero vendor-specific skips: +//! 1. Console graphics PSO with null `SemanticName` does not crash `own_graphics`. +//! 2. Unreadable `pInputElementDescs`, overflowing `NumElements`, unreadable `SemanticName`, +//! and cross-page unterminated `SemanticName` return `E_INVALIDARG` cleanly. +//! 3. Unreadable shader bytecodes, `CachedPSO`, `StreamOutput` pointers, and unreadable +//! top-level desc pointers on graphics and compute PSO hooks return `E_INVALIDARG` cleanly. + +use std::ffi::c_void; +use std::sync::OnceLock; + +use windows::core::{GUID, HRESULT, Interface, PCSTR}; +use windows::Win32::Foundation::E_INVALIDARG; +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + +use xcl::gpu::recomp::runner; +use xcl::hle::d3d12x::real; + +fn device() -> Option { + static DEV: OnceLock> = OnceLock::new(); + DEV.get_or_init(|| unsafe { + if real::init().is_err() { + runner::skip_test("d3d12x::real::init failed"); + return None; + } + let raw = real::device_raw(); + ID3D12Device::from_raw_borrowed(&raw).cloned() + }) + .clone() +} + +/// Minimal synthetic console shader DXBC container recognized by `pso::is_console` +/// (`kind = 1` for `"VS"`, `kind = 5` for `"CS"`), with no game data. +fn synthetic_console_shader(kind: u32) -> Vec { + let dxil_size = 32u32; + let total_size = 36u32 + 8 + dxil_size; + let mut b = Vec::with_capacity(total_size as usize); + b.extend_from_slice(b"DXBC"); + b.extend_from_slice(&[0u8; 16]); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&total_size.to_le_bytes()); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&36u32.to_le_bytes()); + b.extend_from_slice(b"DXIL"); + b.extend_from_slice(&dxil_size.to_le_bytes()); + let pv = (kind << 16) | 0x65; + b.extend_from_slice(&pv.to_le_bytes()); + b.extend_from_slice(&[0u8; 20]); + b.extend_from_slice(b"XDAT"); + b.extend_from_slice(&0u32.to_le_bytes()); + assert!(xcl::gpu::recomp::pso::is_console(&b)); + b +} + +fn bytecode(b: &[u8]) -> D3D12_SHADER_BYTECODE { + D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const c_void, BytecodeLength: b.len() } +} + +#[test] +fn graphics_pso_null_semantic_name_does_not_crash() { + let Some(dev) = device() else { return }; + let vs = synthetic_console_shader(1); + let elem = D3D12_INPUT_ELEMENT_DESC::default(); + assert!(elem.SemanticName.0.is_null()); + + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.VS = bytecode(&vs); + desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &elem, NumElements: 1 }; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.SampleMask = u32::MAX; + desc.SampleDesc.Count = 1; + + // Must not dereference NULL in `own_graphics` (`CStr::from_ptr(null)`). + let _ = unsafe { dev.CreateGraphicsPipelineState::(&desc) }; +} + +#[test] +fn graphics_pso_unreadable_input_layout_and_semantic_name_return_invalidarg() { + let Some(dev) = device() else { return }; + let vs = synthetic_console_shader(1); + + let mut base = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + base.VS = bytecode(&vs); + base.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + base.SampleMask = u32::MAX; + base.SampleDesc.Count = 1; + + // 1. Unreadable pInputElementDescs pointer + let mut d1 = base.clone(); + d1.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: 0x1000 as *const D3D12_INPUT_ELEMENT_DESC, NumElements: 1 }; + let err = unsafe { dev.CreateGraphicsPipelineState::(&d1) }.expect_err("unreadable InputLayout must fail"); + assert_eq!(err.code(), E_INVALIDARG); + + // 2. Overflowing / out-of-bounds NumElements + let valid_elem = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(b"POSITION\0".as_ptr()), + ..Default::default() + }; + let mut d2 = base.clone(); + d2.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &valid_elem, NumElements: u32::MAX }; + let err = unsafe { dev.CreateGraphicsPipelineState::(&d2) }.expect_err("huge NumElements must fail"); + assert_eq!(err.code(), E_INVALIDARG); + + // 3. Unreadable SemanticName pointer + let bad_name_elem = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(0x1000 as *const u8), + ..Default::default() + }; + let mut d3 = base.clone(); + d3.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &bad_name_elem, NumElements: 1 }; + let err = unsafe { dev.CreateGraphicsPipelineState::(&d3) }.expect_err("unreadable SemanticName must fail"); + assert_eq!(err.code(), E_INVALIDARG); + + // 4. Unterminated SemanticName reaching into an uncommitted guard page + unsafe { + let base_mem = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_NOACCESS); + assert!(!base_mem.is_null(), "VirtualAlloc MEM_RESERVE failed"); + let page0 = VirtualAlloc(base_mem, 0x1000, MEM_COMMIT, PAGE_READWRITE) as *mut u8; + assert!(!page0.is_null(), "VirtualAlloc MEM_COMMIT failed"); + std::ptr::write_bytes(page0.add(0xFF0), b'A', 16); + + let guard_elem = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(page0.add(0xFF0)), + ..Default::default() + }; + let mut d4 = base; + d4.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: &guard_elem, NumElements: 1 }; + let res = dev.CreateGraphicsPipelineState::(&d4); + VirtualFree(base_mem, 0, MEM_RELEASE); + assert_eq!(res.expect_err("unterminated SemanticName must fail").code(), E_INVALIDARG); + } +} + +#[test] +fn graphics_and_compute_pso_unreadable_shader_and_desc_pointers_return_invalidarg() { + let Some(dev) = device() else { return }; + let bad_bc = D3D12_SHADER_BYTECODE { pShaderBytecode: 0x1000 as *const c_void, BytecodeLength: 64 }; + let bad_cache = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: 0x1000 as *const c_void, CachedBlobSizeInBytes: 64 }; + + // Graphics: unreadable VS, PS, CachedPSO, StreamOutput pointers + let mut g_vs = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g_vs.VS = bad_bc; + assert_eq!(unsafe { dev.CreateGraphicsPipelineState::(&g_vs) }.expect_err("unreadable VS").code(), E_INVALIDARG); + + let mut g_ps = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g_ps.PS = bad_bc; + assert_eq!(unsafe { dev.CreateGraphicsPipelineState::(&g_ps) }.expect_err("unreadable PS").code(), E_INVALIDARG); + + let mut g_cache = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g_cache.CachedPSO = bad_cache; + assert_eq!(unsafe { dev.CreateGraphicsPipelineState::(&g_cache) }.expect_err("unreadable graphics CachedPSO").code(), E_INVALIDARG); + + let mut g_so_decl = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g_so_decl.StreamOutput.pSODeclaration = 0x1000 as *const D3D12_SO_DECLARATION_ENTRY; + g_so_decl.StreamOutput.NumEntries = 1; + assert_eq!(unsafe { dev.CreateGraphicsPipelineState::(&g_so_decl) }.expect_err("unreadable pSODeclaration").code(), E_INVALIDARG); + + let mut g_so_strides = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g_so_strides.StreamOutput.pBufferStrides = 0x1000 as *const u32; + g_so_strides.StreamOutput.NumStrides = 1; + assert_eq!(unsafe { dev.CreateGraphicsPipelineState::(&g_so_strides) }.expect_err("unreadable pBufferStrides").code(), E_INVALIDARG); + + // Compute: unreadable CS and CachedPSO + let mut c_cs = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + c_cs.CS = bad_bc; + assert_eq!(unsafe { dev.CreateComputePipelineState::(&c_cs) }.expect_err("unreadable CS").code(), E_INVALIDARG); + + let mut c_cache = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + c_cache.CachedPSO = bad_cache; + assert_eq!(unsafe { dev.CreateComputePipelineState::(&c_cache) }.expect_err("unreadable compute CachedPSO").code(), E_INVALIDARG); + + // Raw COM vtable calls with unreadable top-level desc pointer (slots 10 & 11 of ID3D12Device) + unsafe { + type PsoFn = unsafe extern "system" fn(*mut c_void, *const c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let raw = real::device_raw(); + let vtbl = *(raw as *const *const usize); + let create_gfx: PsoFn = std::mem::transmute(*vtbl.add(10)); + let create_cmp: PsoFn = std::mem::transmute(*vtbl.add(11)); + let iid = ID3D12PipelineState::IID; + + let mut out: *mut c_void = std::ptr::null_mut(); + assert_eq!(create_gfx(raw, 0x1000 as *const c_void, &iid, &mut out), E_INVALIDARG); + assert!(out.is_null()); + + let mut out: *mut c_void = std::ptr::null_mut(); + assert_eq!(create_cmp(raw, 0x1000 as *const c_void, &iid, &mut out), E_INVALIDARG); + assert!(out.is_null()); + } +}