Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,18 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder

## Tests

### Offline shader diagnostic bundles

With Python 3.11+, `python scripts/analyze_shader.py FILE.manifest.json --out diagnostics`
copies a direct shader dump into a new directory and verifies the copied guest/DXIL hashes
(or the exact translation error). It writes `report.json` with the original manifest, SHA-256
hashes and local artifact paths. Each invocation has its own directory, so an older result
cannot be mistaken for a new one. An invalid bundle returns exit 1; a verified bundle with no
analyzer requested reports `SKIPPED` and returns 0. This is not DXIL validation or GPU coverage.
Use `--source-commit HASH` to record the producer revision when known; it is caller-supplied,
not inferred from the checkout analyzing the files. Bundles remain local and may contain game
shader data; review them before sharing.

```powershell
.\scripts\test.ps1 # cargo build --workspace + cargo test --workspace
```
Expand Down
100 changes: 95 additions & 5 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2104,6 +2104,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);
Expand Down Expand Up @@ -2255,6 +2298,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
Expand Down Expand Up @@ -2365,15 +2435,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(|| {
Expand Down
74 changes: 74 additions & 0 deletions scripts/analyze_shader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Prepare a verified, isolated shader bundle for optional vendor diagnostics."""

import argparse
import hashlib
import json
from pathlib import Path
import shutil
import sys
import tempfile

from verify_shader_dump import verify


def prepare(manifest, output, source_commit=None):
"""Copy first, then verify the exact bytes an analyzer will consume."""
output.mkdir(parents=True, exist_ok=True)
run = Path(tempfile.mkdtemp(prefix="shader-", dir=output)).resolve()
report = dict(schema_version=1, source_commit=source_commit,
manifest_path=str(manifest.resolve()), status="ERROR",
category="invalid_bundle", verification=None, analyzer=None)
try:
if not manifest.name.endswith(".manifest.json"):
raise ValueError("expected a .manifest.json file")
bundle = run / "input"
bundle.mkdir()
copied = bundle / manifest.name
shutil.copyfile(manifest, copied)
data = json.loads(copied.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("expected a manifest object")
prefix = manifest.name[:-len(".manifest.json")]
suffixes = [".guest.bin", ".direct.err.txt" if data.get("error") is not None else ".direct.dxil"]
for suffix in suffixes:
shutil.copyfile(manifest.with_name(prefix + suffix), bundle / (prefix + suffix))
report["verification"] = verify(copied)
report["manifest"] = data
# SHA-256 complements the manifest's FNV identity; neither authenticates its author.
report["artifacts"] = {}
for path in sorted(bundle.iterdir()):
with path.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
report["artifacts"][path.name] = dict(path=str(path), sha256=digest)
report.update(status="SKIPPED", category="analyzer_not_requested")
if data.get("error") is not None:
report["category"] = "translation_rejected"
except (OSError, ValueError, KeyError) as exc:
report["detail"] = str(exc)
return run, report


def save_report(run, report):
path = run / "report.json"
path.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return path


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("manifest", type=Path)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--source-commit", help="producer commit, supplied by the caller; not inferred from this checkout")
args = parser.parse_args(argv)
try:
run, report = prepare(args.manifest, args.out, args.source_commit)
path = save_report(run, report)
except OSError as exc:
print(str(exc), file=sys.stderr)
return 1
print(f"{report['status']}: {report['category']}; {path}")
return int(report["status"] == "ERROR")


if __name__ == "__main__":
sys.exit(main())
63 changes: 63 additions & 0 deletions scripts/test_analyze_shader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Synthetic artifact fixtures; these bytes are not executable DXIL."""
import hashlib
import json
from pathlib import Path
import tempfile
import unittest

from analyze_shader import prepare, save_report, main


class AnalysisTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.path = self.root / "sample.manifest.json"
self.data = dict(schema_version=1, backend="direct-dxil", stage="cs", wave64=False,
guest_fnv64="a430d84680aabd0b", dxil_fnv64="85944171f73967e8", error=None)
self.path.write_text(json.dumps(self.data), encoding="utf-8")
(self.root / "sample.guest.bin").write_bytes(b"hello")
(self.root / "sample.direct.dxil").write_bytes(b"foobar")
self.output = self.root / "reports"

def test_snapshot_and_hashes(self):
run, report = prepare(self.path, self.output, "a" * 40)
self.assertEqual(report["category"], "analyzer_not_requested")
self.assertEqual(report["source_commit"], "a" * 40)
artifact = report["artifacts"]["sample.direct.dxil"]
self.assertEqual(artifact["sha256"], hashlib.sha256(b"foobar").hexdigest())
(self.root / "sample.direct.dxil").write_bytes(b"changed")
self.assertEqual(Path(artifact["path"]).read_bytes(), b"foobar")
self.assertEqual(json.loads(save_report(run, report).read_text()), report)

def test_corruption_and_missing_artifact_fail(self):
artifact = self.root / "sample.direct.dxil"
artifact.write_bytes(b"corrupt")
self.assertEqual(prepare(self.path, self.output)[1]["status"], "ERROR")
artifact.unlink()
self.assertEqual(main([str(self.path), "--out", str(self.output)]), 1)

def test_rejected_translation_preserves_error(self):
self.data.update(dxil_fnv64=None, error="unsupported\n")
self.path.write_text(json.dumps(self.data), encoding="utf-8")
(self.root / "sample.direct.err.txt").write_bytes(b"unsupported\n")
run, report = prepare(self.path, self.output)
self.assertEqual(report["category"], "translation_rejected")
self.assertFalse((run / "input" / "sample.direct.dxil").exists())

def test_invalid_manifest_and_schema(self):
for value in ([], {}, dict(self.data, schema_version=True), dict(self.data, backend="other")):
with self.subTest(value=value):
self.path.write_text(json.dumps(value), encoding="utf-8")
self.assertEqual(prepare(self.path, self.output)[1]["status"], "ERROR")

def test_runs_never_reuse_outputs(self):
a, _ = prepare(self.path, self.output)
b, _ = prepare(self.path, self.output)
self.assertNotEqual(a, b)
self.assertEqual(main([str(self.path), "--out", str(self.output)]), 0)


if __name__ == "__main__":
unittest.main()
62 changes: 62 additions & 0 deletions scripts/test_verify_shader_dump.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading