mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 12:38:38 +00:00
Keep stale shader files out of resumed builds
Select each stage's inputs from its producer index and refresh downstream stages when a saved cache contains obsolete shader names.
This commit is contained in:
31
make_game.py
31
make_game.py
@ -45,6 +45,7 @@ ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
TOOLS = os.path.join(ROOT, "tools")
|
||||
sys.path.insert(0, TOOLS)
|
||||
from mc_command import mc_command # noqa: E402
|
||||
from shader_stage_manifest import shader_stems # noqa: E402
|
||||
|
||||
VERSIONS = os.path.join(ROOT, "game")
|
||||
STAGES = ["check", "shaders", "assets", "runtime", "pipelines"]
|
||||
@ -638,9 +639,28 @@ def llvm_mc_signature() -> str:
|
||||
return json.dumps([command, version])
|
||||
|
||||
|
||||
def unpacked_shader_stems(dxbc: str) -> set[str] | None:
|
||||
"""Return current unpacked names, allowing the unpacker to skip non-FSSM containers."""
|
||||
try:
|
||||
carved = shader_stems(os.path.join(dxbc, "index.json"), "file", ".dxbc")
|
||||
unpacked = shader_stems(os.path.join(dxbc, "fssm_index.json"), "name")
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return unpacked if unpacked and unpacked <= carved else None
|
||||
|
||||
|
||||
def disassembly_matches(dxbc: str, signature: str) -> bool:
|
||||
return (os.path.isdir(os.path.join(dxbc, "disasm"))
|
||||
and read_shader_setting(os.path.join(dxbc, "disasm.done")) == signature)
|
||||
if read_shader_setting(os.path.join(dxbc, "disasm.done")) != signature:
|
||||
return False
|
||||
names = unpacked_shader_stems(dxbc)
|
||||
if names is None:
|
||||
return False
|
||||
try:
|
||||
with os.scandir(os.path.join(dxbc, "disasm")) as entries:
|
||||
return all(entry.name[:-2] in names for entry in entries
|
||||
if entry.name.endswith(".s") and entry.is_file())
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def shader_outputs_reusable(work: str, emulate: bool, keep_emulated: bool,
|
||||
@ -691,10 +711,10 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
|
||||
log("shaders: carving shaders.rpf")
|
||||
drop(translated, shard_plan, disassembled, unpacked)
|
||||
py("shader_carve.py", src, dxbc)
|
||||
if not os.path.isfile(unpacked):
|
||||
if unpacked_shader_stems(dxbc) is None:
|
||||
log("shaders: unpacking native code")
|
||||
drop(translated, shard_plan, disassembled)
|
||||
py("fssm_unpack.py", dxbc)
|
||||
py("fssm_unpack.py", dxbc, "--carve-index", carved)
|
||||
# rdna2spirv.py finds index.json, the .dxbc files and fssm/ in the parent of the .s files' folder, so the
|
||||
# disassembly must sit inside the carve folder: next to it, every stage reads as "?" and is rejected.
|
||||
disasm = os.path.join(dxbc, "disasm")
|
||||
@ -704,7 +724,8 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
|
||||
log("shaders: disassembling (gfx1013)")
|
||||
drop(translated, shard_plan, disassembled)
|
||||
clear_shader_disassembly(work, disasm)
|
||||
py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs)
|
||||
py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--unpack-index", unpacked,
|
||||
"--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs)
|
||||
with open(disassembled, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(signature + "\n")
|
||||
# The translation also depends on the translator's own files, so their digest is kept beside it. A folder without
|
||||
|
||||
@ -463,6 +463,20 @@ class TestMainDirectoryProcessing(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_carve_index_selects_current_containers(self):
|
||||
shader = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(make_fssm())}))])
|
||||
for name in ("current", "obsolete"):
|
||||
with open(os.path.join(self.src, name + ".dxbc"), "wb") as f:
|
||||
f.write(shader)
|
||||
index = os.path.join(self.src, "index.json")
|
||||
with open(index, "w", encoding="utf-8") as f:
|
||||
json.dump([{"file": "current.dxbc"}], f)
|
||||
result = subprocess.run([sys.executable, "-I", TOOL, self.src, "--carve-index", index],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(os.listdir(os.path.join(self.src, "fssm")), ["current.fssm"])
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.src, "obsolete.dxbc")))
|
||||
|
||||
def test_main_rejects_invalid_fssm_magic(self):
|
||||
bad_payload = b"JUNK\x01\x01" + bytes(58)
|
||||
bad_dxbc = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(bad_payload)}))])
|
||||
|
||||
@ -386,9 +386,9 @@ class StageResumptionAndStepIsolationTest(unittest.TestCase):
|
||||
os.makedirs(spirv_dir, exist_ok=True)
|
||||
|
||||
with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8") as f:
|
||||
f.write("{}")
|
||||
f.write('[{"file": "shader.dxbc"}]')
|
||||
with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8") as f:
|
||||
f.write("{}")
|
||||
f.write('[{"name": "shader"}]')
|
||||
with open(os.path.join(dxbc_dir, "disasm.done"), "w", encoding="utf-8") as f:
|
||||
f.write("test llvm-mc 21\n")
|
||||
with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f:
|
||||
@ -425,10 +425,10 @@ class StageResumptionAndStepIsolationTest(unittest.TestCase):
|
||||
fake_py_calls.append(tool)
|
||||
if tool == "shader_carve.py":
|
||||
with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8") as f:
|
||||
f.write("{}")
|
||||
f.write('[{"file": "shader.dxbc"}]')
|
||||
elif tool == "fssm_unpack.py":
|
||||
with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8") as f:
|
||||
f.write("{}")
|
||||
f.write('[{"name": "shader"}]')
|
||||
|
||||
with mock.patch("make_game.py", side_effect=fake_py), \
|
||||
mock.patch("make_game.llvm_mc_signature", return_value="test llvm-mc 21"), \
|
||||
|
||||
@ -487,8 +487,8 @@ class PreflightPrerequisiteTest(PreflightTestBase):
|
||||
for name, changed, settings, legacy_layout, reusable in cases:
|
||||
with self.subTest(name=name), tempfile.TemporaryDirectory() as work:
|
||||
files = {
|
||||
"dxbc/index.json": "{}",
|
||||
"dxbc/fssm_index.json": "{}",
|
||||
"dxbc/index.json": '[{"file": "shader.dxbc"}]',
|
||||
"dxbc/fssm_index.json": '[{"name": "shader"}]',
|
||||
"dxbc/disasm.done": "test llvm-mc 21",
|
||||
"spirv/index.json": "{}",
|
||||
"spirv/translation_sources.sha256": fingerprint,
|
||||
|
||||
@ -123,9 +123,10 @@ class EarlierStepDropsThePlanTest(unittest.TestCase):
|
||||
spirv = os.path.join(work, "shaders", "spirv")
|
||||
os.makedirs(dxbc)
|
||||
os.makedirs(spirv)
|
||||
for name in ("index.json", "fssm_index.json"): # carve and unpack finished
|
||||
for name, entries in (("index.json", [{"file": "shader.dxbc"}]),
|
||||
("fssm_index.json", [{"name": "shader"}])):
|
||||
with open(os.path.join(dxbc, name), "w", encoding="utf-8") as f:
|
||||
f.write("{}")
|
||||
json.dump(entries, f)
|
||||
plan = os.path.join(spirv, make_game.SHARD_PLAN)
|
||||
with open(plan, "w", encoding="utf-8") as f:
|
||||
json.dump({"jobs": 2, "wave64_emulate": False, "translator": "d1"}, f)
|
||||
|
||||
@ -101,7 +101,11 @@ class RecordedFlagsTest(unittest.TestCase):
|
||||
def touch(self, *parts):
|
||||
p = os.path.join(*parts)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
open(p, "w").close()
|
||||
with open(p, "w", encoding="utf-8") as f:
|
||||
if p == os.path.join(self.dxbc, "index.json"):
|
||||
json.dump([{"file": "shader.dxbc"}], f)
|
||||
elif p == os.path.join(self.dxbc, "fssm_index.json"):
|
||||
json.dump([{"name": "shader"}], f)
|
||||
|
||||
def run_stage(self, fallbacks=()):
|
||||
ran = []
|
||||
|
||||
@ -6,6 +6,7 @@ shader was reported "clean" (and make_game.py translated nothing). The probe now
|
||||
|
||||
python -I tests/test_shader_disasm.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@ -184,6 +185,18 @@ class DisasmInputTest(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(os.listdir(out), ["b_shader.s"])
|
||||
|
||||
def test_unpack_index_selects_current_blobs(self):
|
||||
self.write("current.fssm", fssm())
|
||||
self.write("obsolete.fssm", fssm())
|
||||
index = os.path.join(self.dir, "fssm_index.json")
|
||||
with open(index, "w", encoding="utf-8") as f:
|
||||
json.dump([{"name": "current"}], f)
|
||||
out = os.path.join(self.dir, "out")
|
||||
result = self.run_tool(self.src, "--out", out, "--unpack-index", index)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(os.listdir(out), ["current.s"])
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.src, "obsolete.fssm")))
|
||||
|
||||
def test_jobs_and_limit_must_be_at_least_one(self):
|
||||
self.write("one.fssm", fssm())
|
||||
out = os.path.join(self.dir, "out")
|
||||
|
||||
@ -88,15 +88,21 @@ class ShaderStageResumeTest(unittest.TestCase):
|
||||
def touch(self, *parts):
|
||||
p = os.path.join(*parts)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
open(p, "w").close()
|
||||
with open(p, "w", encoding="utf-8") as f:
|
||||
if p == os.path.join(self.dxbc, "index.json"):
|
||||
json.dump([{"file": "s0.dxbc"}], f)
|
||||
elif p == os.path.join(self.dxbc, "fssm_index.json"):
|
||||
json.dump([{"name": "s0"}], f)
|
||||
|
||||
def fake_py(self, tool, *args):
|
||||
self.ran.append(tool)
|
||||
if tool == "shader_carve.py":
|
||||
self.touch(self.dxbc, "index.json")
|
||||
elif tool == "fssm_unpack.py":
|
||||
self.assertEqual(args[-2:], ("--carve-index", os.path.join(self.dxbc, "index.json")))
|
||||
self.touch(self.dxbc, "fssm_index.json")
|
||||
elif tool == "shader_disasm.py":
|
||||
self.assertEqual(args[1:3], ("--unpack-index", os.path.join(self.dxbc, "fssm_index.json")))
|
||||
os.makedirs(os.path.join(self.dxbc, "disasm"), exist_ok=True)
|
||||
|
||||
def fake_translate(self, disasm, spirv, jobs, emulate=False, fallbacks=()):
|
||||
@ -198,6 +204,22 @@ class ShaderStageResumeTest(unittest.TestCase):
|
||||
os.remove(os.path.join(self.dxbc, "fssm_index.json"))
|
||||
self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"])
|
||||
|
||||
def test_old_unpack_index_with_a_noncurrent_shader_is_refreshed(self):
|
||||
self.run_stage()
|
||||
with open(os.path.join(self.dxbc, "fssm_index.json"), "w", encoding="utf-8") as f:
|
||||
json.dump([{"name": "s0"}, {"name": "removed"}], f)
|
||||
self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False))
|
||||
self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"])
|
||||
self.assertEqual(self.run_stage(), [])
|
||||
|
||||
def test_old_disassembly_with_a_noncurrent_shader_is_refreshed(self):
|
||||
self.run_stage()
|
||||
self.touch(self.dxbc, "disasm", "removed.s")
|
||||
self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False))
|
||||
self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"])
|
||||
self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm", "removed.s")))
|
||||
self.assertEqual(self.run_stage(), [])
|
||||
|
||||
def test_legacy_folder_without_llvm_version_refreshes_disassembly_once(self):
|
||||
self.touch(self.dxbc, "index.json")
|
||||
self.touch(self.dxbc, "fssm_index.json")
|
||||
|
||||
@ -21,7 +21,7 @@ The FSSM blob is the precompiled RDNA2 program plus its metadata. It contains th
|
||||
the code.
|
||||
|
||||
Usage:
|
||||
python -I fssm_unpack.py <carved_shader_dir> [--payload first|last]
|
||||
python -I fssm_unpack.py <carved_shader_dir> [--carve-index FILE] [--payload first|last]
|
||||
(writes <dir>/fssm/<name>.fssm and fssm_index.json)
|
||||
"""
|
||||
import argparse
|
||||
@ -32,6 +32,9 @@ import sys
|
||||
import zlib
|
||||
from collections import Counter
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from shader_stage_manifest import shader_stems # noqa: E402
|
||||
|
||||
# Defensive per-blob ceiling, not a maximum defined by the XBCH format.
|
||||
# 64 MiB matches the repository's existing per-resource cap in tools/world_index.py.
|
||||
MAX_FSSM_BYTES = 64 << 20
|
||||
@ -107,6 +110,7 @@ def unpack(dxbc: bytes, payload: str = "last"):
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.")
|
||||
ap.add_argument("src", help="carved shader directory")
|
||||
ap.add_argument("--carve-index", help="unpack only the DXBC files listed in this carve index")
|
||||
ap.add_argument("--payload", choices=("first", "last"), default="last",
|
||||
help="tag-0x0D payload when a container has more than one (default: last)")
|
||||
a = ap.parse_args(argv)
|
||||
@ -117,18 +121,24 @@ def main(argv=None) -> int:
|
||||
print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
with os.scandir(src) as entries:
|
||||
shaders = sorted((entry for entry in entries
|
||||
if entry.name.endswith(".dxbc") and entry.is_file()),
|
||||
key=lambda entry: entry.name)
|
||||
except OSError as e:
|
||||
print(f"ERROR: cannot list {src}: {e.strerror or e}", file=sys.stderr)
|
||||
if a.carve_index:
|
||||
names = shader_stems(a.carve_index, "file", ".dxbc")
|
||||
shaders = sorted(os.path.join(src, name + ".dxbc") for name in names)
|
||||
for path in shaders:
|
||||
if not os.path.isfile(path):
|
||||
raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}")
|
||||
else:
|
||||
with os.scandir(src) as entries:
|
||||
shaders = sorted(entry.path for entry in entries
|
||||
if entry.name.endswith(".dxbc") and entry.is_file())
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"ERROR: cannot list shaders in {src}: {e}", file=sys.stderr)
|
||||
return 2
|
||||
out = os.path.join(src, "fssm")
|
||||
os.makedirs(out, exist_ok=True)
|
||||
rows, problems = [], Counter()
|
||||
for shader in shaders:
|
||||
with open(shader.path, "rb") as f:
|
||||
with open(shader, "rb") as f:
|
||||
d = f.read()
|
||||
try:
|
||||
fssm, ents = unpack(d, payload=a.payload)
|
||||
@ -138,7 +148,7 @@ def main(argv=None) -> int:
|
||||
if fssm is None:
|
||||
problems["no XBCH"] += 1
|
||||
continue
|
||||
stem = shader.name[:-5]
|
||||
stem = os.path.basename(shader)[:-5]
|
||||
with open(os.path.join(out, stem + ".fssm"), "wb") as f:
|
||||
f.write(fssm)
|
||||
ends = [i for i in range(0, len(fssm) - 3, 4) if fssm[i:i + 4] == b"\x00\x00\x81\xbf"]
|
||||
|
||||
@ -6,7 +6,7 @@ The code ends with s_endpgm (0xBF810000). If the header guess doesn't hold for a
|
||||
scanning back from the first s_endpgm to the start that decodes with no invalid instructions.
|
||||
|
||||
Usage:
|
||||
python -I shader_disasm.py <fssm dir or file> [--out DIR] [--mcpu gfx1013] [--limit N]
|
||||
python -I shader_disasm.py <fssm dir or file> [--unpack-index FILE] [--out DIR] [--mcpu gfx1013] [--limit N]
|
||||
Writes <out>/<name>.s and prints a summary (decoded cleanly / with invalid words / failed).
|
||||
Set LLVM_MC to llvm-mc's path, or to a whole command such as
|
||||
'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' when the tool is not on PATH.
|
||||
@ -20,6 +20,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from mc_command import mc_command # noqa: E402
|
||||
from shader_stage_manifest import shader_stems # noqa: E402
|
||||
|
||||
TRIPLE = "amdgcn--amdpal"
|
||||
ENDPGM = b"\x00\x00\x81\xbf"
|
||||
@ -130,17 +131,30 @@ def one(path, out, mcpu):
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("--unpack-index", help="disassemble only the FSSMs listed in this unpack index")
|
||||
ap.add_argument("--out")
|
||||
ap.add_argument("--mcpu", default="gfx1013")
|
||||
ap.add_argument("--limit", type=positive_int)
|
||||
ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2))
|
||||
a = ap.parse_args()
|
||||
if os.path.isfile(a.src):
|
||||
if a.unpack_index:
|
||||
ap.error("--unpack-index requires an FSSM directory")
|
||||
files = [a.src]
|
||||
elif os.path.isdir(a.src):
|
||||
with os.scandir(a.src) as entries:
|
||||
files = sorted(entry.path for entry in entries
|
||||
if entry.name.endswith(".fssm") and entry.is_file())
|
||||
try:
|
||||
if a.unpack_index:
|
||||
names = shader_stems(a.unpack_index, "name")
|
||||
files = sorted(os.path.join(a.src, name + ".fssm") for name in names)
|
||||
for path in files:
|
||||
if not os.path.isfile(path):
|
||||
raise ValueError(f"{a.unpack_index}: declared FSSM file is missing: {path}")
|
||||
else:
|
||||
with os.scandir(a.src) as entries:
|
||||
files = sorted(entry.path for entry in entries
|
||||
if entry.name.endswith(".fssm") and entry.is_file())
|
||||
except (OSError, ValueError) as e:
|
||||
fail(f"cannot list shaders in {a.src}: {e}")
|
||||
else:
|
||||
fail(f"{a.src} is not a file or folder")
|
||||
if not files:
|
||||
|
||||
20
tools/shader_stage_manifest.py
Normal file
20
tools/shader_stage_manifest.py
Normal file
@ -0,0 +1,20 @@
|
||||
"""Read shader names from a completed carve or unpack index."""
|
||||
|
||||
import json
|
||||
import ntpath
|
||||
|
||||
|
||||
def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
rows = json.load(f)
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError(f"{path}: expected an array of shader entries")
|
||||
stems = set()
|
||||
for row in rows:
|
||||
value = row.get(field) if isinstance(row, dict) else None
|
||||
if not isinstance(value, str) or not value or value in (".", "..") or ntpath.basename(value) != value:
|
||||
raise ValueError(f"{path}: expected a shader basename in {field!r}")
|
||||
if suffix and (not value.endswith(suffix) or len(value) == len(suffix)):
|
||||
raise ValueError(f"{path}: expected a {suffix} filename in {field!r}")
|
||||
stems.add(value.removesuffix(suffix))
|
||||
return stems
|
||||
Reference in New Issue
Block a user