diff --git a/docs/shader_library.md b/docs/shader_library.md index 3ef944a528..8a971203f7 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -152,8 +152,11 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv * It writes `fspx/.code` and `fspx/.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state - blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; every compute program has exactly one - (2,684 programs, 2,693 records). It also writes `index.json` with each program's stage, and + blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, + every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, + 2,693 records). A program that records use with different state blobs is written once per distinct state, the + first under its name and each further one as `_state_`, so each pair of keys has an entry + (the library measured above has no such program). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -162,6 +165,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv interface. * `--save` writes the reassembled library. A saved file is also accepted as input. * `--stages` limits the output to some stages. +* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed + in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error. The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest diff --git a/tests/test_shader_library.py b/tests/test_shader_library.py index 8410be28a8..db5fa57f7a 100644 --- a/tests/test_shader_library.py +++ b/tests/test_shader_library.py @@ -388,6 +388,129 @@ def test_compute_missing_state_removes_stale_state_and_skips_none_blob(self): self.assertIn("fspx_code_sha256", meta) self.assertNotIn("fspx_state_sha256", meta) + def two_state_library(self): + """Program 0 with three state blobs, two of them the same bytes, and once without a state; program 1 with one + of those blobs; program 2 in a graphics pipeline. Returns (library, the two distinct states, program 0).""" + first, second = kind0(), kind0(threads=(32, 1, 1)) + code = prog(3) + compute = [(0, NONE, 0, NONE), (1, NONE, 0, NONE), (2, NONE, 0, NONE), (NONE, NONE, 0, NONE), + (1, NONE, 1, NONE)] + lib = build([(NONE, NONE, {0: (2, 3)})], compute, [first, second, first, layout_blob(2, D_PS)], + [code, prog(4), prog(5)]) + return lib, (first, second), code + + # The entries of that library's compute programs: program 0, its second state (blob 1) and program 1. + TWO_STATE_NAMES = [sl.program_name(0, {"cs"}), sl.program_name(0, {"cs"}) + "_state_1", sl.program_name(1, {"cs"})] + + def test_program_with_two_states_gets_an_entry_for_each(self): + lib, (first, second), code = self.two_state_library() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + out = os.path.join(tmp, "out") + # A further state is an output like any other: --save must not name it. + names = self.TWO_STATE_NAMES + self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".state"), "--stages", "cs") + self.assertFalse(os.path.exists(out)) + rc, text = self.run_main(src, "--out", out, "--stages", "cs") + self.assertEqual(rc, 0) + self.assertIn("3 written", text) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + index = json.load(f) + self.assertEqual([(e["file"], e["program"], e["threads"]) for e in index], + [(names[0] + ".dxbc", 0, [8, 8, 1]), (names[1] + ".dxbc", 0, [32, 1, 1]), + (names[2] + ".dxbc", 1, [32, 1, 1])]) + self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))), + sorted(n + ext for n in names for ext in (".code", ".json", ".state"))) + for name, state in zip(names, (first, second, second)): + with open(os.path.join(out, "fspx", name + ".state"), "rb") as f: + self.assertEqual(f.read(), state) + for name in names[:2]: + with open(os.path.join(out, "fspx", name + ".code"), "rb") as f: + self.assertEqual(f.read(), code) + # Both entries of program 0 have its code key, and each its own state key. + metas = [shader_meta.collect(os.path.join(out, "disasm", n + ".s"), n, [[]], [[]]) for n in names[:2]] + self.assertEqual({m["fspx_code_sha256"] for m in metas}, {hashlib.sha256(code).hexdigest()}) + self.assertEqual([m["fspx_state_sha256"] for m in metas], + [hashlib.sha256(first).hexdigest(), hashlib.sha256(second).hexdigest()]) + # Every record names the entry with its state; the one without a state names the program. + with open(os.path.join(out, "library.json"), encoding="utf-8") as f: + self.assertEqual([c["program"] for c in json.load(f)["compute"]], + [names[0], names[1], names[0], names[0], names[2]]) + + def test_compute_hashes_select_programs_by_their_code(self): + lib, (first, second), code = self.two_state_library() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + hashes = os.path.join(tmp, "hashes.txt") + with open(hashes, "w", encoding="utf-8", newline="\n") as f: + f.write("\n " + hashlib.sha256(code).hexdigest().upper() + "\n\n") + out = os.path.join(tmp, "out") + names = self.TWO_STATE_NAMES[:2] + self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".code"), + "--compute-hashes", hashes) + self.assertFalse(os.path.exists(out)) + rc, text = self.run_main(src, "--out", out, "--compute-hashes", hashes) + self.assertEqual(rc, 0) + self.assertIn("2 written", text) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + self.assertEqual([e["file"] for e in json.load(f)], [n + ".dxbc" for n in names]) + self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))), + sorted(n + ext for n in names for ext in (".code", ".json", ".state"))) + for name, state in zip(names, (first, second)): + with open(os.path.join(out, "fspx", name + ".state"), "rb") as f: + self.assertEqual(f.read(), state) + # The tables are the library's, whatever was selected. + with open(os.path.join(out, "library.json"), encoding="utf-8") as f: + summary = json.load(f) + self.assertEqual([c["program"] for c in summary["compute"]], + [names[0], names[1], names[0], names[0], self.TWO_STATE_NAMES[2]]) + self.assertEqual(summary["graphics"][0]["stages"], {"ps": sl.program_name(2, {"ps"})}) + + def test_compute_hashes_are_checked_before_anything_is_written(self): + lib, _, code = self.two_state_library() + digest = hashlib.sha256(code).hexdigest() + pixel = hashlib.sha256(sl.program(lib, sl.parse(lib), 2)).hexdigest() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + out = os.path.join(tmp, "out") + listed = os.path.join(tmp, "hashes.txt") + + def usage_error(text, *args): + with open(listed, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as caught: + self.run_main(src, *args) + self.assertEqual(caught.exception.code, 2) + return err.getvalue() + + self.assertIn("not allowed with", usage_error(digest, "--out", out, "--stages", "cs", + "--compute-hashes", listed)) + self.assertIn("--compute-hashes needs --out", usage_error(digest, "--save", os.path.join(tmp, "l.bin"), + "--compute-hashes", listed)) + for text in ("", "\n", digest[:-1], digest + " not-a-digest", "0x" + digest): + with self.subTest(text=text): + self.assertIn("cannot read --compute-hashes", usage_error(text, "--out", out, + "--compute-hashes", listed)) + self.assertIn("cannot read --compute-hashes", + usage_error(digest, "--out", out, "--compute-hashes", os.path.join(tmp, "missing.txt"))) + # A digest no compute program has, here an unknown one and a pixel program's. + for text in (digest + "\n" + "0" * 64, pixel): + with self.subTest(text=text): + with open(listed, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + with self.assertRaises(sl.LibraryError) as caught: + self.run_main(src, "--out", out, "--compute-hashes", listed) + self.assertIn("match no compute program", str(caught.exception)) + self.assertFalse(os.path.exists(out)) + self.assertFalse(os.path.exists(os.path.join(tmp, "l.bin"))) + def test_same_code_with_distinct_states_gets_distinct_state_keys(self): code = prog(0x44556677) s_a, s_b = kind0(threads=(32, 1, 1)), kind0(threads=(64, 1, 1)) diff --git a/tools/shader_library.py b/tools/shader_library.py index a74a820bb7..b1f928292d 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -270,7 +270,10 @@ def compute_variants(b: bytes, lib: dict, names: dict): i, state_id = rec["program"], rec["state"] if i is None: continue - state = blob(b, lib, state_id) if state_id is not None else None + if state_id is None: + by_record[i, None] = names[i] + continue + state = blob(b, lib, state_id) states = variants.setdefault(i, {}) if state not in states: states[state] = names[i] if not states else f"{names[i]}_state_{state_id}" @@ -301,7 +304,7 @@ def main(argv=None) -> int: if not a.out and not a.save: ap.error("give --out, --save or both") hashes = None - if a.compute_hashes: + if a.compute_hashes is not None: if not a.out: ap.error("--compute-hashes needs --out") try: @@ -310,7 +313,7 @@ def main(argv=None) -> int: except (OSError, UnicodeError) as error: ap.error(f"cannot read --compute-hashes: {error}") if not hashes or any(not re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes): - ap.error("--compute-hashes needs at least one SHA-256 digest") + ap.error("cannot read --compute-hashes: expected one or more SHA-256 digests of 64 hex digits") with open(a.src, "rb") as f: head = f.read(4) f.seek(0) @@ -346,7 +349,8 @@ def main(argv=None) -> int: selected = [i for i in selected if matching[i] in hashes] missing = hashes - {matching[i] for i in selected} if missing: - raise LibraryError(f"{len(missing)} requested compute code hashes not found in the pipeline library") + raise LibraryError(f"{len(missing)} of the {len(hashes)} --compute-hashes digests match no compute " + f"program of the library, first {min(missing)}") carve_errors = [] sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None