diff --git a/README.md b/README.md index 3f76544f6a..7e5002d58e 100644 --- a/README.md +++ b/README.md @@ -486,6 +486,14 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. `hle,-kernelx.dll!GetTickCount,gameinput`. - `XCL_D3D12_TRACE=1` (any value): every call console code makes to a public D3D12.X method is logged with the interface and method name. Very verbose: use it for a short run. + - `XCL_SHADER_DEBUG_DIR=`: DXC-compiled shaders use full debug information and keep the + exact stripped DXIL submitted to D3D12, its matching PDB, generated HLSL and a JSON manifest + under that folder. Programs are compiled whole while this is set (as with `XCL_LINK_MEM=0`) so + the PDB comes from the compilation that produced the submitted DXIL. Its `cache\` is a separate + warm cache. Cache hits check the PDB against the hash saved at compilation. A mismatch or an + older manifest without that hash triggers a rebuild. Keep or remove the folder as one unit. + The files contain title-derived shader code: keep them private. Direct-DXIL translations do + not pass through DXC and therefore have no HLSL PDB. - Title data: `%LOCALAPPDATA%\XCL\\` (`%XCL_DATA_ROOT%`): `xcl.toml`, `overlay\`, `saves\`, `pls\` (the title's `S:\`), `temp\` (`T:\`), `cache\`, `logs\xcl.log`, `logs\report.json` (the previous run's: `xcl.prev.log`, `report.prev.json`). diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index a5c381e226..d9d1e15e66 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -8,6 +8,7 @@ //! Which DXC it is matters ([`Toolchain::outdated`]), so the one that was loaded is logged and //! kept for `report.json` ([`toolchain`]). +use std::borrow::Cow; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; @@ -17,7 +18,9 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{ - CLSID_DxcCompiler, CLSID_DxcLinker, CLSID_DxcUtils, DxcBuffer, IDxcBlob, IDxcBlobEncoding, IDxcCompiler3, IDxcLinker, IDxcResult, IDxcUtils, DXC_CP, DXC_CP_UTF8, + CLSID_DxcCompiler, CLSID_DxcLinker, CLSID_DxcUtils, DxcBuffer, IDxcBlob, + IDxcBlobEncoding, IDxcCompiler3, IDxcLinker, IDxcResult, IDxcUtils, DXC_CP, + DXC_CP_UTF8, DXC_OUT_OBJECT, DXC_OUT_PDB, }; use windows::Win32::System::Com::{IMalloc, IMalloc_Impl}; @@ -893,7 +896,152 @@ pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result< /// takes the direct DXIL translator instead (`pso::compile_console_shader`). pub const UNOPTIMISED_ABOVE: usize = 8 * 1024 * 1024; +fn shader_debug_dir() -> Option<PathBuf> { + std::env::var_os("XCL_SHADER_DEBUG_DIR").filter(|v| !v.is_empty()).map(PathBuf::from) +} + +fn blob_bytes(blob: &IDxcBlob) -> Vec<u8> { + unsafe { std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec() } +} + +fn symbol_bundle_dir(root: &Path, key: u64, dxil: &[u8]) -> PathBuf { + root.join("symbols").join(format!("{key:016x}-{:016x}", crate::gpu::shader::fnv64(dxil))) +} + +fn symbol_index_file(root: &Path, dxil: &[u8]) -> PathBuf { + root.join("symbols").join("by-dxil").join(format!("{:016x}.txt", crate::gpu::shader::fnv64(dxil))) +} + +fn symbol_bundle_complete(root: &Path, key: u64, dxil: &[u8]) -> bool { + let dir = symbol_bundle_dir(root, key, dxil); + let Some(manifest) = std::fs::read(dir.join("manifest.json")).ok() + .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok()) else { return false }; + manifest["cache_key"] == format!("{key:016x}") + && manifest["dxil_fnv64"] == format!("{:016x}", crate::gpu::shader::fnv64(dxil)) + && std::fs::read(dir.join("shader.dxil")).ok().as_deref() == Some(dxil) + && std::fs::metadata(dir.join(format!("{key:016x}.hlsl"))).is_ok_and(|m| m.len() != 0) + && std::fs::read(dir.join(format!("{key:016x}.pdb"))).is_ok_and(|pdb| { + !pdb.is_empty() && manifest["pdb_fnv64"] == format!("{:016x}", crate::gpu::shader::fnv64(&pdb)) + }) +} + +fn store_symbol_index(root: &Path, key: u64, dxil: &[u8]) -> Result<(), String> { + static NEXT_INDEX_TEMP: AtomicU64 = AtomicU64::new(0); + let file = symbol_index_file(root, dxil); + let bundle = symbol_bundle_dir(root, key, dxil).file_name().unwrap_or_default().to_string_lossy().into_owned(); + if std::fs::read_to_string(&file).is_ok_and(|v| v == bundle) { + return Ok(()); + } + let parent = file.parent().unwrap_or(root); + std::fs::create_dir_all(parent).map_err(|e| format!("shader symbols: create index directory: {e}"))?; + let nonce = NEXT_INDEX_TEMP.fetch_add(1, Ordering::Relaxed); + let temp = parent.join(format!(".{:016x}.{}-{nonce}.tmp", crate::gpu::shader::fnv64(dxil), std::process::id())); + std::fs::write(&temp, &bundle).map_err(|e| format!("shader symbols: write index: {e}"))?; + if std::fs::rename(&temp, &file).is_err() { + if std::fs::read_to_string(&file).is_ok_and(|v| v == bundle) { + let _ = std::fs::remove_file(&temp); + return Ok(()); + } + let _ = std::fs::remove_file(&file); + if let Err(e) = std::fs::rename(&temp, &file) { + let _ = std::fs::remove_file(&temp); + return Err(format!("shader symbols: publish index: {e}")); + } + } + Ok(()) +} + +fn shader_symbols_available_in(root: &Path, dxil: &[u8]) -> bool { + let Ok(bundle) = std::fs::read_to_string(symbol_index_file(root, dxil)) else { return false }; + let Some((key, hash)) = bundle.split_once('-') else { return false }; + if key.len() != 16 || hash != format!("{:016x}", crate::gpu::shader::fnv64(dxil)) { + return false; + } + let Ok(key) = u64::from_str_radix(key, 16) else { return false }; + symbol_bundle_complete(root, key, dxil) +} + +pub(super) fn shader_symbols_available(dxil: &[u8]) -> bool { + shader_debug_dir().is_none_or(|root| shader_symbols_available_in(&root, dxil)) +} + +fn store_symbol_bundle(root: &Path, key: u64, src: &str, entry: &str, profile: &str, dxil: &[u8], pdb: &[u8]) -> Result<(), String> { + static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + let parent = root.join("symbols"); + let final_dir = symbol_bundle_dir(root, key, dxil); + if symbol_bundle_complete(root, key, dxil) { + return store_symbol_index(root, key, dxil); + } + std::fs::create_dir_all(&parent).map_err(|e| format!("shader symbols: create output directory: {e}"))?; + let id = final_dir.file_name().unwrap_or_default().to_string_lossy(); + let nonce = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let temp_dir = parent.join(format!(".{id}.tmp-{}-{nonce}", std::process::id())); + std::fs::create_dir(&temp_dir).map_err(|e| format!("shader symbols: create temporary bundle: {e}"))?; + let pdb_name = format!("{key:016x}.pdb"); + let hlsl_name = format!("{key:016x}.hlsl"); + let manifest = serde_json::to_vec_pretty(&serde_json::json!({ + "schema": "xcl-shader-symbols-v1", + "cache_key": format!("{key:016x}"), + "dxil_fnv64": format!("{:016x}", crate::gpu::shader::fnv64(dxil)), + "pdb_fnv64": format!("{:016x}", crate::gpu::shader::fnv64(pdb)), + "dxil": "shader.dxil", + "pdb": pdb_name, + "hlsl": hlsl_name, + "entry": entry, + "profile": profile, + "xcl_version": env!("CARGO_PKG_VERSION"), + "translator_source_id": env!("XCL_TRANSLATOR_SOURCE_ID"), + "dxc_toolchain_id": toolchain_identity(), + "debug_information": "full-separate" + })) + .map_err(|e| format!("shader symbols: encode manifest: {e}"))?; + let result = (|| { + std::fs::write(temp_dir.join("shader.dxil"), dxil).map_err(|e| format!("shader symbols: write DXIL: {e}"))?; + std::fs::write(temp_dir.join(&pdb_name), pdb).map_err(|e| format!("shader symbols: write PDB: {e}"))?; + std::fs::write(temp_dir.join(&hlsl_name), src).map_err(|e| format!("shader symbols: write HLSL: {e}"))?; + std::fs::write(temp_dir.join("manifest.json"), manifest).map_err(|e| format!("shader symbols: write manifest: {e}"))?; + match std::fs::rename(&temp_dir, &final_dir) { + Ok(()) => Ok(()), + Err(_) if symbol_bundle_complete(root, key, dxil) => Ok(()), + Err(first) if final_dir.is_dir() => { + let stale = parent.join(format!(".{id}.stale-{}-{nonce}", std::process::id())); + std::fs::rename(&final_dir, &stale).map_err(|e| format!("shader symbols: move incomplete bundle aside after {first}: {e}"))?; + if let Err(e) = std::fs::rename(&temp_dir, &final_dir) { + let _ = std::fs::rename(&stale, &final_dir); + return Err(format!("shader symbols: replace incomplete bundle: {e}")); + } + let _ = std::fs::remove_dir_all(stale); + Ok(()) + } + Err(e) => Err(format!("shader symbols: publish bundle: {e}")), + } + })(); + if temp_dir.is_dir() { + let _ = std::fs::remove_dir_all(&temp_dir); + } + result.and_then(|()| store_symbol_index(root, key, dxil)) +} + +fn shader_debug_key(src: &str, entry: &str, profile: &str, extra: &[&str]) -> u64 { + let mut h = cache_key(src, entry, profile); + if extra.is_empty() { + return h; + } + for part in std::iter::once("xcl-dxc-extra-args").chain(extra.iter().copied()) { + for byte in part.bytes().chain([0]) { + h ^= byte as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + } + h +} + fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> { + // A linked shader is not emitted by the same DXC compilation as either input PDB. Keep + // symbol capture to one compilation so the submitted DXIL and stored PDB remain an exact pair. + if let Some(debug_dir) = shader_debug_dir() { + return compile_here_in(src, entry, profile, extra, Some(&debug_dir)); + } // compute (also what MS and GS programs run as): DXC's time for its memory accesses is // linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before. if profile.starts_with("cs_") && linking() { @@ -1062,6 +1210,19 @@ fn compile_whole(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Resul /// `compile_whole` through the compiler `c`. fn compile_with(c: &IDxcCompiler3, src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> { + compile_with_debug(c, src, entry, profile, extra, None) +} + +fn compile_here_in(src: &str, entry: &str, profile: &str, extra: &[&str], debug_dir: Option<&Path>) -> Result<Vec<u8>, String> { + compile_with_debug(&compiler()?, src, entry, profile, extra, debug_dir) +} + +fn compile_with_debug(c: &IDxcCompiler3, src: &str, entry: &str, profile: &str, extra: &[&str], debug_dir: Option<&Path>) -> Result<Vec<u8>, String> { + let key = debug_dir.map(|_| shader_debug_key(src, entry, profile, extra)); + let source = match key { + Some(key) => Cow::Owned(format!("#line 1 \"{key:016x}.hlsl\"\n{src}")), + None => Cow::Borrowed(src), + }; let mut args: Vec<Vec<u16>> = ["-E", entry, "-T", profile, "-HV", "2021"].iter().map(|a| crate::util::wide(a)).collect(); // DXC's optimiser was superlinear on translated programs full of short-circuit `?:` / // `&&` / `if` per instruction (a 1589-instruction console CS: ~6 min and > 30 GB at -O3). @@ -1077,12 +1238,45 @@ fn compile_with(c: &IDxcCompiler3, src: &str, entry: &str, profile: &str, extra: args.push(crate::util::wide("-O1")); } } + if let Some(key) = key { + args.extend(["-Zi", "-Qstrip_debug", "-Fd"].map(crate::util::wide)); + args.push(crate::util::wide(&format!("{key:016x}.pdb"))); + } args.extend(extra.iter().map(|a| crate::util::wide(a))); let ptrs: Vec<PCWSTR> = args.iter().map(|a| PCWSTR(a.as_ptr())).collect(); - let buf = DxcBuffer { Ptr: src.as_ptr() as *const c_void, Size: src.len(), Encoding: DXC_CP_UTF8.0 }; + let buf = DxcBuffer { Ptr: source.as_ptr() as *const c_void, Size: source.len(), Encoding: DXC_CP_UTF8.0 }; unsafe { let r: IDxcResult = c.Compile(&buf, Some(&ptrs), None).map_err(|e| format!("Compile: {e}"))?; - output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()) + let status = r.GetStatus().map_err(|e| format!("{e}"))?; + if status.is_err() { + let msg = r + .GetErrorBuffer() + .ok() + .map(|b| { + let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()); + String::from_utf8_lossy(s).trim_end_matches('\0').to_string() + }) + .unwrap_or_default(); + if status == windows::Win32::Foundation::E_OUTOFMEMORY { + return Err(format!("dxc (0x{:08X}): {msg}", status.0 as u32)); + } + return Err(format!("dxc: {msg}")); + } + let blob: IDxcBlob = if key.is_some() { + let mut output = None; + r.GetOutput(DXC_OUT_OBJECT, std::ptr::null_mut(), &mut output).map_err(|e| format!("DXC object output: {e}"))?; + output.ok_or_else(|| "DXC object output is missing".to_string())? + } else { + r.GetResult().map_err(|e| format!("{e}"))? + }; + let dxil = blob_bytes(&blob); + if let (Some(root), Some(key)) = (debug_dir, key) { + let mut output = None; + r.GetOutput(DXC_OUT_PDB, std::ptr::null_mut(), &mut output).map_err(|e| format!("DXC PDB output: {e}"))?; + let pdb: IDxcBlob = output.ok_or_else(|| "DXC PDB output is missing".to_string())?; + store_symbol_bundle(root, key, &source, entry, profile, &dxil, &blob_bytes(&pdb))?; + } + Ok(dxil) } } @@ -1133,8 +1327,12 @@ pub(crate) fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } -/// Folder of the DXIL cache: `XCL_DXIL_CACHE`, else `%LOCALAPPDATA%\xcl\dxil`. +/// Folder of the DXIL cache: `XCL_SHADER_DEBUG_DIR\cache` while shader symbols are enabled; +/// otherwise `XCL_DXIL_CACHE`, else `%LOCALAPPDATA%\xcl\dxil`. pub fn cache_dir() -> PathBuf { + if let Some(d) = shader_debug_dir() { + return d.join("cache"); + } if let Ok(d) = std::env::var("XCL_DXIL_CACHE") { return PathBuf::from(d); } @@ -1287,13 +1485,18 @@ fn process_cache_lock(file: &Path) -> Result<ProcessCacheLock, String> { Ok(ProcessCacheLock { handle }) } -fn cached_file(file: &Path) -> Option<Vec<u8>> { +fn cached_file(file: &Path, key: u64) -> Option<Vec<u8>> { + let debug_dir = shader_debug_dir(); + cached_file_in(file, key, debug_dir.as_deref()) +} + +fn cached_file_in(file: &Path, key: u64, debug_dir: Option<&Path>) -> Option<Vec<u8>> { let read = { let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); std::fs::read(file) }; if let Ok(b) = read { - if valid_dxil_container(&b) { + if valid_dxil_container(&b) && debug_dir.is_none_or(|root| symbol_bundle_complete(root, key, &b)) { return Some(b); } } @@ -1420,7 +1623,7 @@ where let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); let err_file = dir.join(format!("{key:016x}.err")); - if let Some(b) = cached_file(&file) { + if let Some(b) = cached_file(&file, key) { counters.hits.fetch_add(1, Ordering::Relaxed); return Ok((b, true)); } @@ -1439,7 +1642,7 @@ where let _guard = flight.lock().unwrap_or_else(|e| e.into_inner()); let _process_guard = process_cache_lock(&file)?; // Another caller may have populated the cache while this one waited. - if let Some(b) = cached_file(&file) { + if let Some(b) = cached_file(&file, key) { counters.coalesced_hits.fetch_add(1, Ordering::Relaxed); return Ok((b, true)); } @@ -1680,6 +1883,115 @@ mod cache_tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn shader_debug_bundle_keeps_the_exact_dxil_and_full_pdb() { + use windows::Win32::Graphics::Direct3D::Dxc::{ + IDxcPdbUtils, IDxcUtils, CLSID_DxcPdbUtils, CLSID_DxcUtils, DXC_CP_ACP, + }; + + if location().is_err() { + return; + } + let root = std::env::temp_dir().join(format!("xcl-shader-symbols-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let src = "[numthreads(1, 1, 1)] void main() {}"; + let key = cache_key(src, "main", "cs_6_6"); + assert_eq!(shader_debug_key(src, "main", "cs_6_6", &[]), key); + assert_ne!(shader_debug_key(src, "main", "cs_6_6", &["-Gis"]), key); + let dxil = compile_here_in(src, "main", "cs_6_6", &[], Some(&root)).unwrap(); + let dir = symbol_bundle_dir(&root, key, &dxil); + assert_eq!(std::fs::read(dir.join("shader.dxil")).unwrap(), dxil); + let pdb = std::fs::read(dir.join(format!("{key:016x}.pdb"))).unwrap(); + assert!(!pdb.is_empty()); + let hlsl = std::fs::read_to_string(dir.join(format!("{key:016x}.hlsl"))).unwrap(); + assert_eq!(hlsl, format!("#line 1 \"{key:016x}.hlsl\"\n{src}")); + let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("manifest.json")).unwrap()).unwrap(); + assert_eq!(manifest["cache_key"], format!("{key:016x}")); + assert_eq!(manifest["profile"], "cs_6_6"); + assert_eq!(manifest["entry"], "main"); + assert!(!manifest.to_string().contains(root.to_string_lossy().as_ref())); + + let cache_file = root.join("cached.dxil"); + std::fs::write(&cache_file, &dxil).unwrap(); + assert_eq!(cached_file_in(&cache_file, key, Some(&root)).unwrap(), dxil); + assert!(shader_symbols_available_in(&root, &dxil)); + + unsafe { + let create = create_fn().unwrap(); + let mut raw = std::ptr::null_mut(); + let hr = create(&CLSID_DxcUtils, &IDxcUtils::IID, &mut raw); + assert!(hr.is_ok() && !raw.is_null(), "DxcCreateInstance(IDxcUtils): {hr:?}"); + let utils = IDxcUtils::from_raw(raw); + let pdb_blob = utils.CreateBlob(pdb.as_ptr() as *const c_void, pdb.len() as u32, DXC_CP_ACP).unwrap(); + + let mut raw = std::ptr::null_mut(); + let hr = create(&CLSID_DxcPdbUtils, &IDxcPdbUtils::IID, &mut raw); + assert!(hr.is_ok() && !raw.is_null(), "DxcCreateInstance(IDxcPdbUtils): {hr:?}"); + let pdb_utils = IDxcPdbUtils::from_raw(raw); + pdb_utils.Load(&pdb_blob).unwrap(); + assert!(pdb_utils.IsFullPDB().as_bool()); + assert!(pdb_utils.GetSourceCount().unwrap() > 0); + assert_eq!(pdb_utils.GetEntryPoint().unwrap().to_string(), "main"); + assert_eq!(pdb_utils.GetTargetProfile().unwrap().to_string(), "cs_6_6"); + } + + std::fs::remove_file(dir.join(format!("{key:016x}.pdb"))).unwrap(); + assert!(cached_file_in(&cache_file, key, Some(&root)).is_none()); + assert!(!shader_symbols_available_in(&root, &dxil)); + let rebuilt = compile_here_in(src, "main", "cs_6_6", &[], Some(&root)).unwrap(); + assert_eq!(rebuilt, dxil); + assert!(cached_file_in(&cache_file, key, Some(&root)).is_some()); + assert!(shader_symbols_available_in(&root, &dxil)); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn shader_debug_cache_rejects_a_same_size_pdb_swap() { + if location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let root = std::env::temp_dir().join(format!("xcl-pdb-swap-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let src_a = "RWByteAddressBuffer outbuf : register(u0); [numthreads(1,1,1)] void main() { outbuf.Store(0, 1); }"; + let src_b = src_a.replace("0, 1", "0, 2"); + let compile = |src: &str| compile_here_in(src, "main", "cs_6_6", &[], Some(&root)).unwrap(); + let pdb_path = |src: &str, dxil: &[u8]| { + let key = cache_key(src, "main", "cs_6_6"); + symbol_bundle_dir(&root, key, dxil).join(format!("{key:016x}.pdb")) + }; + let dxil_a = compile(src_a); + let dxil_b = compile(&src_b); + assert_ne!(dxil_a, dxil_b); + let path_a = pdb_path(src_a, &dxil_a); + let pdb_a = std::fs::read(&path_a).unwrap(); + let pdb_b = std::fs::read(pdb_path(&src_b, &dxil_b)).unwrap(); + assert_eq!(pdb_a.len(), pdb_b.len()); + assert_ne!(pdb_a, pdb_b); + + let file = root.join("cached.dxil"); + std::fs::write(&file, &dxil_a).unwrap(); + let key = cache_key(src_a, "main", "cs_6_6"); + let disk_hit = || cached_file_in(&file, key, Some(&root)).is_some(); + assert!(disk_hit() && shader_symbols_available_in(&root, &dxil_a)); + std::fs::write(&path_a, pdb_b).unwrap(); + assert!(!shader_symbols_available_in(&root, &dxil_a), "index accepted the swapped PDB"); + assert!(!disk_hit(), "disk cache accepted the swapped PDB"); + assert_eq!(compile(src_a), dxil_a); + assert_eq!(std::fs::read(&path_a).unwrap(), pdb_a); + assert!(disk_hit() && shader_symbols_available_in(&root, &dxil_a)); + + // A bundle written before PDB hashes were recorded must be refreshed once. + let manifest_path = path_a.with_file_name("manifest.json"); + let mut manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(&manifest_path).unwrap()).unwrap(); + manifest.as_object_mut().unwrap().remove("pdb_fnv64").unwrap(); + std::fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap(); + assert!(!disk_hit()); + assert_eq!(compile(src_a), dxil_a); + assert!(disk_hit() && shader_symbols_available_in(&root, &dxil_a)); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn cache_key_tracks_the_dxc_toolchain() { let a = cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-a"); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 69a926ee0b..90efbb5ebe 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -412,15 +412,26 @@ mod translated { h } - pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option<Compiled> { + pub(super) fn load_in_with( + path: &Path, + ident: u64, + blob: &[u8], + require_symbols: bool, + symbols_available: impl FnOnce(&[u8]) -> bool, + ) -> Option<Compiled> { let b = { let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); std::fs::read(path) }.ok()?; - decode_entry(b, ident, blob) + decode_entry_with(b, ident, blob, require_symbols, symbols_available) } - pub(super) fn decode_entry(mut b: Vec<u8>, ident: u64, blob: &[u8]) -> Option<Compiled> { + #[cfg(test)] + pub(super) fn decode_entry(b: Vec<u8>, ident: u64, blob: &[u8]) -> Option<Compiled> { + decode_entry_with(b, ident, blob, false, |_| true) + } + + fn decode_entry_with(mut b: Vec<u8>, ident: u64, blob: &[u8], require_symbols: bool, symbols_available: impl FnOnce(&[u8]) -> bool) -> Option<Compiled> { let head = header(ident, blob); let mut r = b.strip_prefix(head.as_slice())?; let u32_ = |r: &mut &[u8]| -> Option<u32> { @@ -446,6 +457,7 @@ mod translated { if len == 0 { return None; } let (whole, mut rest) = r.split_at_checked(len)?; if !super::dxc::valid_dxil_container(whole) { return None; } + if require_symbols && !symbols_available(whole) { return None; } let dispatch_chain = if rest.is_empty() { // Keep the file allocation instead of allocating a second payload-sized buffer. // Split entries still copy below, so the whole shader does not retain all pieces. @@ -472,6 +484,10 @@ mod translated { Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap }) } + pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option<Compiled> { + load_in_with(path, ident, blob, false, |_| true) + } + pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { if !super::dxc::valid_dxil_container(&c.dxil) { return; @@ -729,7 +745,17 @@ mod translated { } let rerouted = rerouted_identity(ident, direct); for id in [ident, rerouted] { - if let Some(c) = load_in(&file_for(dir, id, blob, stage, sampler_base, windows, split, rt32_mask), id, blob) { + // The HLSL path's translated entry sits above the DXC cache. In symbol mode it is + // usable only while the exact DXIL/PDB/source bundle published with it is complete. + // A rerouted enormous shader is direct DXIL and has no DXC PDB. + let require_symbols = Backend::current() == Backend::Hlsl && id == ident; + if let Some(c) = load_in_with( + &file_for(dir, id, blob, stage, sampler_base, windows, split, rt32_mask), + id, + blob, + require_symbols, + super::dxc::shader_symbols_available, + ) { super::dxc::note_memory_hit(); if stage == Stage::Compute { super::note_compute_path( @@ -2034,6 +2060,8 @@ mod shader_cache_tests { 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, back.dispatch_remap), (c.dxil.clone(), c.samplers.clone(), c.dispatch_remap)); + assert!(translated::load_in_with(&path, 42, b"console", true, |_| false).is_none(), "a missing symbol bundle invalidates an HLSL cache hit"); + assert!(translated::load_in_with(&path, 42, b"console", true, |_| true).is_some(), "a complete symbol bundle keeps the cache hit"); assert!(translated::load_in(&path, 43, b"console").is_none(), "another identity"); assert!(translated::load_in(&path, 42, b"consolf").is_none(), "other bytes"); let full = std::fs::read(&path).unwrap(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 3b3b803f62..7cd66478bd 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -4692,6 +4692,49 @@ mod tests { } } + #[test] + fn direct_dump_does_not_publish_a_manifest_for_a_missing_artifact() { + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + let root = Temp(std::env::temp_dir().join(format!("xcl-direct-dump-write-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&root.0); + std::fs::create_dir_all(root.0.join("sample.guest.bin")).unwrap(); + let err = write_direct_dump(&root.0, "sample", b"guest", &Ok(vec![1, 2, 3]), &serde_json::json!({ "schema_version": 1 })).unwrap_err(); + assert!(err.contains("sample.guest.bin"), "{err}"); + assert!(!root.0.join("sample.direct.dxil").exists()); + assert!(!root.0.join("sample.manifest.json").exists(), "a manifest must not advertise artifacts that were not saved"); + } + + #[test] + fn direct_dump_invalidates_an_old_manifest_before_replacing_artifacts() { + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + let root = Temp(std::env::temp_dir().join(format!("xcl-direct-dump-replace-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&root.0); + std::fs::create_dir_all(&root.0).unwrap(); + let old_manifest = serde_json::json!({ "schema_version": 1, "generation": "old" }); + write_direct_dump(&root.0, "sample", b"guest", &Ok(vec![1, 2, 3]), &old_manifest).unwrap(); + assert!(root.0.join("sample.manifest.json").is_file()); + + // A directory makes the replacement error artifact unwritable. The previous manifest + // must already be gone, or it would still authenticate the old DXIL after this failure. + std::fs::create_dir(root.0.join("sample.direct.err.txt")).unwrap(); + let new_manifest = serde_json::json!({ "schema_version": 1, "generation": "new" }); + let err = write_direct_dump(&root.0, "sample", b"guest", &Err("new failure".into()), &new_manifest).unwrap_err(); + assert!(err.contains("sample.direct.err.txt"), "{err}"); + assert!(!root.0.join("sample.manifest.json").exists(), "a failed replacement must invalidate the previous manifest"); + } + #[test] fn hlsl_export_is_ordered_and_exact_hash_selects_one_record() { struct Temp(std::path::PathBuf); @@ -4859,6 +4902,33 @@ fn name_hash(name: &str) -> u64 { h } +/// Invalidate an earlier generation, write the required artifacts, then publish the new manifest. +fn write_direct_dump( + dir: &std::path::Path, + prefix: &str, + guest: &[u8], + result: &Result<Vec<u8>, String>, + manifest: &serde_json::Value, +) -> Result<(), String> { + let path = |suffix: &str| dir.join(format!("{prefix}.{suffix}")); + let manifest_path = path("manifest.json"); + match std::fs::remove_file(&manifest_path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("could not invalidate {}: {e}", manifest_path.display())), + } + let write = |suffix: &str, bytes: &[u8]| { + let path = path(suffix); + std::fs::write(&path, bytes).map_err(|e| format!("could not write {}: {e}", path.display())) + }; + write("guest.bin", guest)?; + match result { + Ok(dxil) => write("direct.dxil", dxil)?, + Err(e) => write("direct.err.txt", e.as_bytes())?, + } + std::fs::write(&manifest_path, manifest.to_string()).map_err(|e| format!("could not write {}: {e}", manifest_path.display())) +} + /// `--direct [--sample N] [--seed S] [--validate] [--compare] [--split 0|1] [--windows W]`: /// every program of a seeded sample of N records (default 200 programs' worth; `--sample 0` = /// all) through the direct DXIL translator; per-stage outcomes, a ranked histogram of what it @@ -4969,15 +5039,35 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> Err(e) => *lanes_why.lock().unwrap().entry(survey_key(&e)).or_default() += 1, } } + let prefix = format!("{blob_hash:016x}_f{fi}_{:x}", p.offset); let dump = |suffix: &str, bytes: &[u8]| { if let Some(d) = &dump_dir { - let _ = std::fs::write(d.join(format!("{blob_hash:016x}_f{fi}_{:x}.{suffix}", p.offset)), bytes); + let path = d.join(format!("{prefix}.{suffix}")); + if let Err(e) = std::fs::write(&path, bytes) { + eprintln!("direct: could not write {}: {e}", path.display()); + } } }; - dump("guest.bin", code); - match &r { - Ok(dxil) => dump("direct.dxil", dxil), - Err(e) => dump("direct.err.txt", e.as_bytes()), + if let Some(dir) = &dump_dir { + let manifest = serde_json::json!({ + "schema_version": 1, + "backend": "direct-dxil", + "record_hash": format!("{blob_hash:016x}"), + "fssm_index": fi, + "program_offset": p.offset, + "stage": coverage::stage_name(&mode), + "wave64": wave64, + "split_wave64": o.split, + "memory_windows": windows, + "validation_requested": validate, + "guest_fnv64": format!("{:016x}", shader::fnv64(code)), + "dxil_fnv64": r.as_ref().ok().map(|bytes| format!("{:016x}", shader::fnv64(bytes))), + "translation_wall_us": time.as_micros() as u64, + "error": r.as_ref().err(), + }); + if let Err(e) = write_direct_dump(dir, &prefix, code, &r, &manifest) { + eprintln!("direct: {e}"); + } } let hlsl_size = (compare && r.is_ok()) .then(|| { diff --git a/scripts/test_verify_shader_dump.py b/scripts/test_verify_shader_dump.py new file mode 100644 index 0000000000..3fc5b7a5d7 --- /dev/null +++ b/scripts/test_verify_shader_dump.py @@ -0,0 +1,62 @@ +import json +from pathlib import Path +import tempfile +import unittest + +from verify_shader_dump import verify + + +class ShaderDumpTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.prefix = Path(tmp.name) / "0000000000000001_f0_24" + self.path = self.prefix.with_suffix(".manifest.json") + self.manifest = dict(schema_version=1, backend="direct-dxil", guest_fnv64="a430d84680aabd0b", + dxil_fnv64="85944171f73967e8", error=None) + self.prefix.with_suffix(".guest.bin").write_bytes(b"hello") + self.prefix.with_suffix(".direct.dxil").write_bytes(b"foobar") + + def check(self): + self.path.write_text(json.dumps(self.manifest), encoding="utf-8") + return verify(self.path) + + def test_translation(self): + self.assertEqual(self.check(), "guest and translated DXIL match") + self.prefix.with_suffix(".direct.dxil").write_bytes(b"foo") + with self.assertRaisesRegex(ValueError, "dxil_fnv64 mismatch"): + self.check() + + def test_hashes_every_binary_chunk(self): + self.prefix.with_suffix(".guest.bin").write_bytes(bytes(range(256)) * 512 + b"\0") + self.manifest["guest_fnv64"] = "9fd6a807c893b7df" + self.assertEqual(self.check(), "guest and translated DXIL match") + + def test_error_uses_exact_bytes_even_when_old_dxil_is_present(self): + error = "first\nsecond: \u0394" + self.manifest.update(dxil_fnv64=None, error=error) + diagnostic = self.prefix.with_suffix(".direct.err.txt") + diagnostic.write_bytes(error.encode("utf-8")) + self.assertEqual(self.check(), "guest and translation error match") + diagnostic.write_bytes(error.replace("\n", "\r\n").encode("utf-8")) + with self.assertRaisesRegex(ValueError, "error text mismatch"): + self.check() + + def test_guest_changed_or_missing(self): + guest = self.prefix.with_suffix(".guest.bin") + guest.write_bytes(b"HELLO") + with self.assertRaisesRegex(ValueError, "guest_fnv64 mismatch"): + self.check() + guest.unlink() + with self.assertRaises(FileNotFoundError): + self.check() + + def test_version_and_ambiguous_result(self): + for change in (dict(schema_version=True), dict(schema_version=2), dict(backend="other"), + dict(error="also an error"), dict(dxil_fnv64=None)): + with self.subTest(change=change): + before = dict(self.manifest) + self.manifest.update(change) + with self.assertRaises(ValueError): + self.check() + self.manifest = before diff --git a/scripts/verify_shader_dump.py b/scripts/verify_shader_dump.py new file mode 100644 index 0000000000..a08813f8b8 --- /dev/null +++ b/scripts/verify_shader_dump.py @@ -0,0 +1,66 @@ +"""Check the files next to a manifest written by xcl shaders --direct --dump. + +Run python scripts/verify_shader_dump.py FILE.manifest.json [FILE.manifest.json ...]. +""" + +import argparse +import json +from pathlib import Path +import sys + + +def fnv64(path): + """Match shader::fnv64 on the bytes of a dump file.""" + value = 0xCBF29CE484222325 + with path.open("rb") as stream: + while chunk := stream.read(65536): + for byte in chunk: + value = ((value ^ byte) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return f"{value:016x}" + + +def verify(path): + suffix = ".manifest.json" + if not path.name.endswith(suffix): + raise ValueError(f"expected a {suffix} file") + manifest = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(manifest, dict): + raise ValueError("expected a manifest object") + if type(manifest.get("schema_version")) is not int or manifest["schema_version"] != 1: + raise ValueError("expected schema_version 1") + if manifest.get("backend") != "direct-dxil": + raise ValueError("expected backend direct-dxil") + prefix = path.name[:-len(suffix)] + guest = path.with_name(prefix + ".guest.bin") + if fnv64(guest) != manifest["guest_fnv64"]: + raise ValueError(f"{guest.name}: guest_fnv64 mismatch") + + dxil_hash, error = manifest["dxil_fnv64"], manifest["error"] + if error is None and isinstance(dxil_hash, str): + dxil = path.with_name(prefix + ".direct.dxil") + if fnv64(dxil) != dxil_hash: + raise ValueError(f"{dxil.name}: dxil_fnv64 mismatch") + return "guest and translated DXIL match" + if dxil_hash is None and isinstance(error, str): + diagnostic = path.with_name(prefix + ".direct.err.txt") + if diagnostic.read_bytes() != error.encode("utf-8"): + raise ValueError(f"{diagnostic.name}: error text mismatch") + return "guest and translation error match" + raise ValueError("expected one translation result (dxil_fnv64 or error)") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("manifest", type=Path, nargs="+") + failed = False + for path in parser.parse_args(argv).manifest: + try: + print(f"{path}: {verify(path)}") + except (OSError, ValueError, KeyError) as exc: + print(f"{path}: {exc}", file=sys.stderr) + failed = True + return int(failed) + + +if __name__ == "__main__": + sys.exit(main())