Tests: a console compute shader through the D3D12.X PSO hook, dispatched and read back

A wave64 compute program in the retail container layout (DXBC/DXIL part,
XDAT, XBCH, FSSM with a CS stage descriptor) goes through the backend's
CreateComputePipelineState hook, then is dispatched with runner::dispatch_on
and its memory is checked: per-thread ids, TGID, LDS and s_barrier across the
two waves of a group. The translated-pipeline counter is checked, so a
fallback path cannot pass.

runner::dispatch now shares its body with dispatch_on, which takes a
pipeline and root signature built elsewhere.
This commit is contained in:
gefydev
2026-11-22 22:34:00 -03:00
parent dd713e34f5
commit 31a400195b
2 changed files with 208 additions and 15 deletions
+41 -15
View File
@@ -1193,18 +1193,44 @@ pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> {
pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Result<Vec<u32>, String> {
let mut g = GPU.lock().unwrap();
let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?;
let pso: ID3D12PipelineState = unsafe {
gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: transmute_copy(&gpu.rs),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() },
..Default::default()
})
}
.map_err(|x| format!("CreateComputePipelineState: {x}"))?;
dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem)
}
/// Dispatch with an existing compute pipeline on `dev` (its own queue), e.g. one the D3D12.X
/// backend built from a console shader: root signature `rs` with the XCL shader ABI, u0 =
/// `sgprs`, u2 = `mem`. Returns the memory afterwards.
pub fn dispatch_on(dev: &ID3D12Device, pso: &ID3D12PipelineState, rs: &ID3D12RootSignature, groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Result<Vec<u32>, String> {
unsafe {
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;
dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem)
}
}
#[allow(clippy::too_many_arguments)]
fn dispatch_with(
dev: &ID3D12Device,
queue: &ID3D12CommandQueue,
fence: &ID3D12Fence,
value: &mut u64,
pso: &ID3D12PipelineState,
rs: &ID3D12RootSignature,
groups: [u32; 3],
sgprs: &[u32],
mem: &[u32],
) -> Result<Vec<u32>, String> {
let mut io = sgprs.to_vec();
io.resize(KERNEL_SGPRS, 0);
let mem_len = mem.len().max(64);
unsafe {
let dev = &gpu.dev;
let pso: ID3D12PipelineState = dev
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: transmute_copy(&gpu.rs),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() },
..Default::default()
})
.map_err(|x| format!("CreateComputePipelineState: {x}"))?;
let (io_bytes, mem_bytes) = ((io.len() * 4) as u64, (mem_len * 4) as u64);
let upload = buffer(dev, io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?;
let mut p = std::ptr::null_mut();
@@ -1219,7 +1245,7 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re
let res_buf = buffer(dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?;
let readback = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?;
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, &pso).map_err(e)?;
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso).map_err(e)?;
list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes);
list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes);
list.ResourceBarrier(&[
@@ -1228,7 +1254,7 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re
transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
]);
let _bound = bind_resources(dev, &list, &[], &[])?;
list.SetComputeRootSignature(&gpu.rs);
list.SetComputeRootSignature(rs);
list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress());
list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress());
list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress());
@@ -1236,14 +1262,14 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re
list.ResourceBarrier(&[transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
list.CopyBufferRegion(&readback, 0, &mem_buf, 0, mem_bytes);
list.Close().map_err(e)?;
gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
gpu.value += 1;
gpu.queue.Signal(&gpu.fence, gpu.value).map_err(e)?;
queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
*value += 1;
queue.Signal(fence, *value).map_err(e)?;
let ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).map_err(e)?;
gpu.fence.SetEventOnCompletion(gpu.value, ev).map_err(e)?;
fence.SetEventOnCompletion(*value, ev).map_err(e)?;
windows::Win32::System::Threading::WaitForSingleObject(ev, 10_000);
let _ = windows::Win32::Foundation::CloseHandle(HANDLE(ev.0));
if gpu.fence.GetCompletedValue() < gpu.value {
if fence.GetCompletedValue() < *value {
return Err(format!("GPU did not finish within 10 s ({:?})", dev.GetDeviceRemovedReason()));
}
let mut q = std::ptr::null_mut();
+167
View File
@@ -0,0 +1,167 @@
//! End to end without a game executable: a console compute shader in the retail container
//! layout (DXBC → DXIL part with XDAT → XBCH → FSSM, CS stage descriptor) goes through the
//! D3D12.X backend's CreateComputePipelineState hook as a title would hand it over →
//! recompiled → D3D12 pipeline on the adapter → dispatched → memory read back and checked.
//!
//! The program is wave64, as console compute programs are: on an adapter without 64-lane
//! waves (NVIDIA) the backend has to run it as two wave32 halves, or the driver refuses the
//! pipeline. The pipeline counters are checked, so the test cannot pass on a fallback path.
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
use xcl::gpu::rdna2::encode;
use xcl::gpu::recomp::runner;
use xcl::hle::d3d12x::real;
fn le(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_le_bytes());
}
/// Console CS container: DXBC with one DXIL part (program kind CS, no bitcode) whose XDAT
/// holds XBCH (zlib) → FSSM with `code` and a CS stage descriptor: COMPUTE_PGM_RSRC2
/// `rsrc2` at +0x38, numthreads at +0x3C.
fn console_cs(code: &[u8], rsrc2: u32, threads: [u32; 3]) -> Vec<u8> {
let code_at = 0x308usize;
let mut fssm = vec![0u8; code_at];
fssm[0..4].copy_from_slice(b"FSSM");
fssm[4..8].copy_from_slice(&0x101u32.to_le_bytes());
fssm[0xC0..0xC8].copy_from_slice(&((code_at - 0x10) as u64).to_le_bytes());
fssm[0xC8..0xD0].copy_from_slice(&(code.len() as u64).to_le_bytes());
fssm[0x100..0x108].copy_from_slice(&0x0000_00C0_0002_0106u64.to_le_bytes()); // CS, API stage 1
for (k, x) in [rsrc2, threads[0], threads[1], threads[2]].into_iter().enumerate() {
fssm[0x138 + 4 * k..0x13C + 4 * k].copy_from_slice(&x.to_le_bytes());
}
fssm.extend_from_slice(code);
let size = (fssm.len() - 0x10) as u32;
fssm[8..12].copy_from_slice(&size.to_le_bytes());
let z = miniz_oxide::deflate::compress_to_vec_zlib(&fssm, 6);
let mut xbch = b"XBCH".to_vec();
for x in [3, z.len() as u32, 0, fssm.len() as u32, 0] {
le(&mut xbch, x);
}
xbch.extend_from_slice(&z);
// DXIL part: program header (kind 5 = CS, 6.6), XDAT, its entries, NOBC placeholder
let table = 0x18 + 12;
let data_at = table + 2 * 12;
let mut d = Vec::new();
for x in [5 << 16 | 0x66, 0, u32::from_le_bytes(*b"DXIL"), 0x106, 0, 4] {
le(&mut d, x);
}
d.extend_from_slice(b"XDAT");
for x in [2, table as u32, 0x12, data_at as u32, 16, 0x0d, (data_at + 16) as u32, xbch.len() as u32] {
le(&mut d, x);
}
d.extend_from_slice(&[0x5a; 16]);
d.extend_from_slice(&xbch);
while d.len() % 4 != 0 {
d.push(0);
}
let nobc = d.len();
d.extend_from_slice(b"NOBC");
let dwords = (d.len() / 4) as u32;
d[4..8].copy_from_slice(&dwords.to_le_bytes());
d[16..20].copy_from_slice(&((nobc - 8) as u32).to_le_bytes());
let mut v = vec![0u8; 36];
v[0..4].copy_from_slice(b"DXBC");
v[20..24].copy_from_slice(&1u32.to_le_bytes());
v[28..32].copy_from_slice(&1u32.to_le_bytes());
v[32..36].copy_from_slice(&36u32.to_le_bytes());
v.extend_from_slice(b"DXIL");
le(&mut v, d.len() as u32);
v.extend_from_slice(&d);
let total = v.len() as u32;
v[24..28].copy_from_slice(&total.to_le_bytes());
v
}
const V: u64 = 256; // VALU source code of v0
/// 16×8 threads per group (two wave64s), s[0:1] = output base and row width, TGID_X/Y in
/// s2/s3, thread ids in v0/v1: each thread writes its global (x, y), and through LDS +
/// s_barrier the (x, y) of the thread at the mirrored index, which is in the other wave.
fn program() -> Vec<u8> {
let list: &[(&str, &str, &[(&str, u64)], Option<u32>)] = &[
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 132), ("VSRC1", 1)], None), // y · 16
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 2), ("VSRC1", 0)], None), // index in group
("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 132)], None), // group x · 16
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 4), ("VSRC1", 0)], None), // global x
("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 3), ("SSRC1", 131)], None), // group y · 8
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 5), ("VSRC1", 1)], None), // global y
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 144), ("VSRC1", 4)], None),
("V_OR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 5), ("VSRC1", 3)], None), // x | y << 16
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)], None),
("DS_WRITE_B32", "ENC_DS", &[("ADDR", 6), ("DATA0", 5)], None),
("S_BARRIER", "ENC_SOPP", &[], None),
("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 2)], Some(127)), // mirrored thread
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 130), ("VSRC1", 7)], None),
("DS_READ_B32", "ENC_DS", &[("VDST", 12), ("ADDR", 7)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 5)], None),
("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 1)], None), // y · width
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 9), ("VSRC1", 3)], None),
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 131), ("VSRC1", 9)], None),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 0), ("VSRC1", 9)], None), // + output base
("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None),
("S_ENDPGM", "ENC_SOPP", &[], None),
];
list.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect()
}
#[test]
fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() {
if xcl::gpu::recomp::dxc::location().is_err() {
println!("no DXC – skipping");
runner::skip_test("no DXC");
return;
}
if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real {
println!("no real D3D12 device – skipping");
runner::skip_test("no GPU");
return;
}
let raw = real::device_raw();
let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone();
println!("backend device: {}", real::stats().adapter);
// user SGPRs 2, TGID_X + TGID_Y, thread ids v0 + v1
let blob = console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1]);
assert!(xcl::gpu::xbox::is_xbox(&blob), "expected a console container");
let game_rs: ID3D12RootSignature = unsafe {
let mut ser = None;
D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap();
let ser = ser.unwrap();
dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap()
};
let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::ManuallyDrop::new(Some(game_rs)),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: blob.as_ptr() as _, BytecodeLength: blob.len() },
..Default::default()
};
let before = real::stats();
let pso: Result<ID3D12PipelineState, _> = unsafe { dev.CreateComputePipelineState(&desc) };
unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) };
let pso = pso.expect("CreateComputePipelineState through the backend hook");
// built in the background behind a stand-in when its shader was not compiled yet
let real_raw = xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize) as *mut std::ffi::c_void;
let after = real::stats();
assert_eq!(after.translated_pipelines, before.translated_pipelines + 1, "PSO was not built from the translated shader: {:?}", after.translation_errors);
let pso = unsafe { ID3D12PipelineState::from_raw_borrowed(&real_raw) }.unwrap().clone();
let rs_raw = real::pso_root_signature(pso.as_raw() as usize).expect("root signature of the translated PSO") as *mut std::ffi::c_void;
let rs = unsafe { ID3D12RootSignature::from_raw_borrowed(&rs_raw) }.unwrap().clone();
let (w, h, base) = (32usize, 24usize, 0x100usize);
let mut io = vec![0u32; 128];
io[0] = base as u32;
io[1] = w as u32;
let out = runner::dispatch_on(&dev, &pso, &rs, [2, 3, 1], &io, &vec![0u32; (base + w * h * 8) / 4]).expect("dispatch");
for y in 0..h {
for x in 0..w {
let at = (base + (y * w + x) * 8) / 4;
assert_eq!(out[at], (x | y << 16) as u32, "({x}, {y}): own value");
let (gx, gy, i) = (x / 16, y / 8, (y % 8) * 16 + x % 16);
let (px, py) = (gx * 16 + (127 - i) % 16, gy * 8 + (127 - i) / 16);
assert_eq!(out[at + 1], (px | py << 16) as u32, "({x}, {y}): value of thread {} through LDS", 127 - i);
}
}
}