D3D12.X compute command list format from XboxBvhBuilder (fake list probe, record writer scan)

- probe: the console builder records a whole BLAS build into a fake console list
  (logging vtable, UMA upload memory); record buffer, changed fields and calls dumped
- HANDOFF: list object fields (+0x18/+0x28/+0x30, +0x344 + 4i root parameter headers),
  record kinds (pipeline 28 B, root parameters, Dispatch 0x4002C400, 0x4003CC00),
  console-only methods (#148 AllocateUploadMemory, #146 barrier); plan for an XCL
  console command list
- scripts/re: shader extraction, root-argument layout check, record writer scan
This commit is contained in:
ivall
2026-11-21 00:00:00 +01:00
parent 57b529c3ce
commit e714e2ab50
6 changed files with 387 additions and 0 deletions
+32
View File
@@ -371,6 +371,38 @@ amd_fidelityfx_loader_xbox / amd_fidelityfx_upscaler_xbox, XboxBvhBuilder. Exe g
przy Close/ExecuteCommandLists. Układ pól i format rekordów do ustalenia z kodu inline (najpierw builder: tylko compute,
potem gra). To prawdopodobnie największy pozostały kawałek pracy nad renderowaniem.
### Format listy poleceń D3D12.X (compute) – ustalony na XboxBvhBuilder.dll
Metoda: atrapa listy (`xbox_bvh_builder_records_into_a_fake_console_list`, `XCL_PROBE_BVH_FAKELIST=1`: vtable 600 thunków
logujących slot i argumenty, #148 przydziela z UMA, +0x18/+0x30 = bufor rekordów) – builder nagrał całą budowę BLAS bez
awarii; plus przegląd statyczny wszystkich 141 miejsc zapisu (`record_writers.py` w scratchpadzie).
- **Pola obiektu listy:** +0x00 vtable, +0x18 wskaźnik zapisu, +0x28 granica dla rekordów dispatch, +0x30 koniec bufora,
+0x140 flaga „brudne” (ustawiana, gdy nagłówek ma bity 31:30 = 0), +0x141 bit z pipeline (bit 20 słowa +0x20 rekordu),
+0x143 flaga, **+0x344 + 4·i = nagłówek parametru root i** (wpisuje go metoda – u nas #33, najpewniej
SetComputeRootSignature – kod inline tylko go kopiuje), +0x544 bieżący pipeline (16 B).
- **Rekordy** (bez wspólnej ramki; długość wynika z nagłówka / rodzaju):
- pipeline 28 B (×34): kopia +0x10..+0x2B obiektu „info” buildera = [wskaźnik PSO (nasz adoptowany obiekt)][wskaźnik
obiektu D3D12Core][8 B flag][4 B]; zastępczo slot 25;
- parametr root i: nagłówek = [+0x344 + 4i] (+ (n−1) << 16 dla wielu stałych), potem: deskryptor = adres 64-bit
(12 B, zastępczo slot 43/45), jedna stała (8 B, slot 37), n stałych (4 + 4n B, slot 39: (i, n, dane, offset));
- Dispatch: `0x4002C400` (albo `(0x1000BA00 | flaga) << 2`) + x, y, z = 16 B, zastępczo slot 14 (= PC Dispatch);
- `0x4003CC00`, 20 B, zastępczo slot 80 (pewnie dispatch pośredni);
- metody: #148 AllocateUploadMemory(rozmiar, wyrównanie) → wskaźnik CPU (= adres GPU w UMA), #146 bariera
(1, wskaźnik na opis), #33 (wskaźnik obiektu – root signature / PSO), #14 Dispatch.
- Nagłówki PM4 typu 3 nie występują jako stałe – nagłówki parametrów pochodzą z listy, więc **XCL może wpisać tam własne
znaczniki** (np. 0xC0000000 | i << 8 | znacznik) i jednoznacznie czytać strumień; rekord pipeline rozpoznawać po znanym
wskaźniku PSO.
### Plan: konsolowa lista poleceń w XCL (następne sesje)
1. `hle/d3d12x/console_list.rs`: obiekt o układzie konsoli (pola jak wyżej, bufor rekordów, nagłówki parametrów), opakowujący
listę PC; vtable konsolowy: 14 Dispatch, 25 SetPipelineState, 33 SetComputeRootSignature (wpisuje znaczniki, pamięta
układ RS), 37/39/43/45 zastępcze parametry (dopisują te same rekordy), 80, 146 bariera, 148 AllocateUploadMemory
(UMA), Close/Reset; reszta – logujące zaślepki. CreateCommandList z kodu konsoli → ten obiekt.
2. PSO: przy tworzeniu zapamiętać PSO → (przetłumaczony?, układ RS z RTS0).
3. ExecuteCommandLists: interpretacja rekordów → lista PC: przy każdym dispatchu tablica argumentów root (układ z sekcji
„Wiązanie argumentów root”) w UMA, `io` = [adres lo, hi, …], root signature ABI + io/res/mem, PSO przetłumaczony, Dispatch;
bariery → bariera UAV na `mem`.
4. Test: prawdziwy XboxBvhBuilder buduje BLAS na GPU przez tę listę → wynik czytany `bvh::Bvh::trace` = brute force.
## W trakcie (niedokończone)
Nic otwartego.
+122
View File
@@ -451,3 +451,125 @@ fn memory_cap_is_active() {
assert!(p.is_null(), "a 9 GB commit went through – the job memory cap is not active");
}
}
// ---------------------------------------------------------------------------------------
// Fake console command list: what D3D12.X code inlined into a title writes into the list
// object and which methods it calls (`XCL_PROBE_BVH_FAKELIST=1`).
// ---------------------------------------------------------------------------------------
static FAKE_SLOT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
static FAKE_CALLS: std::sync::Mutex<Vec<(u32, [usize; 6])>> = std::sync::Mutex::new(Vec::new());
static FAKE_BUMP: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
extern "system" fn fake_method(this: usize, a: usize, b: usize, c: usize, d: usize, e: usize) -> usize {
let slot = FAKE_SLOT.load(std::sync::atomic::Ordering::Relaxed);
FAKE_CALLS.lock().unwrap().push((slot, [this, a, b, c, d, e]));
match slot {
// AllocateUploadMemory(size, alignment) → CPU pointer (UMA: = GPU address)
148 => {
let align = b.max(16);
let at = FAKE_BUMP.load(std::sync::atomic::Ordering::Relaxed).div_ceil(align) * align;
FAKE_BUMP.store(at + a, std::sync::atomic::Ordering::Relaxed);
at
}
_ => 0,
}
}
/// vtable of `n` thunks: `mov dword [FAKE_SLOT], slot ; jmp fake_method`
fn fake_vtable(n: usize) -> Vec<usize> {
use windows_sys::Win32::System::Memory::*;
let per = 32usize;
unsafe {
let code = VirtualAlloc(std::ptr::null(), n * per, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8;
(0..n)
.map(|i| {
let mut c = vec![0x48, 0xB8];
c.extend_from_slice(&(&FAKE_SLOT as *const _ as u64).to_le_bytes()); // mov rax, &FAKE_SLOT
c.extend_from_slice(&[0xC7, 0x00]);
c.extend_from_slice(&(i as u32).to_le_bytes()); // mov dword [rax], i
c.extend_from_slice(&[0x48, 0xB8]);
c.extend_from_slice(&(fake_method as *const () as usize as u64).to_le_bytes()); // mov rax, fake_method
c.extend_from_slice(&[0xFF, 0xE0]); // jmp rax
assert!(c.len() <= per);
let p = code.add(i * per);
std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len());
p as usize
})
.collect()
}
}
#[test]
fn xbox_bvh_builder_records_into_a_fake_console_list() {
let Some(dir) = setup() else { return };
if std::env::var_os("XCL_PROBE_BVH_FAKELIST").is_none() {
return;
}
let m = load(dir, "XboxBvhBuilder.dll");
unsafe {
let iid: [u8; 16] = [0xf1, 0x19, 0x98, 0x18, 0xb6, 0x1d, 0x57, 0x4b, 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7];
let mut dev: *mut std::ffi::c_void = std::ptr::null_mut();
assert!(xcl::hle::d3d12x::D3D12XboxCreateDevice(std::ptr::null_mut(), std::ptr::null(), iid.as_ptr() as _, &mut dev) >= 0);
let ctor: extern "system" fn(*mut u8, *mut std::ffi::c_void, bool) -> *mut u8 = std::mem::transmute(proc(&m, "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z"));
let this = pages(0x10000);
ctor(this.as_mut_ptr(), dev, false);
let uma = xcl::gpu::uma::get().expect("UMA");
// the fake list: vtable, then a zeroed console-sized body; +0x18 / +0x30 = record buffer
let vt = Box::leak(fake_vtable(600).into_boxed_slice());
let list = pages(0x10000);
let records = uma.alloc(1 << 20, 256).unwrap() as usize;
let lp = list.as_mut_ptr();
let w = |at: usize, v: usize| (lp.add(at) as *mut usize).write(v);
w(0, vt.as_ptr() as usize);
w(0x18, records);
w(0x30, records + (1 << 20));
FAKE_BUMP.store(uma.alloc(4 << 20, 4096).unwrap() as usize, std::sync::atomic::Ordering::Relaxed);
let snapshot = list.to_vec();
// a bottom level of 64 triangles
let n = 64u32;
let vb = uma.alloc(n as usize * 36, 256).unwrap();
for (i, v) in std::slice::from_raw_parts_mut(vb as *mut f32, n as usize * 9).iter_mut().enumerate() {
*v = (i % 9) as f32 * 0.1 + (i / 9) as f32;
}
let geom = GeometryDesc { ty: 0, flags: 1, transform: 0, index_format: 0, vertex_format: 6, index_count: 0, vertex_count: 3 * n, index_buffer: 0, vertex_buffer: vb as u64, vertex_stride: 12 };
let inputs = BuildInputs { ty: 1, flags: 0, num_descs: 1, layout: 0, descs: &geom as *const GeometryDesc as u64 };
let dest = uma.alloc(13312, 256).unwrap();
let scratch = uma.alloc(23872, 256).unwrap();
let desc = BuildDesc { dest: dest as u64, inputs, source: 0, scratch: scratch as u64 };
println!("vb {vb:?} dest {dest:?} scratch {scratch:?} rekordy {records:#x} upload od {:#x}", FAKE_BUMP.load(std::sync::atomic::Ordering::Relaxed));
let build: extern "system" fn(*mut u8, *mut u8, *const BuildDesc, u32, *const u8) = std::mem::transmute(proc(
&m,
"?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z",
));
build(this.as_mut_ptr(), list.as_mut_ptr(), &desc, 0, std::ptr::null());
println!("== wywołania metod listy");
for (slot, a) in FAKE_CALLS.lock().unwrap().iter() {
println!(" #{slot:<4} {:x?}", &a[1..]);
}
println!("== zmienione pola obiektu listy (offset: przed → po)");
for k in (0..0x10000).step_by(8) {
let (b, a) = (u64::from_le_bytes(snapshot[k..k + 8].try_into().unwrap()), u64::from_le_bytes(list[k..k + 8].try_into().unwrap()));
if a != b {
println!(" +{k:#06x}: {b:#x} → {a:#x}");
}
}
let end = (list.as_ptr().add(0x18) as *const usize).read();
// what the pointers in the records are: the vtable each points to
println!("== urządzenie {dev:?}");
let mut seen = std::collections::BTreeSet::new();
let rec64 = std::slice::from_raw_parts(records as *const u32, (end - records) / 4);
for w in rec64.windows(2) {
let p = (w[0] as usize) | (w[1] as usize) << 32;
if (0x1_0000_0000..0x7FFF_0000_0000).contains(&p) && w[1] != 4 && seen.insert(p) {
let vt = (p as *const usize).read();
println!(" wskaźnik {p:#x}: vtable {vt:#x} = {}", xcl::modules::describe_address(vt));
}
}
println!("== bufor rekordów: {} B", end - records);
let rec = std::slice::from_raw_parts(records as *const u32, (end - records) / 4);
for (i, ch) in rec.chunks(8).enumerate().take(64) {
println!(" {:#06x}: {:08x?}", i * 32, ch);
}
}
}
+56
View File
@@ -0,0 +1,56 @@
"""Extract the DXBC containers embedded in XboxBvhBuilder.dll and print each one's root
signature (RTS0) parameters.
usage: python bvhb_shaders.py <XboxBvhBuilder.dll> [out dir, default ./bvhb_shaders]"""
import os, struct, sys
DLL = sys.argv[1]
OUT = sys.argv[2] if len(sys.argv) > 2 else 'bvhb_shaders'
os.makedirs(OUT, exist_ok=True)
b = open(DLL, 'rb').read()
TYPES = {0: 'table', 1: 'consts', 2: 'CBV', 3: 'SRV', 4: 'UAV'}
RANGE = {0: 'SRV', 1: 'UAV', 2: 'CBV', 3: 'Sampler'}
def parts(blob):
n = struct.unpack_from('<I', blob, 28)[0]
for k in range(n):
off = struct.unpack_from('<I', blob, 32 + 4 * k)[0]
cc, size = blob[off:off + 4].decode('latin1'), struct.unpack_from('<I', blob, off + 4)[0]
yield cc, blob[off + 8:off + 8 + size]
def rts0(r):
ver, n, poff, ns, soff, flags = struct.unpack_from('<6I', r, 0)
out = []
for k in range(n):
ty, vis, pay = struct.unpack_from('<3I', r, poff + 12 * k)
if ty == 0:
nr, roff = struct.unpack_from('<2I', r, pay)
rs = []
for j in range(nr):
w = struct.unpack_from('<6I' if ver >= 2 else '<5I', r, roff + (24 if ver >= 2 else 20) * j)
rs.append(f'{RANGE[w[0]]}x{w[1] if w[1] != 0xFFFFFFFF else "∞"}@{w[2]}')
out.append('table[' + ','.join(rs) + ']')
elif ty == 1:
reg, space, num = struct.unpack_from('<3I', r, pay)
out.append(f'consts b{reg} x{num}')
else:
reg, space = struct.unpack_from('<2I', r, pay)
out.append(f'{TYPES[ty]} {"bt u"[ty - 1] if ty < 5 else "?"}{reg}')
return f'v{ver} flags {flags:#x} samplers {ns}: ' + ' | '.join(out)
i = b.find(b'DXBC')
k = 0
while i >= 0:
size = struct.unpack_from('<I', b, i + 24)[0]
blob = b[i:i + size]
if 32 < size < 4 << 20:
names = [cc for cc, _ in parts(blob)]
rs = next((p for cc, p in parts(blob) if cc == 'RTS0'), None)
path = os.path.join(OUT, f'{k:02d}.dxbc')
open(path, 'wb').write(blob)
print(f'{k:02d} @{i:#x} {size:6} B {",".join(names)} RS: {rts0(rs) if rs else "-"}')
k += 1
i = b.find(b'DXBC', i + 4)
+62
View File
@@ -0,0 +1,62 @@
"""Check the root-argument table hypothesis on all builder shaders: user SGPRs s[0:1] point
to the root arguments packed in order (constant = 4 B, root descriptor = 8 B, no padding).
Every scalar load from the table (s_load from the register pair holding s0/s1) must start
at a descriptor boundary or inside the constants.
usage: python check_layout.py <dir with the .dxbc files of bvhb_shaders.py> (needs target/debug/xcl.exe)"""
import os, re, struct, subprocess, sys
XCL = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'target', 'debug', 'xcl.exe')
D = sys.argv[1]
def parts(blob):
n = struct.unpack_from('<I', blob, 28)[0]
for k in range(n):
off = struct.unpack_from('<I', blob, 32 + 4 * k)[0]
yield blob[off:off + 4].decode('latin1'), blob[off + 8:off + 8 + struct.unpack_from('<I', blob, off + 4)[0]]
def layout(r):
ver, n, poff = struct.unpack_from('<3I', r, 0)
at, consts, descs = 0, [], {}
for k in range(n):
ty, vis, pay = struct.unpack_from('<3I', r, poff + 12 * k)
if ty == 1:
num = struct.unpack_from('<3I', r, pay)[2]
consts.append((at, at + 4 * num))
at += 4 * num
elif ty in (2, 3, 4):
descs[at] = 'CBV SRV UAV'.split()[ty - 2]
at += 8
else:
return None
return consts, descs, at
ok = bad = 0
for name in sorted(os.listdir(D)):
blob = open(os.path.join(D, name), 'rb').read()
rs = next((p for cc, p in parts(blob) if cc == 'RTS0'), None)
lay = layout(rs)
if lay is None:
continue
consts, descs, size = lay
lst = subprocess.run([XCL, 'disasm', os.path.join(D, name)], capture_output=True, text=True, encoding='utf-8', errors='replace').stdout
# the pair the table pointer was copied to: s_mov sA, s0 ; s_and sB, s1, 0xff
m = re.search(r's_and_b32 s(\d+), s1, 0xff\s', lst)
if not m or not re.search(rf's_mov_b32 s{int(m.group(1)) - 1}, s0\s', lst):
print(name, 'no table pointer pattern')
continue
pair = f's[{int(m.group(1)) - 1}:{m.group(1)}]'
loads = re.findall(r's_load_dword(x\d+)? s\[?(\d+)(?::(\d+))?\]?, ' + re.escape(pair) + r', (0x[0-9a-f]+)', lst)
for w, lo, hi, off in loads:
off = int(off, 16)
nbytes = 4 * (int(w[1:]) if w else 1)
good = off in descs or any(a <= off < b for a, b in consts) or (off - 4) in descs # high half of a VA
if good:
ok += 1
else:
bad += 1
print(f'{name}: load {nbytes} B @{off:#x} not on a parameter (descriptors {sorted(descs)}, constants {consts})')
print(f'loads on parameter boundaries: {ok}, off: {bad}')
+45
View File
@@ -0,0 +1,45 @@
"""Print a PE's exports: ordinal, name, RVA (forwarders shown)."""
import struct, sys
for path in sys.argv[1:]:
b = open(path, 'rb').read()
pe = struct.unpack_from('<I', b, 0x3C)[0]
nsec = struct.unpack_from('<H', b, pe + 6)[0]
opt = pe + 24
magic = struct.unpack_from('<H', b, opt)[0]
dd = opt + (112 if magic == 0x20B else 96)
exp_rva, exp_size = struct.unpack_from('<II', b, dd)
secs = []
so = opt + struct.unpack_from('<H', b, pe + 20)[0]
for i in range(nsec):
vs, va, raw_sz, raw = struct.unpack_from('<IIII', b, so + 40 * i + 8)
secs.append((va, max(vs, raw_sz), raw))
def off(rva):
for va, sz, raw in secs:
if va <= rva < va + sz:
return rva - va + raw
raise ValueError(hex(rva))
def cstr(rva):
o = off(rva)
return b[o:b.index(b'\0', o)].decode('latin1')
print(f'== {path}')
if not exp_rva:
print(' (no exports)')
continue
e = off(exp_rva)
name_rva, base, nfun, nnames, afun, anames, aords = struct.unpack_from('<IIIIIII', b, e + 12)
names = {}
for i in range(nnames):
nr = struct.unpack_from('<I', b, off(anames) + 4 * i)[0]
o = struct.unpack_from('<H', b, off(aords) + 2 * i)[0]
names[o] = cstr(nr)
print(f' {cstr(name_rva)}: {nfun} functions, {nnames} names, ordinal base {base}')
for i in range(nfun):
rva = struct.unpack_from('<I', b, off(afun) + 4 * i)[0]
if not rva:
continue
fwd = f' -> {cstr(rva)}' if exp_rva <= rva < exp_rva + exp_size else ''
print(f' #{base + i:<4} {names.get(i, "(ordinal only)")} @{rva:#x}{fwd}')
+70
View File
@@ -0,0 +1,70 @@
"""Find the D3D12.X inline command-list record writers in XboxBvhBuilder.dll (objdump AT&T
listing): `mov 0x18(%L),%P ; cmp 0x30|0x28(%L),%P ; jae fallback` … `add $N,%P ; mov %P,0x18(%L)`.
Per site: list register, bound field, record length, header (immediate or list field) and
the vtable slot of the fallback call.
usage: objdump -d --no-show-raw-insn XboxBvhBuilder.dll > bvhb.asm; python record_writers.py bvhb.asm"""
import re, collections, sys
lines = open(sys.argv[1], encoding='utf-8', errors='replace').read().splitlines()
ins = []
for l in lines:
m = re.match(r'\s+([0-9a-f]+):\s+(.*)$', l)
if m:
ins.append((int(m.group(1), 16), m.group(2).strip()))
idx = {a: i for i, (a, _) in enumerate(ins)}
sites = []
for i, (a, t) in enumerate(ins):
m = re.match(r'mov\s+0x18\(%(\w+)\),%(\w+)$', t)
if not m:
continue
L, P = m.groups()
if i + 2 >= len(ins):
continue
m2 = re.match(rf'cmp\s+0x(30|28)\(%{L}\),%{P}$', ins[i + 1][1])
m3 = re.match(r'jae\s+0x([0-9a-f]+)', ins[i + 2][1])
if not (m2 and m3):
continue
bound, fallback = m2.group(1), int(m3.group(1), 16)
body = []
length = None
for j in range(i + 3, min(i + 60, len(ins))):
tj = ins[j][1]
body.append(tj)
ma = re.match(rf'(?:add\s+\$0x([0-9a-f]+),%{P}|lea\s+0x([0-9a-f]+)\(%(\w+)\),%\w+)$', tj)
if ma and ma.group(1):
length = int(ma.group(1), 16)
if re.match(rf'mov\s+%\w+,0x18\(%{L}\)$', tj):
if length is None:
# lea 0xN(%rcx),%rax style
for tb in body:
ml = re.match(r'lea\s+0x([0-9a-f]+)\(%\w+\),%\w+$', tb)
if ml:
length = int(ml.group(1), 16)
break
# header: first store to (%P) / 0x0(%P) – immediate or from a list field
header = '?'
for tb in body:
mh = re.match(rf'movl\s+\$0x([0-9a-f]+),\(%{P}\)$', tb)
if mh:
header = 'imm ' + mh.group(1)
break
mf = re.match(rf'mov\s+0x([0-9a-f]+)\(%{L}\),%(\w+)$', tb)
if mf:
header = f'list+{mf.group(1)}'
break
# fallback: first indirect call at/after the jae target
slot = '?'
k = idx.get(fallback)
if k is not None:
for j in range(k, min(k + 12, len(ins))):
mc = re.match(r'call\s+\*0x([0-9a-f]+)\(%\w+\)$', ins[j][1])
if mc:
slot = int(mc.group(1), 16) // 8
break
sites.append((a, L, bound, length, header, slot))
print(f'{len(sites)} miejsc zapisu rekordów')
kinds = collections.Counter((h, ln, s, b) for _, _, b, ln, h, s in sites)
for (h, ln, s, b), n in kinds.most_common():
print(f' {n:3}× nagłówek {h:18} długość {ln} B granica +0x{b} zastępczo slot {s}')