Skip to content
Open
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
214 changes: 209 additions & 5 deletions crates/xcl/src/hle/d3d12x/device_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1012,13 +1012,39 @@ pub(super) unsafe fn pc_clear(clear: *const c_void, buf: &mut [u8; 24]) -> *cons
buf.as_ptr() as *const c_void
}

/// Whether `f` is a typeless DXGI format (invalid in `D3D12_CLEAR_VALUE::Format`).
fn is_typeless_format(f: u32) -> bool {
matches!(
f,
1 | 5 | 9 | 15 | 19 | 23 | 27 | 33 | 39 | 44 | 48 | 53 | 60 | 70 | 73 | 76 | 79 | 82 | 90 | 92 | 94 | 97
)
}

/// The unique typed depth-stencil format for a depth format family (None: not a depth family).
fn depth_clear_format(f: u32) -> Option<u32> {
match f {
19 | 20 => Some(20), // R32G8X24_TYPELESS / D32_FLOAT_S8X24_UINT
39 | 40 => Some(40), // R32_TYPELESS / D32_FLOAT
44 | 45 => Some(45), // R24G8_TYPELESS / D24_UNORM_S8_UINT
53 | 55 => Some(55), // R16_TYPELESS / D16_UNORM
_ => None,
}
}

/// The PC format of an optimized clear value (`clear_format`) for a resource whose PC format is
/// `pc_format`: aligns promoted `B5G6R5` (`85 -> 28`) and `B8G8R8X8` (`88 -> 87`) UAV targets
/// while preserving native `85`/`88` on render-target-only resources without UAV.
/// `pc_format`: aligns promoted `B5G6R5` (`85 -> 28`) and `B8G8R8X8` (`88 -> 87`) UAV targets,
/// maps depth-only typeless families (`19`/`44`) to their concrete DSV formats (`20`/`45`), and
/// resolves `UNKNOWN` (`0`) or typeless clear formats when `pc_format` is concrete, while
/// preserving native `85`/`88` on render-target-only resources without UAV.
pub(super) fn pc_clear_format(pc_format: u32, clear_format: u32) -> u32 {
match (pc_format, pc_target_format(clear_format)) {
let f = pc_target_format(clear_format);
match (pc_format, f) {
(28, 85) => 28,
(87, 88) => 87,
(19 | 20, 0 | 19) => 20,
(44 | 45, 0 | 44) => 45,
(_, 0) if pc_format != 0 && !is_typeless_format(pc_format) => pc_format,
(_, t) if is_typeless_format(t) && pc_format != 0 && !is_typeless_format(pc_format) => pc_format,
(_, f) => f,
}
}
Expand All @@ -1035,6 +1061,38 @@ pub(super) unsafe fn pc_clear_for_desc(clear: *const c_void, pc_format: u32, buf
buf.as_ptr() as *const c_void
}

/// Sanitize a `D3D12_CLEAR_VALUE` against a PC `D3D12_RESOURCE_DESC`:
/// - buffers and textures without `ALLOW_RENDER_TARGET` or `ALLOW_DEPTH_STENCIL` cannot carry a
/// non-null `pOptimizedClearValue` on PC D3D12 (`E_INVALIDARG`), so return null;
/// - depth textures (`ALLOW_DEPTH_STENCIL`) map `UNKNOWN` or typeless clear formats (`19`/`39`/
/// `44`/`53`) to their unique depth format (`20`/`40`/`45`/`55`);
/// - concrete render targets map `UNKNOWN` or typeless clear formats to `pc_format`, while
/// unresolvable `UNKNOWN`/typeless clear formats on typeless color textures return null.
pub(super) unsafe fn pc_clear_for_resource_desc(clear: *const c_void, pc_desc: &[u8; 0x38], buf: &mut [u8; 24]) -> *const c_void {
if clear.is_null() || !crate::gpu::shader::readable(clear as usize, 24) {
return clear;
}
let dim = u32::from_le_bytes(pc_desc[0..4].try_into().unwrap());
let pc_format = u32::from_le_bytes(pc_desc[0x20..0x24].try_into().unwrap());
let pc_flags = u32::from_le_bytes(pc_desc[0x30..0x34].try_into().unwrap());
if dim == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 || (pc_flags & 3) == 0 {
return std::ptr::null();
}
std::ptr::copy_nonoverlapping(clear as *const u8, buf.as_mut_ptr(), 24);
let raw = u32::from_le_bytes(buf[0..4].try_into().unwrap());
let mut f = pc_clear_format(pc_format, raw);
if (pc_flags & 2) != 0 && (f == 0 || is_typeless_format(f)) {
if let Some(df) = depth_clear_format(pc_format) {
f = df;
}
}
if f == 0 || is_typeless_format(f) {
return std::ptr::null();
}
buf[0..4].copy_from_slice(&f.to_le_bytes());
buf.as_ptr() as *const c_void
}

/// device #25 GetResourceAllocationInfo(visible mask, count, descs) → {size, alignment},
/// returned through a hidden pointer. Called the C way – (return buffer, device, …), XDefiant –
/// or the C++ way – (device, return buffer, …): whichever argument is the device is `this`.
Expand Down Expand Up @@ -1225,8 +1283,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
// PC's: the PC refused the resource (E_INVALIDARG) and the title threw
let state = pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state);
let mut clear_buf = [0u8; 24];
let pc_format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap());
let clear = pc_clear_for_desc(clear, pc_format, &mut clear_buf);
let clear = pc_clear_for_resource_desc(clear, &d, &mut clear_buf);
if buffer {
if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) {
return hr;
Expand Down Expand Up @@ -2038,4 +2095,151 @@ mod tests {
forget_base(pso_key2);
assert!(weak_vs.upgrade().is_none(), "shared blob drops once all owning PSOs are released");
}

#[test]
fn pc_clear_for_resource_desc_sanitizes_formats_and_non_targets() {
let make_desc = |dim: u32, fmt: u32, flags: u32| -> [u8; 0x38] {
let mut x = [0u8; 0x38];
x[0..4].copy_from_slice(&dim.to_le_bytes());
let w: u64 = if dim == 1 { 256 } else { 64 };
let h: u32 = if dim == 1 { 1 } else { 64 };
x[0x10..0x18].copy_from_slice(&w.to_le_bytes());
x[0x18..0x1C].copy_from_slice(&h.to_le_bytes());
x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes());
x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes());
x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes());
x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes());
x[0x30..0x34].copy_from_slice(&flags.to_le_bytes());
pc_resource_desc(&x)
};
let eval = |d: &[u8; 0x38], clear_fmt: u32| -> Option<(u32, [u8; 20])> {
let mut raw = [0u8; 24];
raw[0..4].copy_from_slice(&clear_fmt.to_le_bytes());
raw[4..8].copy_from_slice(&0.75f32.to_le_bytes());
raw[8] = 0x5A;
let mut buf = [0u8; 24];
let ptr = unsafe { pc_clear_for_resource_desc(raw.as_ptr() as *const c_void, d, &mut buf) };
if ptr.is_null() {
None
} else {
assert_eq!(ptr, buf.as_ptr() as *const c_void);
let mut payload = [0u8; 20];
payload.copy_from_slice(&buf[4..24]);
assert_eq!(&payload[..], &raw[4..24]);
Some((u32::from_le_bytes(buf[0..4].try_into().unwrap()), payload))
}
};
let mut buf = [0u8; 24];
assert!(unsafe { pc_clear_for_resource_desc(std::ptr::null(), &make_desc(3, 28, 1), &mut buf) }.is_null());
// Buffers and non-RT/non-DS textures drop optimized clear values.
assert!(eval(&make_desc(1, 0, 0), 28).is_none());
assert!(eval(&make_desc(3, 28, 0), 28).is_none());
assert!(eval(&make_desc(3, 28, 4), 28).is_none());
// Depth textures resolve typeless/UNKNOWN clear formats to their concrete depth format.
assert_eq!(eval(&make_desc(3, 40, 2), 39).map(|v| v.0), Some(40));
assert_eq!(eval(&make_desc(3, 45, 2), 0).map(|v| v.0), Some(45));
assert_eq!(eval(&make_desc(3, 20, 2), 19).map(|v| v.0), Some(20));
assert_eq!(eval(&make_desc(3, 55, 2), 53).map(|v| v.0), Some(55));
assert_eq!(eval(&make_desc(3, 118, 2), 118).map(|v| v.0), Some(45));
// Concrete RTs resolve UNKNOWN/typeless clear formats to pc_format.
assert_eq!(eval(&make_desc(3, 28, 1), 0).map(|v| v.0), Some(28));
assert_eq!(eval(&make_desc(3, 28, 1), 27).map(|v| v.0), Some(28));
// Typeless color RTs drop unresolvable typeless/UNKNOWN clears (including R32_TYPELESS
// without ALLOW_DEPTH_STENCIL, which must not become D32_FLOAT) but preserve concrete clears.
assert!(eval(&make_desc(3, 27, 1), 27).is_none());
assert!(eval(&make_desc(3, 27, 1), 0).is_none());
assert!(eval(&make_desc(3, 39, 1), 39).is_none());
assert_eq!(eval(&make_desc(3, 27, 1), 29).map(|v| v.0), Some(29));
assert_eq!(eval(&make_desc(3, 39, 1), 41).map(|v| v.0), Some(41));
assert_eq!(eval(&make_desc(3, 85, 5), 85).map(|v| v.0), Some(28));
}

#[test]
fn gpu_pc_clear_for_resource_desc_sanitizes_invalid_clear_values() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;
let dev = unsafe {
let mut dev: Option<ID3D12Device> = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
let Ok(f) = CreateDXGIFactory1::<IDXGIFactory4>() else { return crate::gpu::recomp::runner::skip_test("no GPU or WARP"); };
let Ok(w) = f.EnumWarpAdapter::<IDXGIAdapter>() else { return crate::gpu::recomp::runner::skip_test("no GPU or WARP"); };
if D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { return crate::gpu::recomp::runner::skip_test("no GPU or WARP"); }
}
dev.unwrap()
};
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let make_desc = |dim: u32, fmt: u32, flags: u32| -> [u8; 0x38] {
let mut x = [0u8; 0x38];
x[0..4].copy_from_slice(&dim.to_le_bytes());
let w: u64 = if dim == 1 { 256 } else { 64 };
let h: u32 = if dim == 1 { 1 } else { 64 };
x[0x10..0x18].copy_from_slice(&w.to_le_bytes());
x[0x18..0x1C].copy_from_slice(&h.to_le_bytes());
x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes());
x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes());
x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes());
x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes());
x[0x30..0x34].copy_from_slice(&flags.to_le_bytes());
pc_resource_desc(&x)
};
// Invalid clear-value combinations rejected raw by PC D3D12 and accepted after sanitization.
let invalid_cases: &[(&str, [u8; 0x38], u32, Option<u32>)] = &[
("buf_with_clear", make_desc(1, 0, 0), 28, None),
("srv_tex_with_clear", make_desc(3, 28, 0), 28, None),
("uav_tex_with_clear", make_desc(3, 28, 4), 28, None),
("d32_typeless_clear", make_desc(3, 40, 2), 39, Some(40)),
("d24s8_unknown_clear", make_desc(3, 45, 2), 0, Some(45)),
("d32s8_typeless_clear", make_desc(3, 20, 2), 19, Some(20)),
("d16_typeless_clear", make_desc(3, 55, 2), 53, Some(55)),
("rt_unknown_clear", make_desc(3, 28, 1), 0, Some(28)),
("rt_typeless_clear_on_concrete", make_desc(3, 28, 1), 27, Some(28)),
("rt_typeless_clear_on_typeless", make_desc(3, 27, 1), 27, None),
("rt_r32_typeless_clear", make_desc(3, 39, 1), 39, None),
];
for &(name, d_bytes, clear_fmt, expected_fmt) in invalid_cases {
let d: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(d_bytes.as_ptr() as *const _) };
let raw_clear = D3D12_CLEAR_VALUE {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(clear_fmt as i32),
Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0, 0.0, 0.0, 1.0] },
};
let mut r: Option<ID3D12Resource> = None;
assert!(
unsafe { dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, Some(&raw_clear), &mut r) }.is_err(),
"{name}: expected raw D3D12_CLEAR_VALUE to be rejected by CreateCommittedResource"
);
let mut san_buf = [0u8; 24];
let san_ptr = unsafe { pc_clear_for_resource_desc(&raw_clear as *const _ as *const c_void, &d_bytes, &mut san_buf) };
let san_opt = (!san_ptr.is_null()).then(|| unsafe { std::ptr::read_unaligned(san_ptr as *const D3D12_CLEAR_VALUE) });
assert_eq!(san_opt.as_ref().map(|v| v.Format.0 as u32), expected_fmt, "{name}: unexpected sanitized clear format");
let mut r2: Option<ID3D12Resource> = None;
unsafe {
dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, san_opt.as_ref().map(|v| v as *const _), &mut r2)
.unwrap_or_else(|e| panic!("{name}: CreateCommittedResource failed after sanitization: {e}"));
}
assert!(r2.is_some());
}
// Valid concrete clear values on typeless RT / depth textures must be preserved.
for &(name, d_bytes, clear_fmt, expected_fmt) in &[
("rt_typeless_srgb_clear", make_desc(3, 27, 1), 29u32, 29u32),
("rt_r32_typeless_float_clear", make_desc(3, 39, 1), 41u32, 41u32),
("ds_d16s8_clear", make_desc(3, 118, 2), 118u32, 45u32),
] {
let d: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(d_bytes.as_ptr() as *const _) };
let raw_clear = D3D12_CLEAR_VALUE {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(clear_fmt as i32),
Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.25, 0.5, 0.75, 1.0] },
};
let mut san_buf = [0u8; 24];
let san_ptr = unsafe { pc_clear_for_resource_desc(&raw_clear as *const _ as *const c_void, &d_bytes, &mut san_buf) };
assert!(!san_ptr.is_null(), "{name}: valid clear value should be preserved");
let san_cv: D3D12_CLEAR_VALUE = unsafe { std::ptr::read_unaligned(san_ptr as *const _) };
assert_eq!(san_cv.Format.0 as u32, expected_fmt, "{name}: preserved clear format mismatch");
let mut r: Option<ID3D12Resource> = None;
unsafe {
dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, Some(&san_cv), &mut r)
.unwrap_or_else(|e| panic!("{name}: CreateCommittedResource failed: {e}"));
}
assert!(r.is_some());
}
}
}
11 changes: 7 additions & 4 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2170,9 +2170,11 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta
}
return None;
};
// the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state
// the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state;
// buffers cannot carry a non-null optimized clear value on PC D3D12
let _ = clear;
let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k));
let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, clear, riid, ppv);
let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, 0, riid, ppv);
if hr < 0 || (*ppv).is_null() {
u.free(p);
static ONCE: AtomicU64 = AtomicU64::new(0);
Expand Down Expand Up @@ -2266,7 +2268,8 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc:
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
d.Alignment = 0;
d.Width = (delta + bytes) as u64;
let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, state as usize, clear as usize, riid, ppv);
let _ = clear;
let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, state as usize, 0, riid, ppv);
if hr < 0 || (*ppv).is_null() {
return None;
}
Expand Down Expand Up @@ -3897,7 +3900,7 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro
let desc = pc_full.as_ref().map_or(desc, |d| d.as_ptr() as usize);
let mut clear_buf = [0u8; 24];
let clear = match pc_full.as_ref() {
Some(d) => super::device_x::pc_clear_for_desc(clear as *const c_void, u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), &mut clear_buf),
Some(d) => super::device_x::pc_clear_for_resource_desc(clear as *const c_void, d, &mut clear_buf),
None => super::device_x::pc_clear(clear as *const c_void, &mut clear_buf),
} as usize;
// console-only state bits (e.g. 0x100000 on a display target) are not the PC's; a resource
Expand Down
Loading