diff --git a/HANDOFF.md b/HANDOFF.md index cded449..8c718d2 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -541,6 +541,27 @@ Slots and semantics as observed on Fortnite (UE RHI call sites); XCL's own evide - Next with the exe: the console-only command-list methods Fortnite calls (report.json lists them), title heaps / placed resources at title addresses, occlusion queries (the console allows nesting them, PC does not). +## The console device's own methods (session 5, 2026-11-21, `d3d12x/device_x.rs`) +Slots as observed on Fortnite. From #44 on the console device's vtable holds its extensions, so a title call there +must not run the PC method at that index (#44 is PC CreatePipelineLibrary, #48 OpenExistingHeapFromAddress…): +- **#44 CreatePlacedResourceX**(address, desc, state, clear, riid, out): a buffer at a 64 KiB boundary in unified + memory is placed in that window's heap – it *is* the title's memory (GPU VA = the address; Release leaves the title's + allocation alone). Textures and other buffers get memory of their own (logged): the console tiling of texels the title + writes there is not translated yet. +- **#48 CreateCommandQueueX** / #8, #9, **#73 CreateCommandListX**(params `{ type @0; node mask @8 }`, …) / #12: the + console DMA type 0x10 is the PC copy type, the DMA list IID is created as a graphics list, console priorities → PC. +- **#60 / #62** graphics / compute PSO X (PC desc + extension count / pointer, extensions not modelled), **#86** + CreatePipelineState (streams); **#61 CreateSamplerX** (0x6C-byte desc → anisotropic PC sampler); **#38** + GetCopyableFootprints retried with the PC desc when the console desc is rejected; **#41** command signatures (DispatchX + 105 → Dispatch, root signature only for root arguments); descriptor heap type 4 = CBV / SRV / UAV. +- **#52** SetDebugFlagsX → S_OK, **#56 / #66** SerializePipelineStateX → E_ACCESSDENIED (as the release runtime), + **#57 / #67** DeserializePipelineStateX → E_NOTIMPL (console pipeline caches hold console shaders; not decoded yet), + **#74 / #75** page pools (index registry). Every other device slot from #44: a logged stub answering S_OK. +- The test title copies a buffer placed at its own `XMemAlloc` graphics memory through a DMA queue / allocator / list + created through #48 / #9 / #73 and checks the remaining slots. +- Not yet: CreateDerivedPipelineStateX #55 (patches over a base PSO's desc), deserializing console pipeline caches, + placed textures at title addresses (detiling). + ## Contributions merged (session 5, 2026-11-21, PRs #5, #6, #8, part of #7) - **#5** more RDNA2 instructions (scalar movrel / bitcmp / bfe64, d16 typed buffers, f64 ceil / fract / rndne / frexp / sqrt / rsq / class, v_swaprel, pknorm f16…) with tests. Fixed on the GPU (RX 9070), where its GPU tests had not run: @@ -556,8 +577,9 @@ Slots and semantics as observed on Fortnite (UE RHI call sites); XCL's own evide - **Second round (#6 rebuilt, #9–#11, #13):** D3D12 texture limits and UTF-16 `MicrosoftGame.config`; DXC toolchain id (dxcompiler / dxil size + mtime) in the DXIL cache key – the cache rebuilds once – and fresh DXIL validated; GameSave read results survive a too-small-buffer retry; a null process task queue means disabled (`E_NO_TASK_QUEUE`); `xcl rpf` - probes archives over 1 GB in 4 MB chunks (`--probe` / `--full`). Open: #12 (feature availability should be false - only for XStore / XAppCapture). + probes archives over 1 GB in 4 MB chunks (`--probe` / `--full`). **#12** every documented runtime feature + available except XStore and XAppCapture; **#14** geometry (ES + GS) as two wave32 halves on adapters without wave64, + rejecting cross-half operations (no change on wave64 adapters: the sampled shaders translate identically). - **#7** only the persistent-local-storage accounting (used bytes measured). Its task-queue / XAsync handle registries (2.8 k lines against forged handles) were not taken. diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs new file mode 100644 index 0000000..0dbc178 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -0,0 +1,323 @@ +//! The console device's own methods and the PC ones whose arguments differ on the console. +//! +//! The console's ID3D12Device has the PC ID3D12Device methods at slots 0–43; from 44 on its +//! vtable holds console extensions (as observed on Fortnite): CreatePlacedResourceX #44, +//! CreateCommandQueueX #48, SetDebugFlagsX #52, the pipeline-state (de)serialisation +//! #56 / #57 / #66 / #67, CreateGraphicsPipelineStateX #60, CreateSamplerX #61, +//! CreateComputePipelineStateX #62, CreateCommandListX #73, page pools #74 / #75, the frame +//! clock #78–#81 (`frame`), CreatePipelineState #86 (streams, mesh shaders). A title call +//! of any other extension slot is logged and answered S_OK (`real::class_for`) – not run as +//! the PC method at that index. +//! +//! Console queue and list types add DMA (0x10, the copy engine); console queue priorities +//! are mapped onto PC ones. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::core::GUID; + +use super::real; +use crate::util::{HRESULT, S_OK}; + +const E_INVALIDARG: HRESULT = 0x8007_0057u32 as i32; +const E_NOTIMPL: HRESULT = 0x8000_4001u32 as i32; +const E_ACCESSDENIED: HRESULT = 0x8007_0005u32 as i32; +const E_FAIL: HRESULT = 0x8000_4005u32 as i32; + +/// D3D12_COMMAND_LIST_TYPE of the console's DMA (copy) engine +pub const XBOX_TYPE_DMA: u32 = 0x10; +/// IID of the console's DMA command list (created as a PC graphics command list) +const IID_XBOX_DMA_COMMAND_LIST: GUID = GUID::from_u128(0x30bc77b9_8379_4b25_95de_b8588c42275d); +const IID_GRAPHICS_COMMAND_LIST: GUID = GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); +/// D3D12_INDIRECT_ARGUMENT_TYPE of the console's DispatchX +const XBOX_ARG_DISPATCH_X: u32 = 105; + +fn guid_bytes(g: &GUID) -> (u32, u16, u16, [u8; 8]) { + (g.data1, g.data2, g.data3, g.data4) +} + +fn once(counter: &AtomicU64, n: u64) -> bool { + counter.fetch_add(1, Ordering::Relaxed) < n +} + +/// a console list / allocator type → the PC one +pub fn pc_list_type(t: u32) -> u32 { + if t == XBOX_TYPE_DMA { + D3D12_COMMAND_LIST_TYPE_COPY.0 as u32 + } else { + t + } +} + +/// D3D12_COMMAND_QUEUE_DESC { type, priority, flags, node mask } of the console → PC +pub fn pc_queue_desc(d: [u32; 4]) -> [u32; 4] { + let priority = match d[1] { + 0 | 100 | 10000 => d[1], // NORMAL, HIGH, GLOBAL_REALTIME + _ => 100, + }; + [pc_list_type(d[0]), priority, d[2], if d[3] == 0 { 0 } else { 1 }] +} + +/// device #8 CreateCommandQueue / #48 CreateCommandQueueX(desc, riid, queue) +pub(super) unsafe extern "system" fn create_command_queue_x(this: *mut c_void, desc: *const [u32; 4], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let d = if desc.is_null() { [0; 4] } else { pc_queue_desc(desc.read_unaligned()) }; + real::dev_create_command_queue(this, d.as_ptr() as usize, riid, ppv) +} + +/// device #9 CreateCommandAllocator(type, riid, allocator) +pub(super) unsafe extern "system" fn create_command_allocator_x(this: *mut c_void, ty: u32, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + real::dev_create_command_allocator(this, pc_list_type(ty) as usize, riid, ppv) +} + +unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let dma = !riid.is_null() && guid_bytes(&*riid) == guid_bytes(&IID_XBOX_DMA_COMMAND_LIST); + let riid = if dma { &IID_GRAPHICS_COMMAND_LIST as *const GUID } else { riid }; + let (node, ty) = (if node == 0 { 0 } else { 1 }, pc_list_type(ty) as usize); + if super::console_list::enabled() { + real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) + } else { + real::dev_create_command_list(this, node, ty, alloc, pso, riid, ppv) + } +} + +/// device #12 CreateCommandList(node mask, type, allocator, initial pipeline, riid, list): +/// console list types and the DMA list's IID +pub(super) unsafe extern "system" fn create_command_list_pc(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + create_list(this, node, ty, alloc, pso, riid, ppv) +} + +/// device #73 CreateCommandListX(params { type @0; node mask @8 }, allocator, initial +/// pipeline, riid, list) +pub(super) unsafe extern "system" fn create_command_list_x(this: *mut c_void, params: *const u32, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let (ty, node) = if params.is_null() { (0, 1) } else { (params.read_unaligned(), params.add(2).read_unaligned()) }; + create_list(this, node, ty, alloc, pso, riid, ppv) +} + +/// device #60 CreateGraphicsPipelineStateX(desc, extension count, extensions, riid, pipeline): +/// the desc is a PC D3D12_GRAPHICS_PIPELINE_STATE_DESC with console shaders; the extensions +/// are not modelled +pub(super) unsafe extern "system" fn create_graphics_pso_x(this: *mut c_void, desc: *const c_void, extensions: u32, _ext: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + static N: AtomicU64 = AtomicU64::new(0); + if extensions != 0 && once(&N, 1) { + crate::xlog_info!("D3D12.X: CreateGraphicsPipelineStateX with {extensions} extension(s) – not modelled"); + } + real::dev_create_graphics_pso(this, desc, riid, ppv) +} + +/// device #86 CreatePipelineState(stream desc, riid, pipeline) +pub(super) unsafe extern "system" fn create_pipeline_state_x(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + real::dev_create_pipeline_state(this, desc, riid, ppv) +} + +/// device #56 / #66 SerializePipelineStateX: not available in a release title +pub(super) unsafe extern "system" fn serialize_pso_x(_this: *mut c_void, _pso: *mut c_void) -> HRESULT { + E_ACCESSDENIED +} + +/// device #57 / #67 Deserialize{Graphics,Compute}PipelineStateX(state, riid, pipeline): the +/// serialised form is the console driver's; the title creates the pipeline from its desc +pub(super) unsafe extern "system" fn deserialize_pso_x(_this: *mut c_void, _state: *const u8, _riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + static N: AtomicU64 = AtomicU64::new(0); + if once(&N, 1) { + crate::xlog_warn!("D3D12.X: DeserializePipelineStateX – console pipeline caches are not supported"); + } + if !ppv.is_null() { + *ppv = std::ptr::null_mut(); + } + E_NOTIMPL +} + +/// device #52 SetDebugFlagsX(flags) +pub(super) unsafe extern "system" fn set_debug_flags_x(_this: *mut c_void, _flags: u32) -> HRESULT { + S_OK +} + +static PAGE_POOLS: Mutex> = Mutex::new(Vec::new()); + +/// device #74 RegisterPagePoolX(address, pages, index out) +pub(super) unsafe extern "system" fn register_page_pool_x(_this: *mut c_void, va: u64, pages: u32, out: *mut u32) -> HRESULT { + if va == 0 || pages == 0 { + return E_INVALIDARG; + } + let mut p = PAGE_POOLS.lock().unwrap(); + let i = p.iter().position(|&e| e == (va, pages)).unwrap_or_else(|| { + p.push((va, pages)); + p.len() - 1 + }); + if !out.is_null() { + *out = i as u32; + } + S_OK +} + +/// device #75 UnregisterPagePoolX(index) +pub(super) unsafe extern "system" fn unregister_page_pool_x(_this: *mut c_void, index: u64) -> HRESULT { + match PAGE_POOLS.lock().unwrap().get_mut(index as usize) { + Some(e) if e.1 != 0 => { + *e = (0, 0); + S_OK + } + _ => E_FAIL, + } +} + +/// device #61 CreateSamplerX(desc, destination): the title uses it for anisotropic samplers; +/// the console desc (0x6C bytes) carries the PC fields at other offsets (+0x18 address U / V / +/// W, +0x24 / +0x28 min / max LOD, +0x2C bias, +0x34 max anisotropy, +0x40 comparison); its +/// further anisotropy fields are not modelled +pub(super) unsafe extern "system" fn create_sampler_x(this: *mut c_void, x: *const u8, dest: u64) { + if x.is_null() || !crate::gpu::shader::readable(x as usize, 0x6C) { + return; + } + let u = |o: usize| (x.add(o) as *const u32).read_unaligned(); + let d = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_ANISOTROPIC, + AddressU: D3D12_TEXTURE_ADDRESS_MODE(u(0x18) as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(u(0x1C) as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(u(0x20) as i32), + MipLODBias: f32::from_bits(u(0x2C)), + MaxAnisotropy: u(0x34).clamp(1, 16), + ComparisonFunc: D3D12_COMPARISON_FUNC(u(0x40) as i32), + BorderColor: [0.0; 4], + MinLOD: f32::from_bits(u(0x24)), + MaxLOD: f32::from_bits(u(0x28)), + }; + real::dev_create_sampler_x(this, &d, dest); +} + +/// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts +/// and console flag bits mean nothing to a PC driver +pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { + let mut d = *x; + let dim = u32::from_le_bytes(d[0..4].try_into().unwrap()); + let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); + d[8..16].fill(0); // alignment: the driver's + let layout = if dim == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { D3D12_TEXTURE_LAYOUT_ROW_MAJOR.0 } else { D3D12_TEXTURE_LAYOUT_UNKNOWN.0 }; + d[0x2C..0x30].copy_from_slice(&(layout as u32).to_le_bytes()); + d[0x30..0x34].copy_from_slice(&(flags & 0xFF).to_le_bytes()); + d +} + +/// device #44 CreatePlacedResourceX(address, desc, initial state, clear value, riid, resource): +/// a resource in title memory. A buffer at a 64 KiB-aligned address in unified memory is that +/// memory (placed in its UMA heap); anything else gets memory of its own – a texture's console +/// tiling has no PC equivalent, so what the title writes at the address is not seen there. +pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + static N: AtomicU64 = AtomicU64::new(0); + if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { + return E_INVALIDARG; + } + let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + let d = pc_resource_desc(&x); + let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + if buffer { + if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) { + return hr; + } + } + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv); + if hr < 0 || once(&N, 4) { + let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + crate::xlog_info!( + "D3D12.X: CreatePlacedResourceX at {va:#x}: dimension {} {}x{} format {} flags {:#x} – a resource of its own ({hr:#x})", + w(0), + u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), + w(0x18), + w(0x20), + w(0x30) + ); + } + hr +} + +/// device #38 GetCopyableFootprints: a console resource desc the PC rejects (total stays +/// UINT64_MAX) is asked again as the PC desc XCL creates for it +#[allow(clippy::too_many_arguments)] +pub(super) unsafe extern "system" fn get_copyable_footprints_x( + this: *mut c_void, + desc: *const u8, + first: u32, + num: u32, + base: u64, + layouts: *mut c_void, + rows: *mut u32, + row_sizes: *mut u64, + total: *mut u64, +) { + type F = unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u64, *mut c_void, *mut u32, *mut u64, *mut u64); + let f: F = std::mem::transmute(real::orig_fn(this, 38)); + if desc.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { + return f(this, desc, first, num, base, layouts, rows, row_sizes, total); + } + let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + let mut probe = u64::MAX; + let t = if total.is_null() { &mut probe as *mut u64 } else { total }; + *t = u64::MAX; + f(this, x.as_ptr(), first, num, base, layouts, rows, row_sizes, t); + if *t == u64::MAX { + let d = pc_resource_desc(&x); + f(this, d.as_ptr(), first, num, base, layouts, rows, row_sizes, total); + } +} + +/// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's +/// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments +/// that need one (constants, CBV / SRV / UAV) +pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + if desc.is_null() || ppv.is_null() { + return E_INVALIDARG; + } + let mut pc = [0u8; 24]; + std::ptr::copy_nonoverlapping(desc, pc.as_mut_ptr(), 24); + let n = u32::from_le_bytes(pc[4..8].try_into().unwrap()) as usize; + let args = u64::from_le_bytes(pc[8..16].try_into().unwrap()) as *const [u32; 4]; + let mut list: Vec<[u32; 4]> = if args.is_null() || n > 64 { Vec::new() } else { (0..n).map(|i| args.add(i).read_unaligned()).collect() }; + for a in list.iter_mut() { + if a[0] == XBOX_ARG_DISPATCH_X { + a[0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + } + } + let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); + pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); + real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_types_and_descs_become_pc_ones() { + assert_eq!(pc_list_type(XBOX_TYPE_DMA), D3D12_COMMAND_LIST_TYPE_COPY.0 as u32); + assert_eq!(pc_list_type(2), 2); + assert_eq!(pc_queue_desc([XBOX_TYPE_DMA, 1, 0, 0x10]), [3, 100, 0, 1]); + assert_eq!(pc_queue_desc([0, 10000, 1, 0]), [0, 10000, 1, 0]); + let mut x = [0u8; 0x38]; + x[0] = 1; // buffer + x[8] = 0x40; // alignment + x[0x2C] = 0x22; // console layout + x[0x30..0x34].copy_from_slice(&0x1234u32.to_le_bytes()); + let d = pc_resource_desc(&x); + assert_eq!((d[8], u32::from_le_bytes(d[0x2C..0x30].try_into().unwrap()), u32::from_le_bytes(d[0x30..0x34].try_into().unwrap())), (0, 1, 0x34)); + x[0] = 3; // texture 2D + assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x2C..0x30].try_into().unwrap()), 0); + } + + #[test] + fn page_pools_register_once_and_unregister() { + unsafe { + let mut i = u32::MAX; + assert_eq!(register_page_pool_x(std::ptr::null_mut(), 0x1_0000_0000, 16, &mut i), S_OK); + let mut j = u32::MAX; + assert_eq!(register_page_pool_x(std::ptr::null_mut(), 0x1_0000_0000, 16, &mut j), S_OK); + assert_eq!(i, j); + assert_eq!(register_page_pool_x(std::ptr::null_mut(), 0, 16, &mut j), E_INVALIDARG); + assert_eq!(unregister_page_pool_x(std::ptr::null_mut(), i as u64), S_OK); + assert_eq!(unregister_page_pool_x(std::ptr::null_mut(), i as u64), E_FAIL); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 01cc48b..09372b8 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -11,6 +11,7 @@ pub mod console_heap; pub mod console_list; +pub mod device_x; pub mod frame; pub mod guard; pub mod layout; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e279c9d..c5d21c0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -161,11 +161,11 @@ static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); /// the UMA windows opened as D3D12 heaps (console buffers are placed in them) static UMA_HEAPS: Mutex> = Mutex::new(Vec::new()); /// console buffers placed in unified memory: resource → (address, bytes) -static UMA_BUFFERS: Mutex>> = Mutex::new(None); +static UMA_BUFFERS: Mutex>> = Mutex::new(None); /// Where a console-created buffer lives in unified memory (its console GPU address). pub fn console_buffer(res: usize) -> Option<(usize, usize)> { - UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).copied() + UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).map(|&(p, n, _)| (p, n)) } /// Number of live console buffers in unified memory. @@ -489,6 +489,15 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { v[1 + slot] = f; } } + // the device's other console extensions: a title call is logged and answered S_OK, not run + // as the PC method at that index + if kind == Kind::Device { + let own: HashSet = console_slots(kind).iter().map(|e| e.0).collect(); + for i in (CONSOLE_DEVICE_EXTENSIONS..public).filter(|i| !own.contains(i)) { + let (stub, _) = stubs::make_stub_info(DLL, &format!("{}::#{i} (console extension)", iface.name), 0); + v[1 + i] = super::guard::make_split(stub, v[1 + i]); + } + } // XCL_D3D12_TRACE: every public method called from console code is logged if std::env::var_os("XCL_D3D12_TRACE").is_some() { for i in 0..public { @@ -539,10 +548,20 @@ fn console_remap(kind: Kind) -> Vec<(usize, usize)> { } } +/// console D3D12_DESCRIPTOR_HEAP_TYPE also used for CBV / SRV / UAV heaps +const XBOX_EXTRA_CBV_SRV_UAV: u32 = 4; + +/// The console device's methods from #44 on are its own extensions (`device_x`). +const CONSOLE_DEVICE_EXTENSIONS: usize = 44; + fn console_slots(kind: Kind) -> Vec<(usize, usize)> { + use super::device_x as x; match kind { Kind::Device => { - let mut v = vec![ + vec![ + (8, x::create_command_queue_x as usize), + (9, x::create_command_allocator_x as usize), + (12, x::create_command_list_pc as usize), (14, dev_create_descriptor_heap_x as usize), (15, dev_increment_size_x as usize), (17, dev_create_cbv_x as usize), @@ -551,7 +570,21 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (22, dev_create_sampler_x as usize), (23, dev_copy_descriptors_x as usize), (24, dev_copy_descriptors_simple_x as usize), + (38, x::get_copyable_footprints_x as usize), + (41, x::create_command_signature_x as usize), + (44, x::create_placed_resource_x as usize), + (48, x::create_command_queue_x as usize), + (52, x::set_debug_flags_x as usize), + (56, x::serialize_pso_x as usize), + (57, x::deserialize_pso_x as usize), + (60, x::create_graphics_pso_x as usize), + (61, x::create_sampler_x as usize), (62, dev_create_compute_pso_x as usize), + (66, x::serialize_pso_x as usize), + (67, x::deserialize_pso_x as usize), + (73, x::create_command_list_x as usize), + (74, x::register_page_pool_x as usize), + (75, x::unregister_page_pool_x as usize), (76, dev_create_committed_resource_x as usize), // frame pacing (SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX, // GetFrameStatisticsX) @@ -559,11 +592,8 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (79, super::frame::schedule_frame_event_x as usize), (80, super::frame::wait_frame_event_x as usize), (81, super::frame::frame_statistics_x as usize), - ]; - if super::console_list::enabled() { - v.push((12, dev_create_command_list_x as usize)); - } - v + (86, x::create_pipeline_state_x as usize), + ] } Kind::DescriptorHeap => vec![(9, heap_cpu_start_x as usize), (10, heap_gpu_start_x as usize)], Kind::Resource => vec![(11, res_gpu_va_x as usize)], @@ -596,7 +626,11 @@ unsafe extern "system" fn heap_gpu_start_x(this: *mut c_void) -> u64 { } unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: *const [u32; 4], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let d = if desc.is_null() { [u32::MAX; 4] } else { *desc }; + let mut d = if desc.is_null() { [u32::MAX; 4] } else { *desc }; + if d[0] == XBOX_EXTRA_CBV_SRV_UAV { + d[0] = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32; + } + let desc = if desc.is_null() { desc } else { &d as *const [u32; 4] }; let sampler = d[0] == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32; if d[0] != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 && !sampler { return dev_create_descriptor_heap(this, desc as usize, riid, ppv); @@ -619,6 +653,7 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: } unsafe extern "system" fn dev_increment_size_x(this: *mut c_void, ty: u32) -> u32 { + let ty = if ty == XBOX_EXTRA_CBV_SRV_UAV { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 } else { ty }; if ty == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 { return super::console_heap::SLOT; } @@ -731,7 +766,7 @@ unsafe fn place_console_buffer(this: *mut c_void, desc: usize, state: usize, cle } return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes)); + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -751,13 +786,37 @@ unsafe fn place_console_buffer(this: *mut c_void, desc: usize, state: usize, cle Some(hr) } +/// A buffer the title places at its own address (CreatePlacedResourceX): at a placement +/// boundary (64 KiB) in unified memory it is that memory, placed in the window's heap; the +/// title's allocation stays the title's. +pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: &[u8; 0x38], state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + let u = crate::gpu::uma::get()?; + let k = u.window_of(va)?; + let (base, size) = u.window(k); + let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); + let bytes = d.Width as usize; + if va % 0x1_0000 != 0 || bytes == 0 || va - base + bytes > size { + return None; + } + let heap = *UMA_HEAPS.lock().unwrap().get(k)?; + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Alignment = 0; + let hr = dev_create_placed_resource(this, heap, va - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); + if hr < 0 || (*ppv).is_null() { + return None; + } + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + Some(hr) +} + /// resource Release (every caller): a console buffer's unified memory goes with it unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); - if let (Some((p, _)), Some(u)) = (gone, crate::gpu::uma::get()) { + if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { u.free(p); } } @@ -819,7 +878,7 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 /// #22 CreateSampler: the PC sampler at the slot's index, the S# in XCL ABI form (word 3 /// [11:0] = sampler heap index; the state lives in the PC sampler). -unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, desc: *const D3D12_SAMPLER_DESC, cpu: u64) { +pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, desc: *const D3D12_SAMPLER_DESC, cpu: u64) { let f: unsafe extern "system" fn(*mut c_void, *const D3D12_SAMPLER_DESC, u64) = std::mem::transmute(orig_fn(this, 22)); let Some(slot) = super::console_heap::slot(cpu).filter(|s| s.sampler) else { return f(this, desc, cpu) }; f(this, desc, slot.pc_srv); @@ -1043,7 +1102,7 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro hr } -unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void, mask: usize, ty: usize, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +pub(super) unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void, mask: usize, ty: usize, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let pc_pso = super::console_list::pc_pso(pso as *mut c_void) as usize; let hr = dev_create_command_list(this, mask, ty, alloc, pc_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { @@ -1138,7 +1197,7 @@ macro_rules! as_usize { /// Device creation methods ending in (REFIID riid, void** ppv). macro_rules! creator { ($name:ident, $method:literal, $kind:expr, [$($a:ident),*]) => { - unsafe extern "system" fn $name(this: *mut c_void, $($a: usize,)* riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + pub(super) unsafe extern "system" fn $name(this: *mut c_void, $($a: usize,)* riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void, $(as_usize!($a),)* *const GUID, *mut *mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(this, slot_of(this, $method))); let mut hr = f(this, $($a,)* riid, ppv); @@ -1659,7 +1718,7 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { matches!(translated_mesh_stream(dev.0 as *mut c_void, d.ptr(), &iid, out), Some(hr) if hr >= 0) } -unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); 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) }; @@ -1981,7 +2040,7 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { Some((buf, [size, 0])) } -unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_stream_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_mesh_stream(this, desc, riid, ppv)) } else { (translated_mesh_stream(this, desc, riid, ppv), false) }; diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index d7f37cd..3be257a 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -323,6 +323,97 @@ pub fn present_x_frame() -> Result<(), String> { } } +/// The console device's own methods as a title calls them: a buffer placed at the title's +/// graphics memory (#44 CreatePlacedResourceX) is copied by a DMA queue (#48 +/// CreateCommandQueueX), allocator (#9) and list (#73 CreateCommandListX, the DMA list's IID) +/// into a readback buffer; page pools (#74 / #75), SetDebugFlagsX (#52), +/// SerializePipelineStateX (#56) and an extension XCL does not model (#47). +pub fn console_device_methods() -> Result<(), String> { + const DMA: u32 = 0x10; + const IID_DMA_LIST: windows::core::GUID = windows::core::GUID::from_u128(0x30bc77b9_8379_4b25_95de_b8588c42275d); + type Create = unsafe extern "system" fn(*mut c_void, *const u32, *const windows::core::GUID, *mut *mut c_void) -> HRESULT; + type PlacedX = unsafe extern "system" fn(*mut c_void, u64, *const D3D12_RESOURCE_DESC, u32, *const c_void, *const windows::core::GUID, *mut *mut c_void) -> HRESULT; + type ListX = unsafe extern "system" fn(*mut c_void, *const u32, *mut c_void, *mut c_void, *const windows::core::GUID, *mut *mut c_void) -> HRESULT; + unsafe { + let dev = device()?; + let d = dev.as_raw(); + let slot = |obj: *mut c_void, i: usize| *(*(obj as *const *const usize)).add(i); + let n = 0x1_0000usize; + let graphics = 1u64 << 29; + let mem = crate::XMemAlloc(n, graphics) as *mut u32; + ensure!(!mem.is_null() && mem as usize % n == 0, "graphics memory {mem:?}"); + for i in 0..n / 4 { + *mem.add(i) = 0xC0DE_0000 | i as u32; + } + let buffer = |width: usize| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let placed: PlacedX = std::mem::transmute(slot(d, 44)); + let mut raw = std::ptr::null_mut(); + let hr = placed(d, mem as u64, &buffer(n), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), &ID3D12Resource::IID, &mut raw); + ensure!(hr >= 0 && !raw.is_null(), "CreatePlacedResourceX hr={hr:#x}"); + let src = ID3D12Resource::from_raw(raw); + ensure!(src.GetGPUVirtualAddress() == mem as u64, "placed buffer at {:#x}, not the title's {mem:?}", src.GetGPUVirtualAddress()); + let mut dst: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &buffer(n), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut dst, + ) + .map_err(e)?; + let dst = dst.ok_or("no readback buffer")?; + + let queue_x: Create = std::mem::transmute(slot(d, 48)); + let mut raw = std::ptr::null_mut(); + let hr = queue_x(d, [DMA, 0, 0, 0].as_ptr(), &ID3D12CommandQueue::IID, &mut raw); + ensure!(hr >= 0 && !raw.is_null(), "CreateCommandQueueX (DMA) hr={hr:#x}"); + let queue = ID3D12CommandQueue::from_raw(raw); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(DMA as i32)).map_err(e)?; + let list_x: ListX = std::mem::transmute(slot(d, 73)); + let mut raw = std::ptr::null_mut(); + let hr = list_x(d, [DMA, 0, 1, 0].as_ptr(), alloc.as_raw(), std::ptr::null_mut(), &IID_DMA_LIST, &mut raw); + ensure!(hr >= 0 && !raw.is_null(), "CreateCommandListX (DMA) hr={hr:#x}"); + let list = ID3D12GraphicsCommandList::from_raw(raw); + list.CopyBufferRegion(&dst, 0, &src, 0, n as u64); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + wait(&queue, &fence, 1)?; + let mut p: *mut c_void = std::ptr::null_mut(); + dst.Map(0, None, Some(&mut p)).map_err(e)?; + let copied = std::slice::from_raw_parts(p as *const u32, n / 4).iter().enumerate().all(|(i, &v)| v == 0xC0DE_0000 | i as u32); + dst.Unmap(0, None); + ensure!(copied, "the DMA copy did not read the title's memory"); + drop(src); + ensure!(*mem.add(7) == 0xC0DE_0007, "the title's memory went with the placed buffer"); + crate::XMemFree(mem as *mut c_void, graphics); + + let register: unsafe extern "system" fn(*mut c_void, u64, u32, *mut u32) -> HRESULT = std::mem::transmute(slot(d, 74)); + let unregister: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(slot(d, 75)); + let mut pool = u32::MAX; + ensure!(register(d, 0x2_0000_0000, 16, &mut pool) == 0 && pool != u32::MAX, "RegisterPagePoolX"); + ensure!(unregister(d, pool as u64) == 0 && unregister(d, pool as u64) < 0, "UnregisterPagePoolX"); + let debug_flags: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(slot(d, 52)); + ensure!(debug_flags(d, 1) == 0, "SetDebugFlagsX"); + let serialize: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(slot(d, 56)); + ensure!(serialize(d, std::ptr::null_mut()) == 0x8007_0005u32 as i32, "SerializePipelineStateX"); + // #47 is PC CreatePipelineState: with no arguments it would fail or crash + let unmodelled: unsafe extern "system" fn(*mut c_void, usize, usize, usize) -> HRESULT = std::mem::transmute(slot(d, 47)); + ensure!(unmodelled(d, 0, 0, 0) == 0, "console extension #47"); + Ok(()) + } +} + pub fn render_triangle() -> Result<(), String> { unsafe { let dev = device()?; diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index 249b35b..a47d505 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -439,6 +439,7 @@ fn main() { check("D3D12.X: retail-format console shader (XDAT/XBCH/FSSM) captured + fallback PSO", gpu::xbox_native_pso); check("D3D12.X: triangle rendered on the real GPU and read back", gpu::render_triangle); check("D3D12.X: frame clock + PresentX of the title's back buffer", gpu::present_x_frame); + check("D3D12.X: console device methods (placed title memory, DMA queue + list, page pools)", gpu::console_device_methods); check("XAudio2: console flags/device, XMA2 voice plays silence, PCM passes, callbacks", audio::xaudio2_console_voices); let failures = FAILURES.load(Ordering::SeqCst);