From 2057645f6bb60475c467df612a3af175d57f2557 Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:23:49 +0100 Subject: [PATCH] launcher: reuse one bounded verified DXIL snapshot --- project_tuxbox/dxil_store.py | 32 +++++++++++-------- project_tuxbox/runtime_shaders.py | 33 ++----------------- project_tuxbox/shader_blob.py | 39 +++++++++++++++++++++++ tests/test_dxil_store.py | 51 ++++++++++++++++++++++++++++++ tests/test_runtime_shader_links.py | 2 +- 5 files changed, 112 insertions(+), 45 deletions(-) create mode 100644 project_tuxbox/shader_blob.py diff --git a/project_tuxbox/dxil_store.py b/project_tuxbox/dxil_store.py index 46bb7f9c..1ff2bed7 100644 --- a/project_tuxbox/dxil_store.py +++ b/project_tuxbox/dxil_store.py @@ -10,11 +10,11 @@ import os from pathlib import Path import re -import shutil from tempfile import mkstemp from .inspect import digest from .shader_prep import has_dxil_container +from .shader_blob import MAX_SHADER_BYTES, bounded_shader, exact_marker, bounded_regular # Bump when a policy change can make cached DXIL unacceptable under validation. @@ -64,38 +64,42 @@ def __init__(self, root): def for_cache(cls, cache): """The store behind `cache`, or None when reuse is not enabled for it.""" try: - identity = (cache / IDENTITY_FILE).read_text(encoding="ascii") + identity = bounded_regular(cache / IDENTITY_FILE, 64).decode("ascii") if not re.fullmatch(r"[a-f0-9]{64}", identity): return None # /runtime/ -> /dxil/ root = cache.parent.parent / "dxil" / identity root.mkdir(parents=True, exist_ok=True) - except (OSError, UnicodeError): + except (OSError, UnicodeError, ValueError): return None return cls(root) @staticmethod def key(hlsl, target): tag = f"{target} {VARIANTS[target]}" if target in VARIANTS else target - return hashlib.sha256(f"{tag}\n".encode("ascii") + hlsl).hexdigest() + digest = hashlib.sha256(f"{tag}\n".encode("ascii")) + digest.update(hlsl) + return digest.hexdigest() def fetch(self, key, output): - """Copy the stored DXIL to `output` if its bytes still match their stamp.""" + """Return and stage one bounded, verified snapshot of stored DXIL.""" try: - expected = (self.root / f"{key}.sha256").read_text(encoding="ascii") - shutil.copyfile(self.root / f"{key}.cso", output) - if digest(output) == expected and has_dxil_container(output.read_bytes()): + data = bounded_shader(self.root / f"{key}.cso") + checksum = hashlib.sha256(data).hexdigest().encode("ascii") + if exact_marker(self.root / f"{key}.sha256", checksum) and has_dxil_container(data): + output.write_bytes(data) reused["dxil"] += 1 - return True - except (OSError, UnicodeError): + return data + except (OSError, ValueError): pass output.unlink(missing_ok=True) - return False + return None - def save(self, key, output): - """Keep validated DXIL. A failure only costs a later recompile.""" + def save(self, key, data): + """Keep already-validated DXIL bytes. Failure only costs a later compile.""" + if len(data) > MAX_SHADER_BYTES: + return try: - data = output.read_bytes() _publish(self.root / f"{key}.cso", data) _publish(self.root / f"{key}.sha256", hashlib.sha256(data).hexdigest().encode("ascii")) except OSError: diff --git a/project_tuxbox/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index a6a6f710..8351a51b 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -18,10 +18,10 @@ from .inspect import digest from .persistent_dxc import PersistentDxc from .shader_diagnostics import refusal_line +from .shader_blob import MAX_SHADER_BYTES, bounded_shader, exact_marker from .shader_prep import SOURCE_CACHE, ToolFailure, compiler_tools, run_tool -MAX_SHADER_BYTES = 64 << 20 XSHADER_UNSUPPORTED_HLSL = 65 # The emitter's one-line refusal reason kept beside an .unsupported marker. REASON_BYTES = 512 @@ -46,21 +46,6 @@ def reason_known(self): return not self.cached or self.remembered -def bounded_shader(path): - """Snapshot a regular file without following links or blocking on FIFOs.""" - flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) - with os.fdopen(os.open(path, flags), "rb") as stream: - info = os.fstat(stream.fileno()) - if not stat.S_ISREG(info.st_mode): - raise ValueError(f"{path.name} is not a regular shader file") - if info.st_size > MAX_SHADER_BYTES: - raise ValueError("shader exceeds the 64 MiB runtime limit") - data = stream.read(MAX_SHADER_BYTES + 1) - if len(data) > MAX_SHADER_BYTES: - raise ValueError("shader exceeds the 64 MiB runtime limit") - return data - - def verified_input(path, expected): data = bounded_shader(path) if hashlib.sha256(data).hexdigest() != expected: @@ -116,18 +101,6 @@ def portable_stage(data): return container_stage(data, portable=True) -def exact_marker(path, expected): - """Read a tiny regular marker, without following links or blocking.""" - flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) - try: - with os.fdopen(os.open(path, flags), "rb") as stream: - info = os.fstat(stream.fileno()) - return (stat.S_ISREG(info.st_mode) and info.st_size == len(expected) - and stream.read(len(expected) + 1) == expected) - except OSError: - return False - - def remembered_reason(path): """The refusal reason saved with a marker, or None for caches that predate it.""" flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) @@ -394,7 +367,7 @@ def reuse(): # compiler policy changes deliberately leave warm cache entries valid. store = DxilStore.for_cache(cache) content = store.key(hlsl.read_bytes(), target) if store else None - data = bounded_shader(output) if store and store.fetch(content, output) else None + data = store.fetch(content, output) if store else None if data is None or portable_stage(data) != target_stage: output.unlink(missing_ok=True) data = None @@ -409,7 +382,7 @@ def reuse(): if data is None: data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage) if store: - store.save(content, output) + store.save(content, data) stamp = work / "sha256" stamp.write_text(hashlib.sha256(data).hexdigest()) if session is not None: diff --git a/project_tuxbox/shader_blob.py b/project_tuxbox/shader_blob.py new file mode 100644 index 00000000..57ef6ae8 --- /dev/null +++ b/project_tuxbox/shader_blob.py @@ -0,0 +1,39 @@ +"""Bounded snapshots of local shader cache files.""" +import os +import stat + + +MAX_SHADER_BYTES = 64 << 20 + + +def bounded_regular(path, limit): + """Snapshot a regular file, without following links or blocking on FIFOs.""" + flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) + with os.fdopen(os.open(path, flags), "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode): + raise ValueError(f"{path.name} is not a regular shader file") + if info.st_size > limit: + raise ValueError("shader exceeds the 64 MiB runtime limit" if limit == MAX_SHADER_BYTES + else "file exceeds the cache snapshot limit") + data = stream.read(info.st_size + 1) + if len(data) != info.st_size: + raise ValueError("file size changed during cache snapshot") + return data + + +def bounded_shader(path): + """Snapshot a regular shader under the provider's 64 MiB limit.""" + return bounded_regular(path, MAX_SHADER_BYTES) + + +def exact_marker(path, expected): + """Read a tiny regular marker, without following links or blocking.""" + flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + with os.fdopen(os.open(path, flags), "rb") as stream: + info = os.fstat(stream.fileno()) + return (stat.S_ISREG(info.st_mode) and info.st_size == len(expected) + and stream.read(len(expected) + 1) == expected) + except OSError: + return False diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index 44f9ff17..a33ea3c5 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -1,4 +1,5 @@ import hashlib +import os from pathlib import Path import struct import subprocess @@ -97,6 +98,56 @@ def test_damaged_entry_is_recompiled(self): self.compile(self.cache("c")) self.assertEqual(len(self.calls), 2, "the recompile replaced the damaged entry") + def test_fetch_returns_the_verified_snapshot(self): + cache = self.cache("a") + data = self.compile(cache) + store = DxilStore.for_cache(cache) + key = store.key(self.hlsl.encode(), self.profile) + output = self.root / "output.cso" + self.assertEqual(store.fetch(key, output), data) + self.assertEqual(output.read_bytes(), data) + + def test_fetch_rejects_oversized_entries_before_copy(self): + store = DxilStore.for_cache(self.cache("a")) + key = "a" * 64 + output = self.root / "output.cso" + with (store.root / f"{key}.cso").open("wb") as stream: + stream.truncate((64 << 20) + 1) + (store.root / f"{key}.sha256").write_text("0" * 64) + self.assertIsNone(store.fetch(key, output)) + self.assertFalse(output.exists()) + + def test_fetch_rejects_linked_payloads_and_markers(self): + store = DxilStore.for_cache(self.cache("a")) + key = "a" * 64 + output = self.root / "output.cso" + data = container(b"void") + payload = self.root / "payload" + marker = self.root / "marker" + payload.write_bytes(data) + marker.write_text(hashlib.sha256(data).hexdigest()) + (store.root / f"{key}.cso").symlink_to(payload) + (store.root / f"{key}.sha256").write_bytes(marker.read_bytes()) + self.assertIsNone(store.fetch(key, output)) + (store.root / f"{key}.cso").unlink() + (store.root / f"{key}.cso").write_bytes(data) + (store.root / f"{key}.sha256").unlink() + (store.root / f"{key}.sha256").symlink_to(marker) + self.assertIsNone(store.fetch(key, output)) + self.assertFalse(output.exists()) + + def test_fifo_payload_and_identity_are_rejected_without_blocking(self): + cache = self.cache("a") + store = DxilStore.for_cache(cache) + key = "a" * 64 + output = self.root / "output.cso" + os.mkfifo(store.root / f"{key}.cso") + (store.root / f"{key}.sha256").write_text("0" * 64) + self.assertIsNone(store.fetch(key, output)) + (cache / "dxil-identity").unlink() + os.mkfifo(cache / "dxil-identity") + self.assertIsNone(DxilStore.for_cache(cache)) + def test_timed_out_request_goes_straight_to_o0_afterwards(self): self.timeouts = 1 self.compile(self.cache("a")) diff --git a/tests/test_runtime_shader_links.py b/tests/test_runtime_shader_links.py index b72041ef..6825b252 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -365,7 +365,7 @@ def test_large_pixel_candidate_precedes_slow_marker_and_validates_once(self): dxil = portable_program(0, b"pixel") store = Mock() store.key.return_value = "content" - store.fetch.return_value = False + store.fetch.return_value = None store.is_slow.return_value = True def run(args, *, timeout):