From 1740e093c90cab386e2f419bbc115ca94637b09f Mon Sep 17 00:00:00 2001 From: Rain156 <1954786975@qq.com> Date: Tue, 24 Nov 2026 14:25:53 +0800 Subject: [PATCH 1/2] shaders: index DXBC identities for Xbox native graphics pipelines Generate a deterministic hash-to-stage catalog alongside the translated shaders. Backfill an existing translation without disassembling it again, reject conflicting identities, and atomically replace a complete catalog. Adapted from the GPL native stage index by enx, with the Xbox layout measurements by LooperSalty and KkelebekK. Adapted-from: https://git.notrexed.dev/enx/leonida/commit/5c175db901f8486bcdefd03746b578b657e3151f --- docs/d3d12_vulkan.md | 7 ++ make_game.py | 25 ++++ tests/test_bvh_shaders_stage.py | 2 +- tests/test_fspx_shaders_stage.py | 4 +- tests/test_make_game_translator_flags.py | 2 + tests/test_native_pso_hashes.py | 140 +++++++++++++++++++++++ tests/test_shader_stage_resume.py | 4 + tools/native_pso_hashes.py | 115 +++++++++++++++++++ 8 files changed, 297 insertions(+), 2 deletions(-) create mode 100644 tests/test_native_pso_hashes.py create mode 100644 tools/native_pso_hashes.py diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..0aa2ed61bc 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2029,6 +2029,13 @@ without recorded inputs. In that case the runtime accepts any input layout when ### 3.6 Shader identity, PSOs and feature selection +The Xbox native graphics pipeline descriptor identifies stages by the digest in a DXBC HASH part (see +`docs/fspx.md`, kind 7). The shaders stage writes `/shaders/spirv/native_hashes.txt` from the user's +carved DXBC containers and translation index. After the version header, each line contains the 16-byte digest +in lowercase hex, the translated stage and a container path relative to the index, separated by tabs. +Containers sharing a digest must agree on stage and FSSM hash. A collision fails the stage and preserves the +previous catalog. Existing translated workspaces can build the catalog by rerunning the shaders stage. + A D3D12 PSO carries DXBC containers, not SPIR-V. The layer identifies a shader by hashing the **FSSM payload** (the native RDNA2 program inside the container) and looking it up in a build-time table keyed by `(stage, hash)`. The build emits that hash for every translation; the runtime extracts the FSSM chunk from the DXBC container the same diff --git a/make_game.py b/make_game.py index 83cc5fd367..8b614c2d7a 100644 --- a/make_game.py +++ b/make_game.py @@ -1341,12 +1341,37 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate f.write(sources + "\n") translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks) verify_translation_completeness(dxbc, spirv) + native_pso_hashes(dxbc, spirv) fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks) bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) log("shaders: done") +def native_pso_hashes(dxbc: str, spirv: str) -> None: + """Index the carved containers named by native graphics PSOs, including on a resumed translation.""" + import native_pso_hashes as tool + + index = os.path.join(spirv, "index.json") + if not os.path.isfile(index) or not os.path.isdir(dxbc): + return + output = os.path.join(spirv, tool.OUT_NAME) + if os.path.isfile(output): + stamp = os.stat(output).st_mtime_ns + inputs = (index, dxbc, os.path.join(dxbc, "index.json"), tool.__file__, + os.path.join(os.path.dirname(tool.__file__), "shader_carve.py")) + if all(not os.path.exists(p) or os.stat(p).st_mtime_ns <= stamp for p in inputs): + with os.scandir(dxbc) as files: + if all(not f.name.endswith(".dxbc") or f.stat().st_mtime_ns <= stamp for f in files): + return + try: + table = tool.build(dxbc, spirv) + tool.write(spirv, table) + except (OSError, ValueError) as error: + fail(f"shaders: could not index native graphics pipelines: {error}") + log(f"shaders: indexed {len(table)} native shader digests") + + FSPX_DLL = "amd_fidelityfx_upscaler_xbox.dll" FSPX_TOOLS = ("fspx_unpack.py", "shader_disasm.py") # with TRANSLATION_SOURCES, what the FSPX outputs come from diff --git a/tests/test_bvh_shaders_stage.py b/tests/test_bvh_shaders_stage.py index 60d16a138b..a732b1c993 100644 --- a/tests/test_bvh_shaders_stage.py +++ b/tests/test_bvh_shaders_stage.py @@ -386,7 +386,7 @@ def fake_py(tool_name, *args): def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): ran.append("translate") - write("", spirv, "index.json") + write('{"shader": {"stage": "vs"}}', spirv, "index.json") def stage(): ran.clear() diff --git a/tests/test_fspx_shaders_stage.py b/tests/test_fspx_shaders_stage.py index 3d2e94f037..288454a86e 100644 --- a/tests/test_fspx_shaders_stage.py +++ b/tests/test_fspx_shaders_stage.py @@ -382,7 +382,9 @@ def fake_py(tool, *args): def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): ran.append("translate") - touch(spirv, "index.json") + os.makedirs(spirv, exist_ok=True) + with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: + json.dump({"shader": {"stage": "vs"}}, f) def stage(): ran.clear() diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py index 04067440f1..c268a33e9a 100644 --- a/tests/test_make_game_translator_flags.py +++ b/tests/test_make_game_translator_flags.py @@ -133,6 +133,8 @@ def touch(self, *parts): json.dump([{"file": "shader.dxbc"}], f) elif p == os.path.join(self.dxbc, "fssm_index.json"): json.dump([{"name": "shader"}], f) + elif p == os.path.join(self.spirv, "index.json"): + json.dump({"shader": {"stage": "vs"}}, f) elif p.endswith(".s"): f.write("synthetic listing\n") diff --git a/tests/test_native_pso_hashes.py b/tests/test_native_pso_hashes.py new file mode 100644 index 0000000000..94a73697b6 --- /dev/null +++ b/tests/test_native_pso_hashes.py @@ -0,0 +1,140 @@ +"""tools/native_pso_hashes.py on hand-built DXBC containers and indexes: no game data.""" +import json +import os +import struct +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools")) +import native_pso_hashes as tool # noqa: E402 +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import make_game # noqa: E402 + + +def container(digest: bytes, other=b"") -> bytes: + """A DXBC container with a HASH part (flags 0, then the digest) and an optional second part.""" + parts = [b"HASH" + struct.pack("/native_hashes.txt: the HASH digest of each carved DXBC container -> its stage and path. + +Xbox device slot 57 creates the game's graphics pipelines from native code, and each stage's records name the +source container by the 16-byte digest of its HASH part (docs/fspx.md, kind 7). This catalog connects that +identifier to the original local container and the stage in the translation index. + +Usage: python -I tools/native_pso_hashes.py /shaders/dxbc /shaders/spirv + +Only containers in the translator's index are written. Entries sharing a digest must agree on stage and +fssm_sha256. Adapted from enx/leonida's native graphics PSO index (commit 5c175db90). +""" +import json +import os +import re +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from shader_carve import parts + +HEADER = "# native_pso_hashes 1" +OUT_NAME = "native_hashes.txt" + + +class DigestClash(ValueError): + """One digest names two different programs.""" + + +def hash_digest(data: bytes): + """The 16-byte digest of a DXBC container's HASH part (after its u32 flags), or None.""" + if data[:4] != b"DXBC": + return None + try: + chunk = parts(data).get("HASH") + except ValueError: + return None + if not chunk or chunk[1] < 20: + return None + offset, _ = chunk + return data[offset + 4:offset + 20] + + +def build(dxbc: str, spirv: str) -> dict: + """{digest hex: (stage, path relative to spirv)}. Raises DigestClash when one digest names two programs.""" + workspace = os.path.dirname(os.path.realpath(spirv)) + if os.path.commonpath((workspace, os.path.realpath(dxbc))) != workspace: + raise ValueError("the carved folder must be inside the same shader workspace as the translation") + with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: + index = json.load(f) + if not isinstance(index, dict): + raise ValueError("index.json is not an object") + found = {} + for name in sorted(os.listdir(dxbc)): + if not name.endswith(".dxbc"): + continue + stem = name[:-5] + entry = index.get(stem) + if not isinstance(entry, dict): + continue + with open(os.path.join(dxbc, name), "rb") as f: + digest = hash_digest(f.read()) + if digest is None: + continue + stage, fssm = entry.get("stage"), entry.get("fssm_sha256") + if (not isinstance(stage, str) or re.fullmatch(r"[a-z]+", stage) is None or + not isinstance(fssm, str) or re.fullmatch(r"[0-9a-f]{64}", fssm) is None): + raise ValueError(f"invalid translated stage or FSSM hash for {name!r}") + if any(c in stem for c in "\\:\t\r\n"): + raise ValueError(f"cannot represent this container name in the native catalog: {name!r}") + key = digest.hex() + path = os.path.relpath(os.path.join(dxbc, name), spirv).replace(os.sep, "/") + if key in found: + first = found[key] + if first[2] != fssm or first[0] != stage: + raise DigestClash(f"digest {key} names two programs: {first[3]} and {stem}") + continue + found[key] = (stage, path, fssm, stem) + return {k: (v[0], v[1]) for k, v in found.items()} + + +def write(spirv: str, table: dict) -> str: + out = os.path.join(spirv, OUT_NAME) + tmp = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=spirv, + prefix=".native_hashes.", suffix=".tmp", delete=False) + try: + with tmp: + tmp.write(HEADER + "\n") + for key in sorted(table): + stage, path = table[key] + tmp.write(f"{key}\t{stage}\t{path}\n") + os.replace(tmp.name, out) + finally: + if os.path.exists(tmp.name): + os.unlink(tmp.name) + return out + + +def main(argv) -> int: + if len(argv) != 3: + print(__doc__.strip().splitlines()[0], file=sys.stderr) + print("usage: native_pso_hashes.py ", file=sys.stderr) + return 2 + dxbc, spirv = argv[1], argv[2] + try: + table = build(dxbc, spirv) + out = write(spirv, table) + except (OSError, ValueError) as e: + print(f"native_pso_hashes: {e}", file=sys.stderr) + return 1 + print(f"native_pso_hashes: {len(table)} digests -> {out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) From 62a95883b608d510ae0967cd7ddf5c9938b333a9 Mon Sep 17 00:00:00 2001 From: Rain156 <1954786975@qq.com> Date: Tue, 24 Nov 2026 18:13:26 +0800 Subject: [PATCH 2/2] build: track native PSO catalog dependencies Track the catalog writer and its local imports in the shader-stage fingerprint and CMake fixture dependencies. Cover the same files in both Runtime event filters, including the optional native scanner reached by the carver. Check both import graphs and document the standalone catalog refresh for existing translations. On Windows x64, touching the writer rebuilt the three bindless fixtures once. All three passed spirv-val and both Vulkan bindless tests passed on an RTX 5070 Ti with driver 617.42. The semantic suite ran 6,108 tests with no failed files. The regenerated 25,321-row catalog matched the local reference byte for byte. AI-assisted: OpenAI Codex --- .github/workflows/runtime.yml | 6 ++++++ docs/d3d12_vulkan.md | 4 +++- make_game.py | 5 +++-- runtime/cmake/translator_deps.cmake | 9 ++++++--- tests/test_cmake_translator_deps.py | 14 ++++++++------ tests/test_shader_stage_resume.py | 4 ++-- 6 files changed, 28 insertions(+), 14 deletions(-) diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 004d5a6929..54fc8af94e 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -35,12 +35,15 @@ on: - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" + - "tools/native_pso_hashes.py" - "tools/rdna2_decode.py" - "tools/rdna2_isa_tables.py" - "tools/rdna2spirv.py" - "tools/replace_retry.py" - "tools/report_paths.py" - "tools/shader_carve.py" + - "tools/shader_carve_accel.py" + - "tools/shader_carve_native/**" - "tools/shader_disasm.py" - "tools/shader_ir.py" - "tools/shader_meta.py" @@ -77,12 +80,15 @@ on: - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" + - "tools/native_pso_hashes.py" - "tools/rdna2_decode.py" - "tools/rdna2_isa_tables.py" - "tools/rdna2spirv.py" - "tools/replace_retry.py" - "tools/report_paths.py" - "tools/shader_carve.py" + - "tools/shader_carve_accel.py" + - "tools/shader_carve_native/**" - "tools/shader_disasm.py" - "tools/shader_ir.py" - "tools/shader_meta.py" diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0aa2ed61bc..b176004c92 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2034,7 +2034,9 @@ The Xbox native graphics pipeline descriptor identifies stages by the digest in carved DXBC containers and translation index. After the version header, each line contains the 16-byte digest in lowercase hex, the translated stage and a container path relative to the index, separated by tabs. Containers sharing a digest must agree on stage and FSSM hash. A collision fails the stage and preserves the -previous catalog. Existing translated workspaces can build the catalog by rerunning the shaders stage. +previous catalog. Rerunning the shaders stage checks its source fingerprint, including the catalog writer. +To add or refresh just the catalog in an existing translation, run +`python -I tools/native_pso_hashes.py "/shaders/dxbc" "/shaders/spirv"`. A D3D12 PSO carries DXBC containers, not SPIR-V. The layer identifies a shader by hashing the **FSSM payload** (the native RDNA2 program inside the container) and looking it up in a build-time table keyed by `(stage, hash)`. The diff --git a/make_game.py b/make_game.py index e16355fb9a..df11b8c79b 100644 --- a/make_game.py +++ b/make_game.py @@ -1830,11 +1830,12 @@ def runtime_gpu_max_push_constants(): return int(v) if isinstance(v, int) and not isinstance(v, bool) and v > 0 else None -# Source and data files that produce the translated modules, metadata and partner stubs. +# Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog. TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", "wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py", - "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json") + "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json", + "native_pso_hashes.py", "shader_carve.py", "shader_carve_accel.py") def sources_digest(folder: str, names, lead: str = "") -> str: diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake index 3565fe1e25..42be0f0e2b 100644 --- a/runtime/cmake/translator_deps.cmake +++ b/runtime/cmake/translator_deps.cmake @@ -1,6 +1,6 @@ -# What the SPIR-V that test/shaders/build.py writes comes from, besides the .asm files: build.py and the modules it -# imports, the scripts it runs (tools/rdna2spirv.py, and tools/vk_subgroup_info.py, whose answer picks -# --bary-fallback), and every module rdna2spirv.py imports or file it reads (make_game.py's TRANSLATION_SOURCES). +# The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py +# and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in +# make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer. # Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py # rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). # tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. @@ -16,11 +16,14 @@ set(LEONIDA_TRANSLATOR_DEPS ${_leonida_repo}/tools/gfx10_formats.json ${_leonida_repo}/tools/lane_masks.py ${_leonida_repo}/tools/mc_command.py + ${_leonida_repo}/tools/native_pso_hashes.py ${_leonida_repo}/tools/rdna2_decode.py ${_leonida_repo}/tools/rdna2_isa_tables.py ${_leonida_repo}/tools/rdna2spirv.py ${_leonida_repo}/tools/replace_retry.py ${_leonida_repo}/tools/report_paths.py + ${_leonida_repo}/tools/shader_carve.py + ${_leonida_repo}/tools/shader_carve_accel.py ${_leonida_repo}/tools/shader_ir.py ${_leonida_repo}/tools/shader_meta.py ${_leonida_repo}/tools/shader_stage_manifest.py diff --git a/tests/test_cmake_translator_deps.py b/tests/test_cmake_translator_deps.py index 32ecb40b1f..e3af66bcc2 100644 --- a/tests/test_cmake_translator_deps.py +++ b/tests/test_cmake_translator_deps.py @@ -3,7 +3,8 @@ They used to list only build.py, compute_fixture.py, rdna2spirv.py and their .asm files, so an edit to a module the translator imports (tools/spirv_asm.py, spirv_asm_tables.py, shader_ir.py, ...) left the last build's SPIR-V in place (old #3752, BUILD-1064). The rules now depend on LEONIDA_TRANSLATOR_DEPS (runtime/cmake/translator_deps.cmake); this -checks that list against what build.py reaches. No compiler needed; the cmake -P case is skipped without cmake. +checks the imports of build.py and the native catalog writer. No compiler is needed. The cmake -P check runs when +cmake is on PATH. """ import ast import os @@ -33,11 +34,12 @@ def listed(): def reached(): - """build.py, the tools scripts it runs (named by a string literal) and every local module they import.""" + """build.py, the scripts it runs, the native shader catalog and their transitive local imports.""" tree = ast.parse(BUILD_PY.read_text(encoding="utf-8")) - todo = [BUILD_PY] + [TOOLS / n.value for n in ast.walk(tree) - if isinstance(n, ast.Constant) and isinstance(n.value, str) - and n.value.endswith(".py") and (TOOLS / n.value).is_file()] + todo = [BUILD_PY, TOOLS / "native_pso_hashes.py"] + todo.extend(TOOLS / n.value for n in ast.walk(tree) + if isinstance(n, ast.Constant) and isinstance(n.value, str) + and n.value.endswith(".py") and (TOOLS / n.value).is_file()) seen = set() while todo: path = todo.pop() @@ -60,7 +62,7 @@ def reached(): class TranslatorDepsTest(unittest.TestCase): - def test_the_list_covers_every_local_module_build_py_reaches(self): + def test_the_list_covers_build_py_and_native_catalog_imports(self): self.assertEqual({p for p in listed() if p.endswith(".py")}, reached()) def test_the_list_has_the_data_files_the_translator_reads(self): diff --git a/tests/test_shader_stage_resume.py b/tests/test_shader_stage_resume.py index 1f95be2367..106ca8ea21 100644 --- a/tests/test_shader_stage_resume.py +++ b/tests/test_shader_stage_resume.py @@ -532,8 +532,8 @@ def test_a_kill_right_after_a_merge_for_new_sources_keeps_the_translation(self): class TranslationSourcesTest(unittest.TestCase): - def test_the_list_covers_every_local_module_the_translator_imports(self): - seen, todo = set(), ["rdna2spirv"] + def test_the_list_covers_the_translator_and_native_catalog_imports(self): + seen, todo = set(), ["rdna2spirv", "native_pso_hashes"] while todo: name = todo.pop() if name in seen: