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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,30 @@ 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.

Add `--rga C:\Tools\RGA\rga.exe --target gfx1101` for optional **AMD offline compute**
analysis (or `--rga` with `XCL_RGA` set). Install RGA separately from
[AMD](https://gpuopen.com/rga/); the script never downloads tools. The target is explicitly
selected, not detected from the host GPU. Only `CS` and `kernel` manifests are supported;
other stages, missing tools and tools without the required mode report `SKIPPED`.
Each invocation records its command, exit code, duration and raw output. Nonempty ISA output
is required for success, even if RGA exits zero. Statistics retain RGA's CSV column names
and units. Missing metrics remain absent. `--timeout 120` limits each tool invocation.
Offline compiler results (including autogenerated pipeline state) are not measurements of
the game's actual pipeline, GPU execution, occupancy or frame rate. NVIDIA integration,
host-adapter discovery and graphics-pipeline analysis are not implemented.

```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
85 changes: 85 additions & 0 deletions scripts/analyze_shader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""Prepare a verified, isolated shader bundle for optional vendor diagnostics."""

import argparse
import hashlib
import json
import math
import os
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")
parser.add_argument("--rga", nargs="?", const=os.environ.get("XCL_RGA", "rga.exe"),
help="opt in to AMD offline compute analysis; optional executable path (or XCL_RGA)")
parser.add_argument("--target", help="explicit AMD offline target, e.g. gfx1101; not a detected host adapter")
parser.add_argument("--timeout", type=float, default=120, help="seconds per analyzer invocation")
args = parser.parse_args(argv)
if not math.isfinite(args.timeout) or args.timeout <= 0:
parser.error("--timeout must be finite and positive")
try:
run, report = prepare(args.manifest, args.out, args.source_commit)
if args.rga is not None:
from shader_rga import analyze
analyze(run, report, args.rga, args.target, args.timeout)
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())
90 changes: 90 additions & 0 deletions scripts/shader_rga.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Opt-in RGA DX12 offline compute diagnostics, separate from XCL validation."""
import csv
import os
from pathlib import Path
import re
import shutil
import signal
import subprocess
import time


def execute(command, directory, label, timeout):
stdout, stderr = directory / f"{label}.stdout.txt", directory / f"{label}.stderr.txt"
result = dict(command=command, exit_code=None, timed_out=False,
stdout=str(stdout), stderr=str(stderr))
start = time.monotonic()
with stdout.open("wb") as out, stderr.open("wb") as err:
with subprocess.Popen(command, cwd=directory, stdout=out, stderr=err,
start_new_session=os.name != "nt") as process:
try:
result["exit_code"] = process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
result["timed_out"] = True
if os.name == "nt":
subprocess.run([str(Path(os.environ["SystemRoot"]) / "System32/taskkill.exe"),
"/PID", str(process.pid), "/T", "/F"],
stdout=err, stderr=err, timeout=15, check=False)
else:
os.killpg(process.pid, signal.SIGKILL)
if process.poll() is None:
process.kill()
result["exit_code"] = process.wait()
result["wall_seconds"] = time.monotonic() - start
return result


def analyze(run, report, tool, target, timeout=120):
if report["category"] != "analyzer_not_requested":
return
report["analyzer"] = dict(name="Radeon GPU Analyzer", mode="dx12-offline", target=target,
host_adapter=None, version=None, invocations=[], statistics=[])
info = report["analyzer"]
if report["manifest"].get("stage") not in ("CS", "kernel"):
report["category"] = "unsupported_stage"
return
if not target or not re.fullmatch(r"gfx[0-9a-f]+", target):
report.update(status="ERROR", category="invalid_target")
return
executable = shutil.which(tool) if tool else None
if not executable:
report["category"] = "tool_missing"
return
executable = str(Path(executable).resolve())
# Batch files invoke a shell on Windows; only a native executable is supported.
if os.name == "nt" and Path(executable).suffix.lower() != ".exe":
report.update(status="ERROR", category="invalid_tool")
return
directory = run / "rga"
directory.mkdir()
try:
for label, arguments in (("version", ["--version"]), ("help", ["-s", "dx12", "-h"])):
invocation = execute([executable, *arguments], directory, label, timeout)
info["invocations"].append(invocation)
if invocation["timed_out"] or invocation["exit_code"] != 0:
report.update(status="ERROR", category="tool_probe_failed")
return
info["version"] = (directory / "version.stdout.txt").read_text(encoding="utf-8", errors="replace").strip()
help_text = (directory / "help.stdout.txt").read_text(encoding="utf-8", errors="replace")
if not all(flag in help_text for flag in ("--offline", "--cs-blob")):
report["category"] = "unsupported_tool_mode"
return
dxil = next(v["path"] for k, v in report["artifacts"].items() if k.endswith(".direct.dxil"))
command = [executable, "-s", "dx12", "--offline", "-c", target, "--cs-blob", dxil,
"--isa", str(directory / "shader.isa"), "-a", str(directory / "stats.csv")]
invocation = execute(command, directory, "analysis", timeout)
info["invocations"].append(invocation)
outputs = [p for p in directory.glob("*.isa") if p.stat().st_size]
info["isa_files"] = [str(p) for p in outputs]
for path in sorted(directory.glob("*.csv")):
with path.open(encoding="utf-8-sig", newline="", errors="replace") as stream:
info["statistics"].append(dict(path=str(path), rows=list(csv.DictReader(stream))))
if invocation["timed_out"]:
report.update(status="ERROR", category="analyzer_timeout")
elif invocation["exit_code"] != 0 or not outputs:
# RGA versions can return zero even when pipeline creation fails.
report.update(status="ERROR", category="analyzer_failed")
else:
report.update(status="OK", category="analysis_complete")
except (OSError, ValueError, subprocess.SubprocessError) as exc:
report.update(status="ERROR", category="analyzer_failed", detail=str(exc))
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()
Loading
Loading