Skip to content
Draft
10 changes: 10 additions & 0 deletions docs/ENVIRONMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,13 @@ All are off by default. Capture variables write the game's data to disk, so don'
## Build and test tools

`TUXBOX_XSHADER` selects the shader compiler for launcher preparation and `DXC` selects the DirectX Shader Compiler. `TUXBOX_BLESS_PROFILES`, `TUXBOX_ORACLE_*`, `TUXBOX_TEST_*` and the probe and replay variables in `tools/` belong to individual checks. `TUXBOX_PROVIDER`, `TUXBOX_SHADER_SESSION` and `TUXBOX_WINE_*` are internal; don't set them.


Cold shader requests that translate to identical HLSL and the same target
profile share a single DXC compilation across launcher processes using the
same toolchain cache. Exact source cache hits still bypass compilation and
locking. Different HLSL or target profiles compile independently. A failed
compile does not publish an unsupported marker for another source; the next
request can retry. Content locks are retained as empty files to avoid races
with other processes. The wait is bounded by the maximum compiler fallback
budget plus validation and scheduling margin.
50 changes: 34 additions & 16 deletions project_tuxbox/dxil_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -64,38 +64,56 @@ 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
# <cache root>/runtime/<translator fingerprint> -> <cache root>/dxil/<toolchain>
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):
def _key_hasher(target):
tag = f"{target} {VARIANTS[target]}" if target in VARIANTS else target
return hashlib.sha256(f"{tag}\n".encode("ascii") + hlsl).hexdigest()
return hashlib.sha256(f"{tag}\n".encode("ascii"))

def fetch(self, key, output):
"""Copy the stored DXIL to `output` if its bytes still match their stamp."""
@staticmethod
def key(hlsl, target):
digest = DxilStore._key_hasher(target)
digest.update(hlsl)
return digest.hexdigest()

@staticmethod
def key_file(hlsl, target):
"""Hash private generated HLSL with bounded memory and unchanged keys."""
digest = DxilStore._key_hasher(target)
with hlsl.open("rb") as stream:
for chunk in iter(lambda: stream.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()

def fetch(self, key, output, *, accept=None):
"""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)
and (accept is None or accept(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:
Expand Down
76 changes: 32 additions & 44 deletions project_tuxbox/runtime_shaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -393,23 +366,38 @@ def reuse():
# validated equivalent output, including the candidate and -O0 paths;
# 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
if data is None or portable_stage(data) != target_stage:
content = store.key_file(hlsl, target) if store else None
def reuse_content():
data = store.fetch(content, output, accept=lambda blob: portable_stage(blob) == target_stage) if store else None
if data is not None and portable_stage(data) == target_stage:
return data
output.unlink(missing_ok=True)
data = None
if (persistent is not None and target == "cs_6_0"
and not (store and store.is_slow(key, target))
and persistent.compile(dxc, hlsl, output)):
try:
data = validated_dxil(dxv, output, target_stage)
except (OSError, ValueError, subprocess.SubprocessError) as error:
persistent.report(f"Persistent DXC output rejected, using the CLI: {error}")
output.unlink(missing_ok=True)
if data is None:
data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage)
if store:
store.save(content, output)
return None

data = reuse_content()
if data is None:
# The exact-source lock above cannot deduplicate different
# requests (or translator builds) that emit identical HLSL.
# Acquire the shared toolchain/content lock only after a miss.
# Always acquire source before content; never the reverse.
# Allow time for the optimised attempt, fallback and validation.
lock = (compile_lock(store.root, content, timeout=O0_TIMEOUT_MAX + COMPUTE_TIMEOUT + 60)
if store else nullcontext())
with lock:
data = reuse_content() if store else None
if data is None:
if (persistent is not None and target == "cs_6_0"
and not (store and store.is_slow(key, target))
and persistent.compile(dxc, hlsl, output)):
try:
data = validated_dxil(dxv, output, target_stage)
except (OSError, ValueError, subprocess.SubprocessError) as error:
persistent.report(f"Persistent DXC output rejected, using the CLI: {error}")
output.unlink(missing_ok=True)
if data is None:
data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage)
if store:
store.save(content, data)
stamp = work / "sha256"
stamp.write_text(hashlib.sha256(data).hexdigest())
if session is not None:
Expand Down
39 changes: 39 additions & 0 deletions project_tuxbox/shader_blob.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading