diff --git a/HANDOFF.md b/HANDOFF.md index 538ac93..6de09b2 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -569,6 +569,27 @@ must not run the PC method at that index (#44 is PC CreatePipelineLibrary, #48 O (#55, blend patch: green only → cyan over the blue clear). - Not yet: deserializing console pipeline caches, placed textures at title addresses (detiling). +## The console command list's own methods (session 5, 2026-11-21, `d3d12x/list_x.rs`) +From #60 on the console list holds its extensions (besides the moved PC methods, `real::console_remap`); a title +call there no longer runs the PC method at that index (#60 was AtomicCopyBufferUINT, #66 WriteBufferImmediate…). +Console GPU addresses in unified memory are the title's own: memory operations go to that window's buffer +(`real::uma_window_buffer`), wrapped in COMMON → COPY_DEST → COMMON transitions (the window buffers stay in COMMON). +- **#60 CopyMemoryToMemoryX**(dst, src, size, flags) → CopyBufferRegion (one window: the buffer is source and + destination, overlapping ranges are refused); **#61–#63 FillMemoryWith{32,64,128}BitValueX**(va, size, value) → a + copy from an upload buffer repeating the value (cached per value, up to 256 MiB). +- **#69 / #70 Write{32,64}BitValueBottomOfPipeX**(va, value, flush, flags), **#88 / #89 …TopOfPipeX**(va, value, + flags), **#90 Write32BitValueBottomOfShaderX** → WriteBufferImmediate (MARKER_OUT / MARKER_IN); with a timestamp + flag (bottom 1 / 2, top 4 / 8) the GPU timestamp is resolved there from a timestamp query (PC ticks). +- **#78 DispatchX** → Dispatch; **#81 DrawIndexedX**(index address, format, count, flags) → that index buffer for one + DrawIndexedInstanced, then the bound one again; **#47 IASetIndexBuffer** gives the PC the window buffer's address + for a title address; **#84 CopyResourceX** → CopyResource (in place: nothing); **#85 SetPredicationBufferX** + `{ u64 va; u32 op }`; **#68** depth bounds. +- Not modelled (logged, no-op): Wait32 / 64BitValueX #71 / #72, GDS #76 / #77, KickoffX #93 (TomBox splits the list + and submits the first part), depth bias X #94 (needs pipelines with dynamic depth bias), hints (HiStencil, MSAA, + compression, limits, prefetch). Occlusion queries that nest (the console allows it) are not un-nested yet. +- The test title writes / fills / copies its own graphics memory through #60–#89, takes a GPU timestamp, and draws + through DrawIndexedX and #47 with indices in its memory. + ## 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: diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs new file mode 100644 index 0000000..00572d3 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -0,0 +1,381 @@ +//! The console command list's own methods. +//! +//! The console's ID3D12GraphicsCommandList keeps the PC methods (some moved: +//! `real::console_remap`) and holds console extensions from #60 on (as observed on Fortnite): +//! CopyMemoryToMemoryX #60, FillMemoryWith{32,64,128}BitValueX #61–#63, depth bounds #68, +//! Write{32,64}BitValueBottomOfPipeX #69 / #70, DispatchX #78, DrawIndexedX #81, +//! CopyResourceX #84, SetPredicationBufferX #85, Write{32,64}BitValueTopOfPipeX #88 / #89, +//! Write32BitValueBottomOfShaderX #90. A title call of any other extension (waits on memory, +//! GDS, KickoffX, depth bias, hints…) is logged and does nothing (`real::class_for`). +//! +//! Console GPU addresses in unified memory are the title's own addresses; memory operations +//! go to that window's buffer (`real::uma_window_buffer`), which is in COMMON between them. +//! An index buffer at such an address is given to the PC as the window buffer's GPU address. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{transmute_copy, ManuallyDrop}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::real; + +const PC_GET_TYPE: usize = 8; +const PC_DRAW_INDEXED: usize = 13; +const PC_DISPATCH: usize = 14; +const PC_COPY_BUFFER_REGION: usize = 15; +const PC_COPY_RESOURCE: usize = 17; +const PC_RESOURCE_BARRIER: usize = 26; +const PC_IA_SET_INDEX_BUFFER: usize = 43; +const PC_END_QUERY: usize = 53; +const PC_RESOLVE_QUERY_DATA: usize = 54; +const PC_SET_PREDICATION: usize = 55; +const PC_OM_SET_DEPTH_BOUNDS: usize = 62; +const PC_WRITE_BUFFER_IMMEDIATE: usize = 66; + +/// Write64BitValueBottomOfPipeX flags 1 / 2, Write64BitValueTopOfPipeX flags 4 / 8: the value +/// written is a GPU / system timestamp +const BOTTOM_TIMESTAMPS: u32 = 0x3; +const TOP_TIMESTAMPS: u32 = 0xC; +/// fills larger than this are not done (one pattern buffer per value, up to this size) +const MAX_FILL: u64 = 256 << 20; + +fn once(counter: &AtomicU64, n: u64) -> bool { + counter.fetch_add(1, Ordering::Relaxed) < n +} + +/// a PC method of the list (its runtime's own) +unsafe fn pc(list: *mut c_void, slot: usize) -> F { + transmute_copy(&real::orig_fn(list, slot)) +} + +unsafe fn list_type(list: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + pc:: D3D12_COMMAND_LIST_TYPE>(list, PC_GET_TYPE)(list) +} + +unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: transmute_copy(&res), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + pc::(list, PC_RESOURCE_BARRIER)(list, 1, &b); +} + +/// `op` with the window buffer `res` as a copy destination (back to COMMON after it) +unsafe fn as_copy_dest(list: *mut c_void, res: usize, op: impl FnOnce()) { + transition(list, res, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + op(); + transition(list, res, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); +} + +unsafe fn copy_buffer_region(list: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + pc::(list, PC_COPY_BUFFER_REGION)(list, dst, dst_off, src, src_off, n); +} + +fn warn(counter: &AtomicU64, what: &str, why: std::fmt::Arguments) { + if once(counter, 4) { + crate::xlog_warn!("D3D12.X: {what}: {why} – not done"); + } +} + +/// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) +pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { + static N: AtomicU64 = AtomicU64::new(0); + const W: &str = "CopyMemoryToMemoryX"; + if size == 0 || !size.is_multiple_of(4) { + return warn(&N, W, format_args!("size {size:#x} is not a non-zero multiple of 4")); + } + let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { + return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); + }; + if d == s && dst < src + size && src < dst + size { + return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); + } + if d == s { + // one window: the buffer is the source and the destination (the ranges do not overlap) + as_copy_dest(this, d, || copy_buffer_region(this, d, doff, s, soff, size)); + return; + } + transition(this, s, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + as_copy_dest(this, d, || copy_buffer_region(this, d, doff, s, soff, size)); + transition(this, s, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); +} + +unsafe fn device_of(list: *mut c_void) -> Option { + let mut dev: Option = None; + ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; + dev +} + +/// upload buffers holding a repeated 16-byte pattern: (pattern, buffer, bytes) +static PATTERNS: Mutex> = Mutex::new(Vec::new()); + +/// A buffer of at least `n` bytes repeating `pat` (the device's upload heap). +unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option { + let mut cache = PATTERNS.lock().unwrap(); + if let Some((_, b, _)) = cache.iter().find(|(p, _, len)| *p == pat && *len >= n) { + return Some(b.as_raw() as usize); + } + // a larger one replaces an older pattern buffer only when nothing may still read it: kept + if cache.len() >= 32 { + return None; + } + let dev = device_of(list)?; + let len = n.next_power_of_two().max(0x1_0000); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: len, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut b: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut b, + ) + .ok()?; + let b = b?; + let mut p: *mut c_void = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).ok()?; + for chunk in std::slice::from_raw_parts_mut(p as *mut u8, len as usize).chunks_exact_mut(16) { + chunk.copy_from_slice(&pat); + } + b.Unmap(0, None); + let raw = b.as_raw() as usize; + cache.push((pat, b, len)); + Some(raw) +} + +unsafe fn fill(list: *mut c_void, va: u64, size: u64, pat: [u8; 16], unit: u64, what: &str) { + static N: AtomicU64 = AtomicU64::new(0); + if size == 0 || !size.is_multiple_of(unit) || size > MAX_FILL { + return warn(&N, what, format_args!("size {size:#x} (a non-zero multiple of {unit} up to {MAX_FILL:#x} is filled)")); + } + let Some((d, off)) = real::uma_window_buffer(va as usize, size as usize) else { + return warn(&N, what, format_args!("{va:#x} ({size:#x} bytes) is not in unified memory")); + }; + let Some(src) = pattern_buffer(list, pat, size) else { + return warn(&N, what, format_args!("no pattern buffer for {pat:x?}")); + }; + as_copy_dest(list, d, || copy_buffer_region(list, d, off, src, 0, size)); +} + +fn pattern(bytes: &[u8]) -> [u8; 16] { + let mut p = [0u8; 16]; + for (i, b) in p.iter_mut().enumerate() { + *b = bytes[i % bytes.len()]; + } + p +} + +/// command list #61 FillMemoryWith32BitValueX(address, size, value) +pub(super) unsafe extern "system" fn fill32_x(this: *mut c_void, va: u64, size: u64, value: u32) { + fill(this, va, size, pattern(&value.to_le_bytes()), 4, "FillMemoryWith32BitValueX"); +} + +/// command list #62 FillMemoryWith64BitValueX(address, size, value) +pub(super) unsafe extern "system" fn fill64_x(this: *mut c_void, va: u64, size: u64, value: u64) { + fill(this, va, size, pattern(&value.to_le_bytes()), 8, "FillMemoryWith64BitValueX"); +} + +/// command list #63 FillMemoryWith128BitValueX(address, size, value*) +pub(super) unsafe extern "system" fn fill128_x(this: *mut c_void, va: u64, size: u64, value: *const [u8; 16]) { + if !value.is_null() { + fill(this, va, size, value.read_unaligned(), 16, "FillMemoryWith128BitValueX"); + } +} + +/// Values written by the GPU at `va` (WriteBufferImmediate: MARKER_IN = when the command is +/// reached, MARKER_OUT = when the work before it is done). +unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFFERIMMEDIATE_MODE, what: &str) { + static N: AtomicU64 = AtomicU64::new(0); + let n = 4 * words.len() as u64; + if !va.is_multiple_of(n) { + return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); + } + let (Some((d, _)), Some(at)) = (real::uma_window_buffer(va as usize, n as usize), real::uma_va_of(va as usize)) else { + return warn(&N, what, format_args!("{va:#x} is not in unified memory")); + }; + let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); + let modes = vec![mode; words.len()]; + type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); + as_copy_dest(list, d, || pc::(list, PC_WRITE_BUFFER_IMMEDIATE)(list, params.len() as u32, params.as_ptr(), modes.as_ptr())); +} + +/// timestamp queries (one heap per device, used round-robin) +static TIMESTAMPS: Mutex>> = Mutex::new(None); +const TIMESTAMP_SLOTS: u32 = 4096; +static NEXT_TIMESTAMP: AtomicU32 = AtomicU32::new(0); + +/// The GPU timestamp (the PC queue's ticks) written at `va` when the work before it is done. +unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { + static N: AtomicU64 = AtomicU64::new(0); + let ty = list_type(list); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return warn(&N, what, format_args!("a timestamp on a type-{} list", ty.0)); + } + let Some((d, off)) = real::uma_window_buffer(va as usize, 8).filter(|_| va.is_multiple_of(8)) else { + return warn(&N, what, format_args!("{va:#x} is not 8-byte aligned in unified memory")); + }; + let Some(dev) = device_of(list) else { return }; + let heap = { + let mut m = TIMESTAMPS.lock().unwrap(); + let m = m.get_or_insert_with(HashMap::new); + if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(dev.as_raw() as usize) { + let mut h: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: TIMESTAMP_SLOTS, NodeMask: 0 }; + match dev.CreateQueryHeap(&desc, &mut h) { + Ok(()) if h.is_some() => slot.insert(h.unwrap()), + _ => return warn(&N, what, format_args!("no timestamp query heap")), + }; + } + m[&(dev.as_raw() as usize)].as_raw() as usize + }; + let i = NEXT_TIMESTAMP.fetch_add(1, Ordering::Relaxed) % TIMESTAMP_SLOTS; + pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); + type Resolve = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); + as_copy_dest(list, d, || pc::(list, PC_RESOLVE_QUERY_DATA)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, d, off)); +} + +/// command list #69 Write32BitValueBottomOfPipeX(address, value, flush, flags) +pub(super) unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, _flags: u32) { + write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfPipeX"); +} + +/// command list #70 Write64BitValueBottomOfPipeX(address, value, flush, flags) +pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64, value: u64, _flush: u32, flags: u32) { + const W: &str = "Write64BitValueBottomOfPipeX"; + if flags & BOTTOM_TIMESTAMPS != 0 { + return timestamp(this, va, W); + } + write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, W); +} + +/// command list #88 Write32BitValueTopOfPipeX(address, value, flags) +pub(super) unsafe extern "system" fn write32_top_x(this: *mut c_void, va: u64, value: u32, _flags: u32) { + write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, "Write32BitValueTopOfPipeX"); +} + +/// command list #89 Write64BitValueTopOfPipeX(address, value, flags) +pub(super) unsafe extern "system" fn write64_top_x(this: *mut c_void, va: u64, value: u64, flags: u32) { + const W: &str = "Write64BitValueTopOfPipeX"; + if flags & TOP_TIMESTAMPS != 0 { + return timestamp(this, va, W); + } + write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, W); +} + +/// command list #90 Write32BitValueBottomOfShaderX(address, value, stage) +pub(super) unsafe extern "system" fn write32_bottom_of_shader_x(this: *mut c_void, va: u64, value: u32, _stage: u32) { + write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfShaderX"); +} + +/// command list #68 OMSetDepthBounds(min, max) (PC #62) +pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: f32, max: f32) { + pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); +} + +/// command list #78 DispatchX(x, y, z, flags) +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { + pc::(this, PC_DISPATCH)(this, x, y, z); +} + +/// command list #84 CopyResourceX(destination, source, flags); in place (the console's +/// compression operations) there is nothing to do on PC +pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize, _flags: u32) { + if dst != src { + pc::(this, PC_COPY_RESOURCE)(this, dst, src); + } +} + +/// command list #85 SetPredicationBufferX({ u64 address; u32 operation }*) +pub(super) unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: *const u64) { + static N: AtomicU64 = AtomicU64::new(0); + type F = unsafe extern "system" fn(*mut c_void, usize, u64, D3D12_PREDICATION_OP); + let f = pc::(this, PC_SET_PREDICATION); + if desc.is_null() { + return f(this, 0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + } + let (va, op) = (desc.read_unaligned(), (desc.add(1) as *const u32).read_unaligned()); + let Some((b, off)) = real::uma_window_buffer(va as usize, 8).filter(|_| va.is_multiple_of(8)) else { + return warn(&N, "SetPredicationBufferX", format_args!("{va:#x} is not 8-byte aligned in unified memory")); + }; + transition(this, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); + f(this, b, off, D3D12_PREDICATION_OP(op as i32)); + transition(this, b, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); +} + +/// the index buffer each list has bound (PC addresses), for DrawIndexedX to restore +static INDEX_BUFFERS: Mutex>> = Mutex::new(None); + +/// a console GPU address as the PC's (unified memory: the window buffer's) +fn pc_va(va: u64) -> u64 { + real::uma_va_of(va as usize).unwrap_or(va) +} + +unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_VIEW>) { + let f = pc::(list, PC_IA_SET_INDEX_BUFFER); + f(list, view.map_or(std::ptr::null(), |v| v as *const _)); +} + +/// command list #47 IASetIndexBuffer(view) (PC #43): the address is the title's +pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) { + let mut m = INDEX_BUFFERS.lock().unwrap(); + let m = m.get_or_insert_with(HashMap::new); + if view.is_null() { + m.remove(&(this as usize)); + return set_index_buffer(this, None); + } + let mut v = view.read_unaligned(); + v.BufferLocation = pc_va(v.BufferLocation); + m.insert(this as usize, v); + set_index_buffer(this, Some(&v)); +} + +/// command list #81 DrawIndexedX(index address, index format, index count, flags): one +/// instance of `count` indices read from that address; the bound index buffer stays +pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, format: DXGI_FORMAT, count: u32, _flags: u32) { + static N: AtomicU64 = AtomicU64::new(0); + let stride = match format { + DXGI_FORMAT_R16_UINT => 2, + DXGI_FORMAT_R32_UINT => 4, + f => return warn(&N, "DrawIndexedX", format_args!("index format {}", f.0)), + }; + if count == 0 { + return; + } + let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: pc_va(va), SizeInBytes: count.saturating_mul(stride), Format: format }; + set_index_buffer(this, Some(&view)); + pc::(this, PC_DRAW_INDEXED)(this, count, 1, 0, 0, 0); + let bound = INDEX_BUFFERS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); + set_index_buffer(this, bound.as_ref()); +} + +#[cfg(test)] +mod tests { + #[test] + fn fill_patterns_repeat_the_value() { + assert_eq!(super::pattern(&0x1122_3344u32.to_le_bytes())[..8], [0x44, 0x33, 0x22, 0x11, 0x44, 0x33, 0x22, 0x11]); + assert_eq!(super::pattern(&[7u8; 16]), [7u8; 16]); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 09372b8..2439191 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -15,6 +15,7 @@ pub mod device_x; pub mod frame; pub mod guard; pub mod layout; +pub mod list_x; pub mod null; pub mod present; pub mod pso_async; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4bec646..8377c8d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -161,7 +161,9 @@ 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); +/// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX) +type UmaBuffer = (usize, usize, bool); +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)> { @@ -184,6 +186,17 @@ pub fn uma_window_vas() -> Vec { UMA_BUFFER.lock().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() } +/// The window buffer holding `len` bytes at UMA address `p`, and their offset in it. +pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { + let u = crate::gpu::uma::get()?; + let k = u.window_of(p)?; + let (base, size) = u.window(k); + if p - base + len > size { + return None; + } + Some((UMA_BUFFER.lock().ok()?.get(k)?.0, (p - base) as u64)) +} + /// GPU virtual address of a UMA address (None: not in UMA or not open on the GPU). pub fn uma_va_of(p: usize) -> Option { let u = crate::gpu::uma::get()?; @@ -489,11 +502,11 @@ 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)) { + // the other console extensions (device, command list): a title call is logged and answered + // S_OK, not run as the PC method at that index + if let Some(first) = console_extensions(kind) { + let own: HashSet = console_slots(kind).iter().map(|e| e.0).chain(console_remap(kind).iter().map(|e| e.0)).collect(); + for i in (first..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]); } @@ -517,6 +530,33 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { ext } +/// (console slot, PC slot) of PC methods that sit elsewhere in the console's vtable. +/// ID3D12GraphicsCommandList (from the Fortnite RHI call sites, matching XCL's own evidence +/// – FSR4 calls ClearUnorderedAccessViewUint at #53): 0–27 and 56–59 as on PC; the query +/// methods come right after ExecuteBundle (28–31 = PC 52–55: BeginQuery, EndQuery, +/// ResolveQueryData, SetPredication), so SetDescriptorHeaps … DiscardResource move up by 4 +/// (32–55 = PC 28–51); ID3D12GraphicsCommandList1 is at 104–109 (PC 60–65), the shading-rate +/// methods at 124 / 125 (PC 77 / 78). The console-only methods in between: `list_x`. +fn console_remap(kind: Kind) -> Vec<(usize, usize)> { + match kind { + Kind::CommandList => (28..=31).map(|x| (x, x + 24)).chain((32..=55).map(|x| (x, x - 4))).chain((104..=109).map(|x| (x, x - 44))).chain([(124, 77), (125, 78)]).collect(), + _ => Vec::new(), + } +} + +/// console D3D12_DESCRIPTOR_HEAP_TYPE also used for CBV / SRV / UAV heaps +const XBOX_EXTRA_CBV_SRV_UAV: u32 = 4; + +/// Where a class's console extensions start: the device's from #44 (`device_x`), the command +/// list's from #60 (`list_x`). +fn console_extensions(kind: Kind) -> Option { + match kind { + Kind::Device => Some(44), + Kind::CommandList => Some(60), + _ => None, + } +} + /// Console vtable slots that differ from the PC layout (found on console code calling them): /// * device #62: `CreateComputePipelineState` with two extra arguments (XboxBvhBuilder.dll /// passes a D3D12_COMPUTE_PIPELINE_STATE_DESC, NULL, NULL, riid, ppv); PC #62 = CreateStateObject. @@ -532,28 +572,10 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { /// CBV/SRV/UAV and sampler heaps of console code get 32 / 16-byte slots in unified memory /// (`console_heap`). #14–#19 seen from console code with the PC layout; #17 and #22–#24 /// assumed to follow it (each checks its arguments and otherwise goes to the PC method). -/// * device #12 `CreateCommandList` (only with console lists on): console code gets a -/// console-shaped list (D3D12.X inline code writes into it), XCL's own code a PC one. -/// (console slot, PC slot) of PC methods that sit elsewhere in the console's vtable. -/// ID3D12GraphicsCommandList (from the Fortnite RHI call sites, matching XCL's own evidence -/// – FSR4 calls ClearUnorderedAccessViewUint at #53): 0–27 and 56–59 as on PC; the query -/// methods come right after ExecuteBundle (28–31 = PC 52–55: BeginQuery, EndQuery, -/// ResolveQueryData, SetPredication), so SetDescriptorHeaps … DiscardResource move up by 4 -/// (32–55 = PC 28–51); ID3D12GraphicsCommandList1 is at 104–109 (PC 60–65), the shading-rate -/// methods at 124 / 125 (PC 77 / 78). The console-only methods in between stay guarded. -fn console_remap(kind: Kind) -> Vec<(usize, usize)> { - match kind { - Kind::CommandList => (28..=31).map(|x| (x, x + 24)).chain((32..=55).map(|x| (x, x - 4))).chain((104..=109).map(|x| (x, x - 44))).chain([(124, 77), (125, 78)]).collect(), - _ => Vec::new(), - } -} - -/// 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; - +/// * device #12 `CreateCommandList`: console list types; with console lists on, console code +/// gets a console-shaped list (D3D12.X inline code writes into it), XCL's own code a PC one. +/// * the device's own methods (`device_x`, `frame`), the command list's (`list_x`), queue #30 +/// PresentX (`present`). fn console_slots(kind: Kind) -> Vec<(usize, usize)> { use super::device_x as x; match kind { @@ -600,6 +622,26 @@ fn console_slots(kind: Kind) -> Vec<(usize, 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)], Kind::CommandQueue => vec![(30, super::present::present_x as usize)], + Kind::CommandList => { + use super::list_x as l; + vec![ + (47, l::ia_set_index_buffer_x as usize), + (60, l::copy_memory_x as usize), + (61, l::fill32_x as usize), + (62, l::fill64_x as usize), + (63, l::fill128_x as usize), + (68, l::set_depth_bounds_x as usize), + (69, l::write32_bottom_x as usize), + (70, l::write64_bottom_x as usize), + (78, l::dispatch_x as usize), + (81, l::draw_indexed_x as usize), + (84, l::copy_resource_x as usize), + (85, l::set_predication_buffer_x as usize), + (88, l::write32_top_x as usize), + (89, l::write64_top_x as usize), + (90, l::write32_bottom_of_shader_x as usize), + ] + } _ => vec![], } } @@ -797,7 +839,7 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: 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 { + if !va.is_multiple_of(0x1_0000) || bytes == 0 || va - base + bytes > size { return None; } let heap = *UMA_HEAPS.lock().unwrap().get(k)?; diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 9f59b56..838c4e4 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -414,6 +414,53 @@ pub fn console_device_methods() -> Result<(), String> { } } +/// The console command list's memory methods as a title calls them, on its own graphics +/// memory: Write32BitValueBottomOfPipeX #69, Write64BitValueTopOfPipeX #89, a GPU timestamp +/// (#70), FillMemoryWith32BitValueX #61, CopyMemoryToMemoryX #60, and an extension XCL does not +/// model (Wait32BitValueX #71). +pub fn console_list_methods() -> Result<(), String> { + unsafe { + let dev = device()?; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?; + let graphics = 1u64 << 29; + let mem = crate::XMemAlloc(0x1_0000, graphics) as *mut u8; + ensure!(!mem.is_null(), "graphics memory"); + let at = |o: usize| mem as u64 + o as u64; + for i in 0..64 { + *mem.add(0x1000 + i) = i as u8 ^ 0x5A; + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + let l = list.as_raw(); + let slot = |i: usize| *(*(l as *const *const usize)).add(i); + let write32_bottom: unsafe extern "system" fn(*mut c_void, u64, u32, u32, u32) = std::mem::transmute(slot(69)); + let write64_bottom: unsafe extern "system" fn(*mut c_void, u64, u64, u32, u32) = std::mem::transmute(slot(70)); + let write64_top: unsafe extern "system" fn(*mut c_void, u64, u64, u32) = std::mem::transmute(slot(89)); + let fill32: unsafe extern "system" fn(*mut c_void, u64, u64, u32) = std::mem::transmute(slot(61)); + let copy: unsafe extern "system" fn(*mut c_void, u64, u64, u64, u32) = std::mem::transmute(slot(60)); + let wait32: unsafe extern "system" fn(*mut c_void, u64, u32, u32, u32, u32) = std::mem::transmute(slot(71)); + write32_bottom(l, at(0), 0x1234_5678, 0, 0); + write64_top(l, at(8), 0x1122_3344_5566_7788, 0); + write64_bottom(l, at(0x10), 0, 0, 1); // GPU timestamp + fill32(l, at(0x100), 0x100, 0xABCD_EF01); + copy(l, at(0x2000), at(0x1000), 64, 0); + wait32(l, at(0), 3, 0x1234_5678, u32::MAX, 0); + 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 r32 = |o: usize| (mem.add(o) as *const u32).read(); + let r64 = |o: usize| (mem.add(o) as *const u64).read(); + ensure!(r32(0) == 0x1234_5678, "Write32BitValueBottomOfPipeX: {:#x}", r32(0)); + ensure!(r64(8) == 0x1122_3344_5566_7788, "Write64BitValueTopOfPipeX: {:#x}", r64(8)); + ensure!(r64(0x10) != 0, "no GPU timestamp"); + ensure!((0..64).all(|i| r32(0x100 + 4 * i) == 0xABCD_EF01) && r32(0x200) == 0 && r32(0xFC) == 0, "FillMemoryWith32BitValueX"); + ensure!((0..64).all(|i| *mem.add(0x2000 + i) == i as u8 ^ 0x5A) && *mem.add(0x2040) == 0, "CopyMemoryToMemoryX"); + crate::XMemFree(mem as *mut c_void, graphics); + Ok(()) + } +} + pub fn render_triangle() -> Result<(), String> { unsafe { let dev = device()?; @@ -444,6 +491,14 @@ pub fn render_triangle() -> Result<(), String> { let hr = derive(dev.as_raw(), pso.as_raw(), 1, patch.as_ptr(), &ID3D12PipelineState::IID, &mut raw); ensure!(hr >= 0 && !raw.is_null(), "CreateDerivedPipelineStateX hr={hr:#x}"); let derived = ID3D12PipelineState::from_raw(raw); + // indices in the title's graphics memory: [0 1 2 0 1 2] for the bound index buffer, + // [0 1 2] at +16 for DrawIndexedX + let graphics = 1u64 << 29; + let ib = crate::XMemAlloc(0x1_0000, graphics) as *mut u16; + ensure!(!ib.is_null(), "graphics memory"); + for (i, v) in [0u16, 1, 2, 0, 1, 2, 0, 0, 0, 1, 2].into_iter().enumerate() { + *ib.add(i) = v; + } patch[0] = 4; let hr = derive(dev.as_raw(), pso.as_raw(), 1, patch.as_ptr(), &ID3D12PipelineState::IID, &mut raw); ensure!(hr < 0, "an unknown patch part must fail (hr={hr:#x})"); @@ -520,6 +575,18 @@ pub fn render_triangle() -> Result<(), String> { list.SetPipelineState(&derived); list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: (w / 2) as f32, Height: (h / 2) as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); list.DrawInstanced(3, 1, 0, 0); + // console index buffers at title addresses: IASetIndexBuffer #47 binds [0 1 2 0 1 2]; + // DrawIndexedX #81 draws [0 1 2] from +16 in the top-right quadrant; the bound buffer + // comes back for indices 3–5 in the bottom-left one + type SetIb = unsafe extern "system" fn(*mut c_void, *const D3D12_INDEX_BUFFER_VIEW); + type DrawIndexedX = unsafe extern "system" fn(*mut c_void, u64, DXGI_FORMAT, u32, u32); + list.SetPipelineState(&pso); + xslot::(&list, 47)(list.as_raw(), &D3D12_INDEX_BUFFER_VIEW { BufferLocation: ib as u64, SizeInBytes: 12, Format: DXGI_FORMAT_R16_UINT }); + let half = |x: u32, y: u32| D3D12_VIEWPORT { TopLeftX: x as f32, TopLeftY: y as f32, Width: (w / 2) as f32, Height: (h / 2) as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + list.RSSetViewports(&[half(w / 2, 0)]); + xslot::(&list, 81)(list.as_raw(), ib as u64 + 16, DXGI_FORMAT_R16_UINT, 3, 0); + list.RSSetViewports(&[half(0, h / 2)]); + list.DrawIndexedInstanced(3, 1, 3, 0, 0); let barrier = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -560,7 +627,11 @@ pub fn render_triangle() -> Result<(), String> { let center = px(32, 32); let corner = px(1, 1); let quadrant = px(16, 16); + let (top_right, bottom_left) = (px(48, 16), px(16, 48)); rb.Unmap(0, None); + crate::XMemFree(ib as *mut c_void, graphics); + ensure!(top_right == [0, 255, 0, 255], "top-right quadrant {top_right:?} (expected green: DrawIndexedX)"); + ensure!(bottom_left == [0, 255, 0, 255], "bottom-left quadrant {bottom_left:?} (expected green: the title's index buffer, bound again)"); ensure!(center == [0, 255, 0, 255], "centre pixel {center:?} (expected green triangle)"); ensure!(quadrant == [0, 255, 255, 255], "top-left quadrant {quadrant:?} (expected cyan: the derived pipeline writes green only)"); ensure!(corner == [0, 0, 255, 255], "corner pixel {corner:?} (expected blue clear colour)"); diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index cdc922e..51171e8 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -440,6 +440,7 @@ fn main() { check("D3D12.X: triangle rendered on the real GPU and read back (console + derived pipeline)", 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("D3D12.X: console command list memory methods (writes, timestamp, fill, copy)", gpu::console_list_methods); check("XAudio2: console flags/device, XMA2 voice plays silence, PCM passes, callbacks", audio::xaudio2_console_voices); let failures = FAILURES.load(Ordering::SeqCst);