From 99743eeffb1d0cf152d06feaf20b4bddf9740ca8 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:39:41 +0530 Subject: [PATCH 1/5] =?UTF-8?q?=EF=BB=BFstartup-d3d12:=20load=20validated?= =?UTF-8?q?=20compute=20modules=20by=20key=20from=20the=20shader=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step (b) of the #1412 rework. Device slot 62 no longer inspects bytes: it hashes the container the same way the graphics path does (fnv_bytes over the CS bytecode) and looks for `.cs.cso` in X2W_SHADER_CACHE, which is where the offline retarget/sign/gate step publishes validated desktop modules. A hit builds a real CreateComputePipelineState from those bytes with the unwrapped root signature; a miss keeps the placeholder and logs "no validated module". Nothing else changes: the dispatch path is still inert (slot 14 not installed), so no behaviour moves until the two-arm readback proves it. Offline publication of `.cs.cso`, the compute root bindings and the readback fixture are the remaining steps. Builds clean; startup_stubs passes. --- src/startup_stubs/d3d12_xs_device.cpp | 50 +++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..58fba08f8c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -8215,9 +8215,10 @@ void dump_containers(const char* what, const void* desc, std::size_t bytes) HRESULT __stdcall placeholder_ok(Wrapper*, u64, u64, u64) { return S_OK; } // Device slot 62 (Xbox order): (D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, ppv); first seen from -// XboxBvhBuilder.dll, followed by SetName on the result. The bytecode is console GPU code, not DXIL, -// so no desktop pipeline is built: the result is a placeholder PipelineState until shader translation -// exists. Logs the root signature, bytecode address, length and first 32 bytes. +// XboxBvhBuilder.dll, followed by SetName on the result. With render mode a validated module published +// under the container's hash in the shader cache is loaded, so the result is a real desktop pipeline; +// without one it stays a placeholder PipelineState. Logs the root signature, bytecode address, length +// and first 32 bytes. HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0, u64 extra1, const GUID* iid, void** out) { @@ -8229,15 +8230,50 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO dump_containers("compute", desc, sizeof(*desc)); char bytes[3 * 32 + 1]; hex_text(desc->CS.pShaderBytecode, desc->CS.BytecodeLength < 32 ? desc->CS.BytecodeLength : 32, bytes, sizeof(bytes)); + // A validated compute module is loaded by key from the shader cache, exactly as graphics + // translations are: the offline retarget/sign/gate step decides usability, so there is no + // runtime byte inspection here, and the placeholder is kept when no validated module exists. + ID3D12PipelineState* real_pipeline = nullptr; + char why[128] = ""; + if (render_mode()) { + wchar_t path[MAX_PATH]; + const u64 compute_key = desc->CS.pShaderBytecode && desc->CS.BytecodeLength + ? fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength) : 0; + ID3DBlob* blob = nullptr; + if (!compute_key || !cache_path(path, L"", compute_key, L".cs.cso") || + FAILED(D3DReadFileToBlob(path, &blob)) || !blob) { + std::snprintf(why, sizeof(why), "no validated module"); + } else { + D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; + compute.pRootSignature = + reinterpret_cast(unwrap(reinterpret_cast(desc->pRootSignature))); + compute.CS.pShaderBytecode = blob->GetBufferPointer(); + compute.CS.BytecodeLength = blob->GetBufferSize(); + compute.NodeMask = desc->NodeMask; + compute.CachedPSO = desc->CachedPSO; + compute.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + const HRESULT built = device_of(self)->CreateComputePipelineState(&compute, IID_PPV_ARGS(&real_pipeline)); + blob->Release(); + if (FAILED(built)) { + real_pipeline = nullptr; + std::snprintf(why, sizeof(why), "CreateComputePipelineState 0x%08lx", static_cast(built)); + } + } + } static LONG calls; if (first_calls(calls, 24)) log("x2w-d3d12 Device::slot62(CreateComputePipelineState?) root=%p cs=%p len=0x%llx node=0x%x flags=0x%x extra=0x%llx,0x%llx " - "riid=%s -> placeholder [%s]", static_cast(desc->pRootSignature), desc->CS.pShaderBytecode, - static_cast(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, bytes); + "riid=%s -> %s%s [%s]", static_cast(desc->pRootSignature), desc->CS.pShaderBytecode, + static_cast(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, + real_pipeline ? "REAL desktop pipeline" : "placeholder: ", real_pipeline ? "" : why, bytes); if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; - *out = wrap(nullptr, pipeline_kind); - if (!*out) return E_OUTOFMEMORY; + *out = wrap(real_pipeline, pipeline_kind); + if (!*out) { + if (real_pipeline) real_pipeline->Release(); + return E_OUTOFMEMORY; + } auto* pipeline = static_cast(*out); + pipeline->own().compute_pipeline = real_pipeline != nullptr; note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); note_compute_builder_pipeline(self, pipeline, _ReturnAddress()); From 88de7a895a8ccf6a76a9c07d8662041f475d3558 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:43:43 +0530 Subject: [PATCH 2/5] =?UTF-8?q?=EF=BB=BFstartup-d3d12:=20publish=20compute?= =?UTF-8?q?=20modules=20under=20the=20key=20the=20runtime=20looks=20them?= =?UTF-8?q?=20up=20by?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step (a) of the #1412 rework: tools/startup/compute_cache.py turns the containers the stand-in dumps into the `.cs.cso` files that device slot 62 loads, and records `.fail` with the reason when the existing validated path refuses a module. The retarget/gate/validate/sign decision stays in tools/dxil_retarget.py - this tool only supplies the naming and the refusal record, so validation does not get re-implemented at the runtime. The key is FNV-1a 64 over the shader bytes rendered as 16 hex digits, matching the stand-in's fnv_bytes/cache_path (d3d12_draw.inl), and tests/startup_compute_cache_check.py (ctest startup_compute_cache) pins it in both directions plus the refusal behaviour. Note recorded in the test and worth a maintainer's look: the seed in fnv_bytes is 1469598103934665603, which is a digit short of the canonical FNV-1a 64 offset basis (14695981039346656037). The cache is keyed by whatever the runtime computes, so the publisher matches the runtime rather than the spec; if that constant was a typo it should be corrected deliberately, not as a side effect of this work. --- CMakeLists.txt | 4 ++ tests/startup_compute_cache_check.py | 75 ++++++++++++++++++++ tools/startup/compute_cache.py | 101 +++++++++++++++++++++++++++ 3 files changed, 180 insertions(+) create mode 100644 tests/startup_compute_cache_check.py create mode 100644 tools/startup/compute_cache.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a5b4d5e5d5..5f2b5f2584 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3766,6 +3766,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME runtime_startup_live_view_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_live_view_cli_check.py") set_tests_properties(runtime_startup_live_view_cli_check PROPERTIES TIMEOUT 60) + # The compute shader cache publisher (tools/startup/compute_cache.py) must derive the same key + # the stand-in computes for .cs.cso, or every compute lookup silently misses (#1412). + add_test(NAME startup_compute_cache COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_cache_check.py") add_test(NAME startup_uniform_lane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_uniform_lane_check.py") # NGG primitive-shader cases (#1723): identity triangle against single-change contrasts, reference model. diff --git a/tests/startup_compute_cache_check.py b/tests/startup_compute_cache_check.py new file mode 100644 index 0000000000..ea48c3920f --- /dev/null +++ b/tests/startup_compute_cache_check.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Control for the compute-cache publisher (tools/startup/compute_cache.py). + +Device slot 62 loads ``.cs.cso`` from ``X2W_SHADER_CACHE`` where the key is FNV-1a 64 over the +shader bytes, formatted as 16 lowercase hex digits (the graphics translation path in +``src/startup_stubs/d3d12_draw.inl`` uses the same helper and format). If this tool computed the key +differently, every lookup would miss and the pipeline would silently stay a placeholder, so the key is +pinned here against the published FNV-1a 64 vectors and against the C++ constant. + +The publisher must also record a refusal rather than publish an unusable module: a file that is not a +DXBC container gets ``.fail`` and no ``.cs.cso``. + +The runtime seed is deliberately pinned as it is written in ``d3d12_draw.inl``: 1469598103934665603. +That is *not* the canonical FNV-1a 64 offset basis (14695981039346656037) - it is a digit short. The +values below are therefore computed from the runtime's seed, because the cache is looked up by +whatever the runtime computes; changing the seed would silently invalidate every cached translation. +""" +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup")) +import compute_cache + +failures = [] + + +def check(label, condition): + print("%s: %s" % (label, "ok" if condition else "MISMATCH")) + if not condition: + failures.append(label) + + +def main(): + # Pinned to the runtime's seed as written, not to the FNV specification: the runtime computes these + # digits (d3d12_draw.inl fnv_bytes) and uses them as the cache file name. + check("runtime seed is the one the stand-in uses", compute_cache.BASIS == 1469598103934665603) + check("empty input hashes to the runtime seed", compute_cache.key_of(b"") == 0x14650FB0739D0383) + check("'a' hashes as the runtime would", compute_cache.key_text(b"a") == "44bd8ad473cd9906") + check("'abc' hashes as the runtime would", compute_cache.key_text(b"abc") == "e16801510db89efd") + check("key text is 16 lowercase hex digits", len(compute_cache.key_text(b"abc")) == 16) + + with TemporaryDirectory() as directory: + root = Path(directory) + pending, cache = root / "pending", root / "cache" + pending.mkdir() + cache.mkdir() + (pending / "deadbeef.dxbc").write_bytes(b"not a container at all") + + original = compute_cache.publish_one + # The refusal path must not need the retarget tool at all. + line = compute_cache.publish_one(pending / "deadbeef.dxbc", cache, None, Path("unused.py")) + check("a non-container is refused", "refused" in line and "not a DXBC container" in line) + key = compute_cache.key_text((pending / "deadbeef.dxbc").read_bytes()) + check("a refusal is recorded under the same key", (cache / (key + ".fail")).is_file()) + check("a refusal publishes no module", not (cache / (key + ".cs.cso")).exists()) + + # With no containers at all the tool reports that rather than failing. + empty = subprocess.run([sys.executable, "-B", str(Path(compute_cache.__file__)), + "--pending", str(pending), "--cache", str(cache), + "--retarget", str(Path(compute_cache.__file__))], + capture_output=True, text=True) + check("the tool runs and reports what it did", empty.returncode == 0 or "refused" in empty.stdout) + compute_cache.publish_one = original + + if failures: + print("FAIL: %d case(s)" % len(failures)) + return 1 + print("PASS") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/tools/startup/compute_cache.py b/tools/startup/compute_cache.py new file mode 100644 index 0000000000..2f4c72d6dd --- /dev/null +++ b/tools/startup/compute_cache.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Publish validated desktop compute modules under the key the runtime looks them up by. + +Device slot 62 in the D3D12 stand-in does not inspect bytecode: it hashes the container the way the +graphics translation path does (FNV-1a 64 over the shader bytes, formatted ``%016llx``) and loads +``.cs.cso`` from ``X2W_SHADER_CACHE``. This tool produces those files. + +The decision about whether a module may run on the desktop is *not* made here: it is made by the +existing validated path in ``tools/dxil_retarget.py`` (retarget the target triple, gate ``xbox.*`` +symbols, validate container and module, re-sign). This tool only supplies the naming and the +refusal record, so the runtime never has to re-implement validation. + +usage: compute_cache.py --pending --cache --probe + [--retarget ] + +``--pending`` is the directory the stand-in dumps containers into (``X2W_SHADER_DUMP_DIR``); each +``*.dxbc`` file is content-addressed by the container checksum and is exactly the byte string the +runtime hashes, so the key can be recomputed here. +""" +import argparse +import subprocess +import sys +from pathlib import Path + +BASIS = 1469598103934665603 +PRIME = 1099511628211 + + +def key_of(data: bytes) -> int: + """The runtime's FNV-1a 64: instantiate with BASIS, multiply by PRIME after every xor.""" + value = BASIS + for byte in data: + value = ((value ^ byte) * PRIME) & 0xFFFFFFFFFFFFFFFF + return value + + +def key_text(data: bytes) -> str: + return "%016x" % key_of(data) + + +def publish_one(container: Path, cache: Path, probe: Path | None, retarget: Path) -> str: + """Write .cs.cso for one container, or .fail with the reason. Returns a status line.""" + raw = container.read_bytes() + key = key_text(raw) + if len(raw) < 32 or raw[:4] != b"DXBC": + (cache / (key + ".fail")).write_text("not a DXBC container\n", encoding="utf-8") + return "%s: refused (not a DXBC container)" % container.name + + command = [sys.executable, "-B", str(retarget), str(container), str(cache / (key + ".cs.cso"))] + if probe is not None: + command += ["--probe", str(probe), "--sign"] + result = subprocess.run(command, capture_output=True, text=True) + destination = cache / (key + ".cs.cso") + if result.returncode != 0 or not destination.exists(): + reason = (result.stderr or result.stdout or "retarget failed").strip().splitlines() + (cache / (key + ".fail")).write_text("\n".join(reason[-4:]) + "\n", encoding="utf-8") + return "%s: refused (%s)" % (container.name, reason[-1] if reason else "retarget failed") + + if destination.read_bytes()[:4] != b"DXBC": + destination.unlink() + (cache / (key + ".fail")).write_text("retargeted output is not a DXBC container\n", encoding="utf-8") + return "%s: refused (retargeted output is not a DXBC container)" % container.name + return "%s: published %s.cs.cso" % (container.name, key) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--pending", required=True, type=Path, + help="Directory the stand-in dumps containers into (X2W_SHADER_DUMP_DIR)") + parser.add_argument("--cache", required=True, type=Path, + help="Shader cache directory the runtime reads (X2W_SHADER_CACHE)") + parser.add_argument("--probe", type=Path, help="root_probe executable, used to validate and sign") + parser.add_argument("--retarget", type=Path, + default=Path(__file__).resolve().parents[1] / "dxil_retarget.py", + help="dxil_retarget.py (default: the one beside this tool's parent)") + args = parser.parse_args() + + if not args.pending.is_dir(): + parser.error("--pending is not a directory: %s" % args.pending) + args.cache.mkdir(parents=True, exist_ok=True) + if not args.retarget.is_file(): + parser.error("--retarget is not a file: %s" % args.retarget) + + containers = sorted(args.pending.glob("*.dxbc")) + if not containers: + print("no containers in %s" % args.pending) + return 0 + published = refused = 0 + for container in containers: + line = publish_one(container, args.cache, args.probe, args.retarget) + print(line) + if ".cs.cso" in line: + published += 1 + else: + refused += 1 + print("published %d, refused %d" % (published, refused)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file From 194a6ee1486373f6b5babd08f4ce4fbd4321ca87 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:53:03 +0530 Subject: [PATCH 3/5] =?UTF-8?q?=EF=BB=BFstartup-d3d12:=20do=20not=20forwar?= =?UTF-8?q?d=20a=20console=20cached-PSO=20blob=20to=20the=20desktop=20runt?= =?UTF-8?q?ime?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tedin7's review finding 3 on #1441: the compute pipeline description copied desc->CachedPSO straight through, which hands a console cached blob to desktop CreateComputePipelineState. Zero it instead; a cached PSO is an optimisation the desktop must not be asked to interpret. Findings 1 and 2 were about the byte-scan classifier, which is withdrawn; finding 4 (no end-to-end coverage of the CreateComputePipelineState path) is still true and is the next step. Builds clean; startup_compute_cache and startup_stubs pass. --- src/startup_stubs/d3d12_xs_device.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 58fba08f8c..7adb03ac24 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -8250,7 +8250,7 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO compute.CS.pShaderBytecode = blob->GetBufferPointer(); compute.CS.BytecodeLength = blob->GetBufferSize(); compute.NodeMask = desc->NodeMask; - compute.CachedPSO = desc->CachedPSO; + compute.CachedPSO = {}; // A console cached-PSO blob must not reach the desktop runtime. compute.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; const HRESULT built = device_of(self)->CreateComputePipelineState(&compute, IID_PPV_ARGS(&real_pipeline)); blob->Release(); From 4fa06fcdb3d7f61026382e9c09f0a144927d78d0 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:12:52 +0530 Subject: [PATCH 4/5] =?UTF-8?q?=EF=BB=BFstartup-d3d12:=20add=20the=20compu?= =?UTF-8?q?te=20dispatch=20path=20behind=20an=20explicit=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step (d), first half: gate the compute-dispatch experiment behind X2W_COMPUTE_DISPATCH=1. Rebased onto a main whose command-list slot 14 Dispatch already exists (#1974): main installs slot 14 unconditionally and forwards only when a desktop compute pipeline and root signature are bound and the root arguments are forwarded (`decide_dispatch` in `src/startup_stubs/list_dispatch.h`, covered by startup_list_dispatch and startup_list_dispatch_native). That newer code fully supersedes this PR's own slot 14 handler, so the handler and its gated `list_typed[14]` registration are dropped rather than duplicated. The gate covers the slot 62 side instead, which is what this PR adds: with X2W_COMPUTE_DISPATCH=1 a validated `.cs.cso` is loaded and the desktop pipeline records `own().pipeline_root`, so main's existing gate can match it against the bound compute root signature. Without the variable nothing is loaded, so production behaviour is unchanged and nothing can dispatch on the placeholder path. Still outstanding, and why this is not marked ready: the source-built two-arm readback (invalid artifact -> zero recorded dispatches, accepted artifact -> nonzero UAV readback). The gate exists so that fixture can turn the path on explicitly; until it passes, the default is inert. --- src/startup_stubs/d3d12_xs_device.cpp | 33 ++++++++++++++++++++------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 7adb03ac24..264e1c3b32 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4024,6 +4024,17 @@ void restore_compute_root(const Pass& pass, ID3D12GraphicsCommandList* list) } } +// X2W_COMPUTE_DISPATCH=1 turns on the compute-dispatch experiment: device slot 62 loads a validated +// .cs.cso and builds a real desktop compute pipeline, and command-list slot 14 Dispatch (installed +// unconditionally by main) forwards it. Without the variable no module is loaded, so the default +// placeholder path is exactly as inert as before and the source-built readback fixture is what turns +// this on explicitly. +bool compute_dispatch_enabled() +{ + char value[8]; + const DWORD n = GetEnvironmentVariableA("X2W_COMPUTE_DISPATCH", value, sizeof(value)); + return n == 1 && value[0] == '1'; +} void __stdcall list_compute_root(Wrapper* self, void* root) { auto* list = recording(self); @@ -8215,10 +8226,10 @@ void dump_containers(const char* what, const void* desc, std::size_t bytes) HRESULT __stdcall placeholder_ok(Wrapper*, u64, u64, u64) { return S_OK; } // Device slot 62 (Xbox order): (D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, ppv); first seen from -// XboxBvhBuilder.dll, followed by SetName on the result. With render mode a validated module published -// under the container's hash in the shader cache is loaded, so the result is a real desktop pipeline; -// without one it stays a placeholder PipelineState. Logs the root signature, bytecode address, length -// and first 32 bytes. +// XboxBvhBuilder.dll, followed by SetName on the result. With X2W_COMPUTE_DISPATCH=1 and render mode a +// validated module published under the container's hash in the shader cache is loaded, so the result is a +// real desktop pipeline; without one it stays a placeholder PipelineState. Logs the root signature, +// bytecode address, length and first 32 bytes. HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0, u64 extra1, const GUID* iid, void** out) { @@ -8230,12 +8241,16 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO dump_containers("compute", desc, sizeof(*desc)); char bytes[3 * 32 + 1]; hex_text(desc->CS.pShaderBytecode, desc->CS.BytecodeLength < 32 ? desc->CS.BytecodeLength : 32, bytes, sizeof(bytes)); - // A validated compute module is loaded by key from the shader cache, exactly as graphics - // translations are: the offline retarget/sign/gate step decides usability, so there is no - // runtime byte inspection here, and the placeholder is kept when no validated module exists. + // With X2W_COMPUTE_DISPATCH=1 a validated compute module is loaded by key from the shader cache, + // exactly as graphics translations are: the offline retarget/sign/gate step decides usability, so + // there is no runtime byte inspection here, and the placeholder is kept when no validated module + // exists. ID3D12PipelineState* real_pipeline = nullptr; + ID3D12RootSignature* pipeline_root = nullptr; // the root the desktop module was built against char why[128] = ""; - if (render_mode()) { + if (!compute_dispatch_enabled()) { + std::snprintf(why, sizeof(why), "compute dispatch is off"); + } else if (render_mode()) { wchar_t path[MAX_PATH]; const u64 compute_key = desc->CS.pShaderBytecode && desc->CS.BytecodeLength ? fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength) : 0; @@ -8247,6 +8262,7 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; compute.pRootSignature = reinterpret_cast(unwrap(reinterpret_cast(desc->pRootSignature))); + pipeline_root = compute.pRootSignature; compute.CS.pShaderBytecode = blob->GetBufferPointer(); compute.CS.BytecodeLength = blob->GetBufferSize(); compute.NodeMask = desc->NodeMask; @@ -8274,6 +8290,7 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO } auto* pipeline = static_cast(*out); pipeline->own().compute_pipeline = real_pipeline != nullptr; + pipeline->own().pipeline_root = real_pipeline ? pipeline_root : nullptr; note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); note_compute_builder_pipeline(self, pipeline, _ReturnAddress()); From a0fd8d2e72c4f2f567e12989b546f95afe55eac2 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:30:52 +0100 Subject: [PATCH 5/5] startup: validate cached slot 62 compute artifacts --- src/startup_stubs/d3d12_xs_device.cpp | 31 +++++----- tests/cmake/startup_slot62_cache.cmake | 15 +++++ tests/startup_list_dispatch_native.cpp | 81 +++++++++++++++++++++++++- tests/startup_slot62_cache.hlsl | 7 +++ tests/startup_slot62_cache_check.py | 29 +++++++++ 5 files changed, 146 insertions(+), 17 deletions(-) create mode 100644 tests/cmake/startup_slot62_cache.cmake create mode 100644 tests/startup_slot62_cache.hlsl create mode 100644 tests/startup_slot62_cache_check.py diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 264e1c3b32..eb114895ff 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -8237,14 +8237,12 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO guid_text(iid, text, sizeof(text)); if (!out || !desc || !iid) return E_POINTER; *out = nullptr; + if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; dump_pipeline("compute", 62, desc, sizeof(*desc)); dump_containers("compute", desc, sizeof(*desc)); char bytes[3 * 32 + 1]; hex_text(desc->CS.pShaderBytecode, desc->CS.BytecodeLength < 32 ? desc->CS.BytecodeLength : 32, bytes, sizeof(bytes)); - // With X2W_COMPUTE_DISPATCH=1 a validated compute module is loaded by key from the shader cache, - // exactly as graphics translations are: the offline retarget/sign/gate step decides usability, so - // there is no runtime byte inspection here, and the placeholder is kept when no validated module - // exists. + // Validate the cached compute container before handing it to the desktop device. ID3D12PipelineState* real_pipeline = nullptr; ID3D12RootSignature* pipeline_root = nullptr; // the root the desktop module was built against char why[128] = ""; @@ -8252,27 +8250,33 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO std::snprintf(why, sizeof(why), "compute dispatch is off"); } else if (render_mode()) { wchar_t path[MAX_PATH]; - const u64 compute_key = desc->CS.pShaderBytecode && desc->CS.BytecodeLength + const u64 compute_key = desc->CS.BytecodeLength && x2w_local::readable(desc->CS.pShaderBytecode, desc->CS.BytecodeLength) ? fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength) : 0; - ID3DBlob* blob = nullptr; + x2w_startup::ComPtr blob; if (!compute_key || !cache_path(path, L"", compute_key, L".cs.cso") || - FAILED(D3DReadFileToBlob(path, &blob)) || !blob) { + FAILED(D3DReadFileToBlob(path, blob.GetAddressOf())) || !blob) { std::snprintf(why, sizeof(why), "no validated module"); } else { D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; compute.pRootSignature = reinterpret_cast(unwrap(reinterpret_cast(desc->pRootSignature))); - pipeline_root = compute.pRootSignature; compute.CS.pShaderBytecode = blob->GetBufferPointer(); compute.CS.BytecodeLength = blob->GetBufferSize(); compute.NodeMask = desc->NodeMask; compute.CachedPSO = {}; // A console cached-PSO blob must not reach the desktop runtime. compute.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; - const HRESULT built = device_of(self)->CreateComputePipelineState(&compute, IID_PPV_ARGS(&real_pipeline)); - blob->Release(); - if (FAILED(built)) { - real_pipeline = nullptr; - std::snprintf(why, sizeof(why), "CreateComputePipelineState 0x%08lx", static_cast(built)); + if (const char* reason = desktop_compute_program_reason(compute.CS)) { + std::snprintf(why, sizeof(why), "cached module rejected: %s", reason); + } else if (!compute.pRootSignature) { + std::snprintf(why, sizeof(why), "root signature has no desktop object"); + } else { + const HRESULT built = device_of(self)->CreateComputePipelineState(&compute, IID_PPV_ARGS(&real_pipeline)); + if (FAILED(built)) { + real_pipeline = nullptr; + std::snprintf(why, sizeof(why), "CreateComputePipelineState 0x%08lx", static_cast(built)); + } else { + pipeline_root = compute.pRootSignature; + } } } } @@ -8282,7 +8286,6 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_CO "riid=%s -> %s%s [%s]", static_cast(desc->pRootSignature), desc->CS.pShaderBytecode, static_cast(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, real_pipeline ? "REAL desktop pipeline" : "placeholder: ", real_pipeline ? "" : why, bytes); - if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; *out = wrap(real_pipeline, pipeline_kind); if (!*out) { if (real_pipeline) real_pipeline->Release(); diff --git a/tests/cmake/startup_slot62_cache.cmake b/tests/cmake/startup_slot62_cache.cmake new file mode 100644 index 0000000000..4522063486 --- /dev/null +++ b/tests/cmake/startup_slot62_cache.cmake @@ -0,0 +1,15 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_list_dispatch_native) + set(slot62_shader "${CMAKE_CURRENT_BINARY_DIR}/startup_slot62_cache.cso") + add_custom_command(OUTPUT "${slot62_shader}" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E main -Fo "${slot62_shader}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot62_cache.hlsl" + DEPENDS tests/startup_slot62_cache.hlsl VERBATIM) + add_custom_target(startup_slot62_cache_shader DEPENDS "${slot62_shader}") + add_dependencies(startup_list_dispatch_native startup_slot62_cache_shader) + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_slot62_cache_${backend} + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot62_cache_check.py" + "$" "${slot62_shader}" ${backend}) + set_tests_properties(startup_slot62_cache_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_list_dispatch_native.cpp b/tests/startup_list_dispatch_native.cpp index 25586fde22..2e786120bf 100644 --- a/tests/startup_list_dispatch_native.cpp +++ b/tests/startup_list_dispatch_native.cpp @@ -186,6 +186,73 @@ class Fixture { native_ = native_object(device, guest, list_.Get()); } + bool run_cached(bool accepted) + { + D3D12_ROOT_PARAMETER uav{}; + uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + const auto signature = guest_root(guest_, {1, &uav}, "create cached compute root"); + constexpr char input[] = "slot62 fixture"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = signature.Get(); + desc.CS = {input, sizeof(input) - 1}; + using Create = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT, + const void*, REFIID, void**); + ComPtr pipeline; + check(slot(guest_, 62)(guest_, &desc, 0, nullptr, IID_PPV_ARGS(&pipeline)), "create slot 62 PSO"); + reset(); + if (!accepted) { + std::ifstream log(log_path, std::ios::binary); + bool rejected_before_creation = false; + for (std::string line; std::getline(log, line);) { + if (line.find("cached module rejected: the console compute container is malformed") != std::string::npos) + rejected_before_creation = true; + } + if (!rejected_before_creation) { + std::fprintf(stderr, "expected slot 62 to reject the malformed cache before desktop creation\n"); + return false; + } + if (!expect({"invalid cached module", 1, 1, 1, "requires a desktop compute pipeline and root", 0}, + [&] { bind(pipeline.Get(), signature.Get()); })) return false; + resolve(1); + check(slot(list_.Get(), 9)(list_.Get()), "close refused recording"); + return execute(0, 1); + } + + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = sizeof(UINT); + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr output; + check(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&output)), "create output UAV"); + const auto desktop_pipeline = native_object(device_, guest_, pipeline.Get()); + bind(pipeline.Get(), signature.Get()); + // The base shim's direct Dispatch accepts SRV-only roots. Exercise the slot 62 PSO on its desktop list. + native_->SetPipelineState(desktop_pipeline.Get()); + native_->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress()); + native_->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {output.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; + native_->ResourceBarrier(1, &barrier); + native_->CopyBufferRegion(readback_.Get(), 0, output.Get(), 0, sizeof(UINT)); + check(slot(list_.Get(), 9)(list_.Get()), "close cached PSO recording"); + submit(); + void* mapped = nullptr; + const D3D12_RANGE read{0, sizeof(UINT)}, untouched{0, 0}; + check(readback_->Map(0, &read, &mapped), "map cached PSO readback"); + UINT value = 0; + std::memcpy(&value, mapped, sizeof(value)); + readback_->Unmap(0, &untouched); + std::printf("slot 62 cached PSO readback: %u (expected 73)\n", value); + return value == 73; + } + bool run() { // Recording 1: the fully bound call alone, executed and counted before any refused case runs. @@ -306,13 +373,18 @@ class Fixture { native_->ResolveQueryData(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, count, readback_.Get(), 0); } - bool execute(UINT first, UINT count) + void submit() { ID3D12CommandList* lists[]{native_.Get()}; queue_->ExecuteCommandLists(1, lists); check(queue_->Signal(fence_.Get(), ++fence_value_), "signal completion fence"); check(fence_->SetEventOnCompletion(fence_value_, nullptr), "wait for completion"); check(device_->GetDeviceRemovedReason(), "GPU completion"); + } + + bool execute(UINT first, UINT count) + { + submit(); void* mapped = nullptr; const D3D12_RANGE read{0, count * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS)}; check(readback_->Map(0, &read, &mapped), "map query readback"); @@ -367,7 +439,10 @@ int main(int argc, char** argv) try const bool warp = argc >= 2 && std::strcmp(argv[1], "warp") == 0; if (!warp && (argc < 2 || std::strcmp(argv[1], "hardware") != 0)) return 2; const bool skip_srv = argc == 3 && std::strcmp(argv[2], "skip-srv") == 0; - if (argc > 3 || (argc == 3 && !skip_srv)) return 2; + const bool cached = argc == 3 && std::strcmp(argv[2], "cached") == 0; + const bool rejected = argc == 3 && std::strcmp(argv[2], "rejected-cache") == 0; + if (argc > 3 || (argc == 3 && !skip_srv && !cached && !rejected)) return 2; + if (cached || rejected) SetEnvironmentVariableA("X2W_COMPUTE_DISPATCH", "1"); ComPtr debug; const HRESULT debug_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug)); if (debug_hr != DXGI_ERROR_SDK_COMPONENT_MISSING) check(debug_hr, "get debug layer"); @@ -416,7 +491,7 @@ int main(int argc, char** argv) try bool ok = false; { Fixture fixture(device.Get(), guest.Get(), skip_srv); - ok = fixture.run(); + ok = cached || rejected ? fixture.run_cached(cached) : fixture.run(); } if (info) { for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { diff --git a/tests/startup_slot62_cache.hlsl b/tests/startup_slot62_cache.hlsl new file mode 100644 index 0000000000..948b87600b --- /dev/null +++ b/tests/startup_slot62_cache.hlsl @@ -0,0 +1,7 @@ +RWByteAddressBuffer output : register(u0); + +[numthreads(1, 1, 1)] +void main() +{ + output.Store(0, 73); +} diff --git a/tests/startup_slot62_cache_check.py b/tests/startup_slot62_cache_check.py new file mode 100644 index 0000000000..499386dfd4 --- /dev/null +++ b/tests/startup_slot62_cache_check.py @@ -0,0 +1,29 @@ +"""Publish a source-built compute shader and a structurally malformed copy.""" + +import os +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + + +def main(consumer, shader, backend): + key = 1469598103934665603 + for byte in b"slot62 fixture": + key = ((key ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF + code = Path(shader).read_bytes() + assert code[:4] == b"DXBC" + + with TemporaryDirectory() as directory: + cache = Path(directory) / f"{key:016x}.cs.cso" + env = dict(os.environ, X2W_SHADER_CACHE=directory, X2W_COMPUTE_BUILDER_GATE="0") + for mode, artifact in (("rejected-cache", code + b"\0"), ("cached", code)): + cache.write_bytes(artifact) + result = subprocess.run([consumer, backend, mode], env=env, timeout=30) + if result.returncode: + return result.returncode + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:]))