Shader loading: dumps on request, translations kept on disk, precompile of compute

Every new shader was dumped (blob, FSSMs, disassembly, HLSL from a second translation)
on the title's thread at each start: now only with XCL_DUMP_SHADERS=1 (the retail game:
4.8 GB of dumps). Translations (DXIL and static samplers) are kept on disk by the console
bytes and the XCL binary's hash, so a start does not translate again. `xcl shaders
--precompile --only cs` fills both caches through the title's path. XCL_FRAME_DUMP=n,
frames shown at the end of a timed run, each translation failure logged once.
This commit is contained in:
ivall
2026-11-23 18:02:40 +01:00
parent 66e8e97460
commit db5dc26cba
9 changed files with 233 additions and 14 deletions
+13 -1
View File
@@ -45,7 +45,8 @@ NOTE:
opcodes that are free in the spec. The VALU literal is fetched when ANY SRC0/1/2 field = 255, even one unused by the opcode
(the compiler hides a hash in `v_nop` this way) – displayed as `v_nop ; lit 0x…`. SDWA/DPP: src0 from the extension dword (was `?249`).
- **Shader capture** (`gpu/shader.rs`): classification DXIL/DXBC/**xbox-native**/unknown container/ELF/raw RDNA2,
dump to `<data>\shaders\` (+ `*.fssmN.bin`, `*.rdna2.txt`); `report.json → shaders`: `xbox_hw_stages`, `xbox_errors`,
dump to `<data>\shaders\` (+ `*.fssmN.bin`, `*.rdna2.txt`; since 2026-11-23 only with `XCL_DUMP_SHADERS=1`, as the
`.hlsl` and `recomp_*` below); `report.json → shaders`: `xbox_hw_stages`, `xbox_errors`,
`rdna2_instructions`, `rdna2_undecoded_dwords`, `rdna2_mnemonics` (histogram sorted in descending order).
- **Console shader format** (`gpu/xbox.rs`, NEW) – worked out on `shaders.rpf` (23 869 shaders, all stages),
full description in the design §5.7a: DXIL (bitcode `NOBC`) → XDAT (+0x18; offsets from the program header) → XBCH v3 (zlib from +0x18)
@@ -1747,6 +1748,17 @@ to an outside server at every crash (`hle/netoff.rs`: the title's WinHTTP / Wins
shift probably starts below #72); the debug layer's Map of a DEFAULT-heap resource and a CopyResource source in
UAV state; queue #35, list #131 / #132 and allocator #9 are stubs (#9 registers the title's command memory callback);
MSAA layouts. With ~21 GB taken by other programs, 1 - 2 GB of commit stays free during a run.
- Loading (later): it shows 2 frames and then loads for minutes – ~3 500 shaders, 2 076 of them compute (13 M RDNA2
instructions, 611 programs over 10 000). Shader dumps (and a second translation of each) are now only made with
`XCL_DUMP_SHADERS=1` (they took 4.8 GB and its loading threads' time); translations are kept on disk
(`<dxil cache> ranslated`, by the console bytes and the XCL binary's hash); `XCL_FRAME_DUMP=n`. During a run DXC
compiles one program at a time (`wait_for_memory`: under 6 GB of commit free; ~11 GB of the system's commit is the
kernel's and drivers'), so the caches are filled without the title: `xcl shaders <shaders.rpf> --precompile --only cs`
(compute programs through `pso::console_to_dxil_in`, the title's path: both caches).
- Then at ~183 s: 5 mesh pipelines with an "AS" subobject fail and the title writes to address 0. The AS slot (24)
holds an MS container (`MSNC_VS_TransformUnlit_*`, NGG) – the console's subobject numbering around AS / MS is to be
checked (the message now lists the stream's subobject types and both hashes); translation failures are each logged
once (the first five hid this one).
- XDefiant, Fortnite, Unicorn Overlord and Minecraft were **not** run after these changes (only the test suites).
## Next steps (priority)
+1
View File
@@ -23,6 +23,7 @@ next steps:
| **Unicorn Overlord** | `SEGAofAmericaInc.Pa253b0c1Y` 1.0.0.6 | ✅ | fully playable | – |
| **Fortnite** | `436609B6.FortniteClient` 2.0.1461.7919 | ✅ | works fully, as far as the game allows without its online services | the game itself is online-only (multiplayer servers) |
| **XDefiant** | `Ubisoft.XDefiant-Game` 1.0.0.186 | ✅ | works fully, as far as the game allows without its servers | the game's own servers have been shut down |
| **A newer retail game** | – | 🚧 | starts, presents its first frames after ~4 s and runs for ~3 minutes without a crash (2 frames shown, then it loads its ~3 500 shaders) | stops after ~3 minutes at mesh pipelines it creates; its image has not been checked yet |
## Highlights
+131 -2
View File
@@ -100,7 +100,12 @@ pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<C
/// (`Options::split_wave64`) instead of `[WaveSize(64)]`, which such a driver rejects.
/// Finished shaders are also kept in memory (`ShaderCache`): pipelines share their shaders.
pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<Compiled, String> {
let windows = mem_windows();
console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows())
}
/// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile`
/// fills the caches without a title: the same keys as at its run).
pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Compiled, String> {
let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64);
if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) {
return compile_one();
@@ -115,7 +120,113 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w
split_wave64,
cache_dir: dxc::cache_dir(),
};
cached_shader(cache, key, blob, compile_one).map(|shader| shader.as_ref().clone())
let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one);
cached_shader(cache, key, blob, from_disk).map(|shader| shader.as_ref().clone())
}
/// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run
/// does not translate again what an earlier run of the same XCL build translated. The DXIL
/// cache is keyed by the generated HLSL, so it needs the translation first: a retail game's
/// ~2 800 programs (611 of more than 10 000 instructions) took its loading threads 0.1 - 0.3 s
/// each at every start. Keyed by two hashes and the length of the bytes, the stage and the
/// translation parameters; the XCL binary's hash is in each file (another build: a miss).
/// `XCL_TRANSLATED_CACHE=0` turns it off.
mod translated {
use super::{Compiled, Stage};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
const MAGIC: &[u8; 8] = b"XCLTRAN1";
/// the running XCL binary's hash (0: unknown – the disk is not used)
fn identity() -> u64 {
static I: OnceLock<u64> = OnceLock::new();
*I.get_or_init(|| {
if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") {
return 0;
}
std::env::current_exe().and_then(std::fs::read).map_or(0, |b| crate::gpu::shader::fnv64(&b) | 1)
})
}
/// a second hash of the bytes, independent of `fnv64`'s
fn hash2(b: &[u8]) -> u64 {
b.iter().fold(0x9E37_79B9_7F4A_7C15u64, |h, &x| (h ^ x as u64).wrapping_mul(0xFF51_AFD7_ED55_8CCD).rotate_left(29))
}
fn file(dir: &Path, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf {
dir.join("translated").join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", crate::gpu::shader::fnv64(blob), split as u8))
}
fn header(ident: u64, blob: &[u8]) -> Vec<u8> {
let mut h = MAGIC.to_vec();
for v in [ident, blob.len() as u64, hash2(blob)] {
h.extend_from_slice(&v.to_le_bytes());
}
h
}
pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option<Compiled> {
let b = std::fs::read(path).ok()?;
let head = header(ident, blob);
let mut r = b.strip_prefix(head.as_slice())?;
let u32_ = |r: &mut &[u8]| -> Option<u32> {
let (v, rest) = r.split_first_chunk::<4>()?;
*r = rest;
Some(u32::from_le_bytes(*v))
};
let n = u32_(&mut r)? as usize;
let mut samplers = Vec::with_capacity(n.min(64));
for _ in 0..n {
let s = [u32_(&mut r)?, u32_(&mut r)?, u32_(&mut r)?, u32_(&mut r)?];
let (&cmp, rest) = r.split_first()?;
r = rest;
samplers.push((s, cmp != 0));
}
let len = u32_(&mut r)? as usize;
(r.len() == len && len > 0).then(|| Compiled { dxil: r.to_vec(), samplers })
}
pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) {
let mut b = header(ident, blob);
b.extend_from_slice(&(c.samplers.len() as u32).to_le_bytes());
for (s, cmp) in &c.samplers {
s.iter().for_each(|v| b.extend_from_slice(&v.to_le_bytes()));
b.push(*cmp as u8);
}
b.extend_from_slice(&(c.dxil.len() as u32).to_le_bytes());
b.extend_from_slice(&c.dxil);
let Some(dir) = path.parent() else { return };
let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id()));
// written whole, then renamed: a reader never sees half a file
if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
}
/// `translate` through the disk (`ident` 0: not used)
pub(super) fn cached(
dir: &Path,
blob: &[u8],
stage: Stage,
sampler_base: u32,
windows: u32,
split: bool,
translate: impl FnOnce() -> Result<Compiled, String>,
) -> Result<Compiled, String> {
let ident = identity();
if ident == 0 {
return translate();
}
let path = file(dir, blob, stage, sampler_base, windows, split);
if let Some(c) = load_in(&path, ident, blob) {
super::dxc::note_memory_hit();
return Ok(c);
}
let c = translate()?;
store_in(&path, ident, blob, &c);
Ok(c)
}
}
fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
@@ -521,6 +632,24 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S
mod shader_cache_tests {
use super::*;
/// A translation on disk comes back for the same bytes and build only: other bytes of the
/// same length, another build or a cut file are misses.
#[test]
fn translations_on_disk_need_the_same_bytes_and_build() {
let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id()));
let path = dir.join("t.bin");
let c = Compiled { dxil: vec![1, 2, 3, 4, 5], samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] };
translated::store_in(&path, 42, b"console", &c);
let back = translated::load_in(&path, 42, b"console").expect("stored");
assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone()));
assert!(translated::load_in(&path, 43, b"console").is_none(), "another build");
assert!(translated::load_in(&path, 42, b"consolf").is_none(), "other bytes");
let full = std::fs::read(&path).unwrap();
std::fs::write(&path, &full[..full.len() - 1]).unwrap();
assert!(translated::load_in(&path, 42, b"console").is_none(), "a cut file");
let _ = std::fs::remove_dir_all(&dir);
}
fn key(hash: u64) -> ShaderKey {
ShaderKey {
hash,
+36
View File
@@ -252,6 +252,14 @@ pub fn capture(stage: &str, ptr: usize, len: usize) {
*st.stats.unknown_parts.entry(p.fourcc.clone()).or_default() += 1;
}
drop(g);
if !dumps_enabled() {
let names: Vec<&str> = parts.iter().map(|p| p.fourcc.as_str()).collect();
crate::xlog_info!("[SHADER] {stage} {h:016x}: {} B, format {}, parts [{}]", blob.len(), kind.label(), names.join(","));
if kind == Kind::XboxNative {
account_xbox(&blob, h);
}
return;
}
let dir = dump_dir();
let _ = std::fs::create_dir_all(&dir);
let base = dir.join(format!("{h:016x}_{stage}"));
@@ -269,6 +277,34 @@ pub fn capture(stage: &str, ptr: usize, len: usize) {
}
}
/// `XCL_DUMP_SHADERS=1`: every shader the title submits is written to the title's `shaders`
/// folder – the blob, a console program's FSSMs, its disassembly and its HLSL (translated once
/// more for that: the report's `recomp_*` counts come from it). Off by default: a retail game's
/// ~17 000 dumps took 4.8 GB, and translating each again took its loading threads ~0.1 s a
/// program at every start.
fn dumps_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1"))
}
/// Console container without dumps: its FSSM variants and instructions accounted.
fn account_xbox(blob: &[u8], h: u64) {
let Some(sh) = xbox::parse(blob) else { return };
let mut insts = xbox::InstStats::default();
insts.add_shader(&sh);
let failed = !sh.notes.is_empty() || sh.fssm.iter().any(|f| f.error.is_some() || f.programs.is_empty());
if let Some(st) = STATE.lock().unwrap().as_mut() {
for f in &sh.fssm {
*st.stats.xbox_hw_stages.entry(f.stage_label()).or_default() += 1;
}
st.stats.xbox_errors += failed as usize;
st.insts.merge(&insts);
}
if failed {
crate::xlog_info!("[SHADER] {h:016x}: console container {} – WARNING: incomplete parse (xcl disasm)", sh.stage);
}
}
/// Console container: account its FSSM variants and instructions, write the
/// decompressed FSSMs and the disassembly next to the blob.
fn capture_xbox(blob: &[u8], base: &std::path::Path, h: u64) {
+13 -3
View File
@@ -695,11 +695,21 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) {
}
}
/// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder
/// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder (`XCL_FRAME_DUMP=n`,
/// n > 1: every n-th; a title loading at a few frames a second shows few)
/// (`frame_<n>.bmp`, a quarter of each side; `XCL_FRAME_DUMP_FULL=1`: full size) – what the title presented, before the window.
fn frame_dump_due() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("XCL_FRAME_DUMP").is_some()) && PRESENTS.load(Ordering::Relaxed) % 120 == 20
static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let every = *EVERY.get_or_init(|| match std::env::var("XCL_FRAME_DUMP") {
Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120),
Err(_) => 0,
});
every > 0 && PRESENTS.load(Ordering::Relaxed) % every == 20.min(every - 1)
}
/// Frames shown so far.
pub fn presents() -> u64 {
PRESENTS.load(Ordering::Relaxed)
}
/// a copy of subresource 0 of `src` into a new readback buffer, recorded on `list`
+10 -5
View File
@@ -2744,11 +2744,11 @@ fn note_translation_error(e: String) {
ATTEMPT_NOTES.with(|n| n.borrow_mut().push(e));
return;
}
// each different reason once (the first five only hid a retail game's "mesh pipeline with
// AS" behind five earlier ones)
let mut g = TRANSLATE_ERRORS.lock().unwrap();
if g.len() < 5 {
if g.len() < 40 && !g.contains(&e) {
crate::xlog_warn!("D3D12.X: console shaders in the PSO without a translation: {e}");
}
if g.len() < 20 && !g.contains(&e) {
g.push(e);
}
}
@@ -3435,8 +3435,13 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *
if !is_console(ms) {
return None;
}
if subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32 && payload_shader(s.1).is_some()) {
note_translation_error("mesh pipeline with AS – not supported yet".into());
if let Some(a) = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32).and_then(|s| payload_shader(s.1)) {
let types: Vec<u32> = subs.iter().map(|s| s.0).collect();
note_translation_error(format!(
"mesh pipeline with AS {:016x} (MS {:016x}) – not supported yet; subobjects {types:?}",
crate::gpu::shader::fnv64(a),
crate::gpu::shader::fnv64(ms)
));
return Some(E_INVALIDARG);
}
let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1));
+1 -1
View File
@@ -70,7 +70,7 @@ pub fn host_main(boot_path: &Path) -> i32 {
if let Some(secs) = std::env::var("XCL_RUN_SECONDS").ok().and_then(|v| v.parse::<u64>().ok()) {
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(secs));
crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title");
crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({} frames shown)", crate::hle::d3d12x::present::presents());
crate::report::write_final(None);
crate::log::flush();
crate::hle::d3d12x::real::end_title(0);
+26 -2
View File
@@ -713,7 +713,8 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
}
};
if args.iter().any(|a| a == "--precompile") {
return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), t0);
let only = args.iter().position(|a| a == "--only").and_then(|i| args.get(i + 1)).map(|s| s.to_ascii_lowercase());
return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), t0);
}
let agg = analyze(&input, recomp_on, compile, iface_on);
drop(input);
@@ -731,7 +732,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
/// no split form, so a title asked for other HLSL and compiled everything again. Still
/// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the
/// mesh pass-through, which the runtime builds for its pixel shader.
fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, t0: std::time::Instant) -> i32 {
fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, only: Option<&str>, t0: std::time::Instant) -> i32 {
let n = input.len().min(limit);
let next = AtomicUsize::new(0);
let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
@@ -755,6 +756,29 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, t0
let (name, blob) = input.get(i);
let Some(blob) = blob else { continue };
let Some(sh) = xbox::parse(&blob) else { continue };
if only.is_some_and(|o| !sh.stage.eq_ignore_ascii_case(o)) {
done.fetch_add(1, Ordering::Relaxed);
continue;
}
// a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`):
// into the translation cache too, so the title does not translate it again
if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) {
match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) {
Ok(_) => compiled.fetch_add(1, Ordering::Relaxed),
Err(e) => {
let mut g = errors.lock().unwrap();
if g.len() < 10 {
g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or(""))));
}
failed.fetch_add(1, Ordering::Relaxed)
}
};
let d = done.fetch_add(1, Ordering::Relaxed) + 1;
if d % 200 == 0 {
eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64());
}
continue;
}
for f in &sh.fssm {
let Some(mode) = recomp::interface(&blob, &sh, f) else { continue };
let jobs: Vec<(&str, Option<String>)> = match &mode {
+2
View File
@@ -112,6 +112,8 @@ fn test_title_runs_and_game_folder_is_untouched() {
.arg("--")
.arg("--hello")
.env("XCL_DATA_ROOT", &data)
// the shader dumps and their translation, which the report's shader counts come from
.env("XCL_DUMP_SHADERS", "1")
.output()
.expect("spawn xcl");
let stdout = String::from_utf8_lossy(&out.stdout);