From 0c34d80a993d6f5eac7325dc9e8709aaee7de994 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:19:06 +1000 Subject: [PATCH 01/14] tooling: refuse a patch manifest nested too deeply for tomllib --- docs/experiments/patch-manifests.md | 3 +++ tests/patch_manifest_check.py | 19 +++++++++++++++++++ tools/patch_manifest.py | 5 ++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index c5ab890304..8814a43fea 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -25,6 +25,7 @@ bytes = "90c3" # the replacement, lowercase hex - **No partial apply:** the whole manifest is validated, and the input hash compared, before the loader returns anything. One bad patch refuses the manifest. - **Every patch** needs a unique `id`, a `kind`, and non-empty `why` and `remove_when`. - **Strict keys:** unknown keys and missing keys are refused at every level, so a misspelled key fails instead of being ignored. +- **Nesting:** `tomllib` recurses once per nested array or inline table. A manifest nested past the interpreter's recursion limit is refused with `manifest is nested too deeply to parse`, and the CLI exits with status 1 instead of printing a traceback. - **Kinds:** `kind` must be a string, and only `memory` is defined. `hook` and `data` are refused as `not supported` until their stages land. - **Memory patches:** `bytes` must be non-empty, and every byte it replaces needs an RVA below 2^32: a 1-byte patch at `0xffffffff` is accepted, a 2-byte one is not. Two memory patches may not overlap. Whether the span lies in a mapped section is checked later, by the runtime stage. - **Original bytes are never stored:** `expect_sha256` is a hash of the bytes the patch replaces. The loader only checks its shape; the memory stage will compare it with the mapped image. @@ -50,6 +51,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, no patches, and a TOML syntax error. - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. +- **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** | Change | Result | @@ -59,6 +61,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | String check on `kind` removed | Both wrong-type cases raise `TypeError`, and the CLI prints a traceback. | | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | + | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`, and the CLI prints a traceback. | Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` CI job ran the first version of the check with Python 3.12 and passed. diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 8f2f7477ad..1cf9f106bf 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -107,6 +107,25 @@ def test_malformed_manifests_are_refused(self): self.assertIn("patch manifest: [[patch]] 0: kind ['memory'] is not supported", result.stderr) self.assertNotIn("Traceback", result.stderr) + def test_deep_nesting_is_refused(self): + def nested(depth): + return "x = " + "[" * depth + "]" * depth + "\n" + manifest_text(self.digest, self.original) + + # Shape control: a shallow array gets past tomllib and is refused only for its unknown key. + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(nested(50)) + self.assertIn("manifest has unknown keys: x", str(caught.exception)) + # Far past the interpreter's recursion limit (1000 by default): refused, not a RecursionError. + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(nested(2000)) + self.assertIn("manifest is nested too deeply to parse", str(caught.exception)) + self.manifest.write_text(nested(2000), encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertEqual(result.stdout, "") + self.assertIn("patch manifest: manifest is nested too deeply to parse", result.stderr) + self.assertNotIn("Traceback", result.stderr) + if __name__ == "__main__": unittest.main() diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 3ff82090ce..1f8ce2a46e 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -56,7 +56,10 @@ def _sha256(value, where): def parse(text): """Return (input_sha256, patches) from manifest text, or raise ValueError.""" - data = tomllib.loads(text) + try: + data = tomllib.loads(text) + except RecursionError: # tomllib recurses once per nested array or inline table + raise ValueError("manifest is nested too deeply to parse") from None _keys(data, {"target", "patch"}, "manifest") _keys(data["target"], {"input_sha256"}, "[target]") target = _sha256(data["target"]["input_sha256"], "input_sha256") From efec112d3abe7bdb4d692a0e8ad300e1cfab07b4 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:19:28 +1000 Subject: [PATCH 02/14] tooling: define the shader patch kind, checked for shape only --- docs/experiments/patch-manifests.md | 36 +++++++++++- tests/patch_manifest_check.py | 89 +++++++++++++++++++++++++++++ tools/patch_manifest.py | 61 +++++++++++++++++++- 3 files changed, 182 insertions(+), 4 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 8814a43fea..5f463fc025 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -26,11 +26,40 @@ bytes = "90c3" # the replacement, lowercase hex - **Every patch** needs a unique `id`, a `kind`, and non-empty `why` and `remove_when`. - **Strict keys:** unknown keys and missing keys are refused at every level, so a misspelled key fails instead of being ignored. - **Nesting:** `tomllib` recurses once per nested array or inline table. A manifest nested past the interpreter's recursion limit is refused with `manifest is nested too deeply to parse`, and the CLI exits with status 1 instead of printing a traceback. -- **Kinds:** `kind` must be a string, and only `memory` is defined. `hook` and `data` are refused as `not supported` until their stages land. +- **Kinds:** `kind` must be a string, and `memory` and `shader` are defined. `hook`, `data` and any other kind are refused as `not supported`. - **Memory patches:** `bytes` must be non-empty, and every byte it replaces needs an RVA below 2^32: a 1-byte patch at `0xffffffff` is accepted, a 2-byte one is not. Two memory patches may not overlap. Whether the span lies in a mapped section is checked later, by the runtime stage. - **Original bytes are never stored:** `expect_sha256` is a hash of the bytes the patch replaces. The loader only checks its shape; the memory stage will compare it with the mapped image. - **Reporting:** the loader returns `manifest_sha256`, the SHA-256 of the manifest file's bytes, with the patch ids, for run reports to record. +### Shader patches + +A shader patch names the translation files of one shader cache key, for the runtime to read instead +of the shader cache's. The loader checks their shape only. Reading and hashing the files, and +serving them, belong to a later consumer; none exists yet. + +```toml +[[patch]] +id = "s001" +kind = "shader" +why = "" +remove_when = "" +key = "0123456789abcdef" # the cache key, 16 lowercase hex digits +pipeline = "compute" # graphics, compute or mesh86 +revision = "x2w-startup-shader-29cs" +files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, + { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "" }] +``` + +| `pipeline` | `revision` | Files the runtime reads | Required | +|---|---|---|---| +| `graphics` | `x2w-startup-shader-29` | `.txt`, `.vs.cso`, `.ps.cso` | all three | +| `compute` | `x2w-startup-shader-29cs` | `.txt`, `.cs.cso` | both | +| `mesh86` | `x2w-startup-mesh-86-1` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | + +- **Revision:** `revision` must equal the runtime's key revision for the pipeline (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`). A new revision changes every key, so a manifest written for the old one is refused instead of matching nothing. +- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a non-empty path for the consumer to resolve; `sha256` is lowercase. +- **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. + Input-specific manifests stay local under `game-files/patches/`, which is gitignored. Do not publish them or the hashes in them. @@ -51,6 +80,8 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, no patches, and a TOML syntax error. - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Revisions pinned:** each pipeline's `revision` is found as written in the runtime source and in the translator that writes the cache (`tools/startup/gfx2hlsl.py`, `tools/startup/mesh86_cache.py`). - **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** @@ -61,6 +92,9 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | String check on `kind` removed | Both wrong-type cases raise `TypeError`, and the CLI prints a traceback. | | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | + | Shader revision comparison removed | The wrong-revision case is accepted. | + | Required-file check removed | Both missing-file cases are accepted. | + | Same-key check removed | The two-patches-for-one-key case is accepted. | | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`, and the CLI prints a traceback. | Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 1cf9f106bf..b0605c8574 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -1,6 +1,7 @@ """Schema, loader and hash-gate controls for tools/patch_manifest.py on a synthetic PE32+.""" import hashlib +import json from pathlib import Path import subprocess import sys @@ -35,6 +36,25 @@ def manifest_text(input_sha256, original, patches=None): return f'[target]\ninput_sha256 = "{input_sha256}"\n{patches}' +def shader_patch(pid="s001", key="00c0ffee0badf00d", pipeline="compute", revision=None, exts=None): + """One [[patch]] of kind shader; its files are named after the patch and hashed from their names.""" + revision = revision or patch_manifest.PIPELINES[pipeline][0] + exts = patch_manifest.PIPELINES[pipeline][2] if exts is None else exts + files = ", ".join(f'{{ ext = "{ext}", file = "{pid}{ext}", sha256 = "{hashlib.sha256((pid + ext).encode()).hexdigest()}" }}' + for ext in exts) + return f""" +[[patch]] +id = "{pid}" +kind = "shader" +why = "synthetic fixture" +remove_when = "never; this is a test" +key = "{key}" +pipeline = "{pipeline}" +revision = "{revision}" +files = [{files}] +""" + + class PatchManifest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -107,6 +127,75 @@ def test_malformed_manifests_are_refused(self): self.assertIn("patch manifest: [[patch]] 0: kind ['memory'] is not supported", result.stderr) self.assertNotIn("Traceback", result.stderr) + def test_shader_patches(self): + sha = self.digest + ok = manifest_text(sha, self.original) + # Accepted beside a memory patch: each pipeline with its required files, mesh86 also with its pixel shader. + text = (ok + shader_patch("s001") + shader_patch("s002", "0123456789abcdef", "graphics") + + shader_patch("s003", "fedcba9876543210", "mesh86") + + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso"))) + target, patches = patch_manifest.parse(text) + self.assertEqual([(p["id"], p["kind"]) for p in patches], + [("p001", "memory"), ("s001", "shader"), ("s002", "shader"), ("s003", "shader"), ("s004", "shader")]) + s001 = patches[1] + self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), + ("00c0ffee0badf00d", "compute", "x2w-startup-shader-29cs")) + self.assertEqual(s001["files"], [ + {"ext": ".txt", "file": "s001.txt", "sha256": hashlib.sha256(b"s001.txt").hexdigest()}, + {"ext": ".cs.cso", "file": "s001.cs.cso", "sha256": hashlib.sha256(b"s001.cs.cso").hexdigest()}]) + self.assertEqual([f["ext"] for f in patches[4]["files"]], [".mesh86.txt", ".ms.cso", ".ps.cso"]) + # The CLI lists shader ids with the memory ones. + self.manifest.write_text(text, encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004"]) + good = shader_patch() + cases = { + "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), + "s001 key must be 16 lowercase hex": ok + shader_patch(key="00C0FFEE0BADF00D"), + "pipeline must be one of: graphics, compute, mesh86": ok + shader_patch().replace('"compute"', '"vertex"'), + "revision 'x2w-startup-shader-29' is not the runtime's compute key revision x2w-startup-shader-29cs": + ok + shader_patch(revision="x2w-startup-shader-29"), + "files must be a non-empty array": ok + good.replace(good[good.index("files = "):], "files = []\n"), + "files[0] has unknown keys: size": ok + good.replace('{ ext = ".txt",', '{ size = 1, ext = ".txt",'), + "files[1] is missing: sha256": ok + good.replace( + f', sha256 = "{hashlib.sha256(b"s001.cs.cso").hexdigest()}"', ""), + "files[1] ext '.vs.cso' is not a compute translation file (.txt, .cs.cso)": + ok + shader_patch(exts=(".txt", ".vs.cso")), + "s001 lists .txt twice": ok + shader_patch(exts=(".txt", ".cs.cso", ".txt")), + "s001 compute override is missing: .cs.cso": ok + shader_patch(exts=(".txt",)), + "s002 graphics override is missing: .vs.cso, .ps.cso": ok + shader_patch("s002", pipeline="graphics", exts=(".txt",)), + "files[0] file must be a non-empty string": ok + good.replace('file = "s001.txt"', 'file = ""'), + "files[0] sha256 must be 64 lowercase hex digits": ok + good.replace( + hashlib.sha256(b"s001.txt").hexdigest(), hashlib.sha256(b"s001.txt").hexdigest().upper()), + "patches s001 and s002 override the same key 00c0ffee0badf00d": ok + good + shader_patch("s002"), + "has unknown keys: rva": ok + good.replace('key = "', 'rva = 0x1000\nkey = "'), + "[[patch]] 1 is missing: files": ok + good[:good.index("files = ")], + "kind 'shaders' is not supported": ok + good.replace('"shader"', '"shaders"'), + } + for message, case in cases.items(): + with self.subTest(message): + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(case) + self.assertIn(message, str(caught.exception)) + + def test_shader_revisions_match_the_runtime(self): + # Each pipeline's revision, where the runtime and the translator that writes the cache spell it. + sites = { + "graphics": (("src/startup_stubs/d3d12_draw.inl", 'constexpr char revision[] = "{}";'), + ("tools/startup/gfx2hlsl.py", "fnv(b'{}')")), + "compute": (("src/startup_stubs/d3d12_draw.inl", 'constexpr char compute_revision[] = "{}";'), + ("tools/startup/gfx2hlsl.py", "fnv(b'{}')")), + "mesh86": (("src/startup_stubs/mesh86_cache.inl", 'constexpr char revision[] = "{}";'), + ("tools/startup/mesh86_cache.py", "fnv(b'{}')")), + } + self.assertEqual(set(sites), set(patch_manifest.PIPELINES)) + for pipeline, places in sites.items(): + revision = patch_manifest.PIPELINES[pipeline][0] + for path, spelling in places: + with self.subTest(f"{pipeline} in {path}"): + self.assertIn(spelling.format(revision), (ROOT / path).read_text(encoding="utf-8")) + def test_deep_nesting_is_refused(self): def nested(depth): return "x = " + "[" * depth + "]" * depth + "\n" + manifest_text(self.digest, self.original) diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 1f8ce2a46e..390b34cbc3 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -14,9 +14,20 @@ expect_sha256 = "" bytes = "90c3" # the replacement, lowercase hex + [[patch]] + id = "s001" + kind = "shader" # the translation files of one shader cache key + why = "" + remove_when = "" + key = "0123456789abcdef" # the cache key, 16 lowercase hex digits + pipeline = "compute" # graphics, compute or mesh86 + revision = "x2w-startup-shader-29cs" + files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, + { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "" }] + The whole manifest is validated and the input's SHA-256 compared before anything is returned, so -a manifest that fails any check applies nothing. Only the memory kind is defined so far, and -nothing applies it yet. +a manifest that fails any check applies nothing. The memory and shader kinds are defined, checked +for shape only; nothing applies them yet. """ import argparse @@ -28,9 +39,17 @@ SHA256 = re.compile(r"[0-9a-f]{64}") HEX = re.compile(r"(?:[0-9a-f]{2})+") +KEY = re.compile(r"[0-9a-f]{16}") COMMON = {"id", "kind", "why", "remove_when"} # Every key of a kind is required. hook and data get their tables with their stages. -KINDS = {"memory": {"rva", "expect_sha256", "bytes"}} +KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} +# Shader patches, per pipeline: the runtime's key revision (src/startup_stubs/d3d12_draw.inl and mesh86_cache.inl), +# the translation files it reads for one key, and the ones without which it has no translation. +PIPELINES = { + "graphics": ("x2w-startup-shader-29", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), + "compute": ("x2w-startup-shader-29cs", (".txt", ".cs.cso"), (".txt", ".cs.cso")), + "mesh86": ("x2w-startup-mesh-86-1", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), +} def _keys(table, keys, where): @@ -54,6 +73,35 @@ def _sha256(value, where): return value +def _shader(entry, where): + """The key, pipeline, revision and files of a shader patch, checked for shape only.""" + key = entry["key"] + if not isinstance(key, str) or not KEY.fullmatch(key): + raise ValueError(f"{where} key must be 16 lowercase hex digits") + pipeline = entry["pipeline"] + if not isinstance(pipeline, str) or pipeline not in PIPELINES: + raise ValueError(f"{where} pipeline must be one of: {', '.join(PIPELINES)}") + revision, extensions, required = PIPELINES[pipeline] + if entry["revision"] != revision: + raise ValueError(f"{where} revision {entry['revision']!r} is not the runtime's {pipeline} key revision {revision}") + if not isinstance(entry["files"], list) or not entry["files"]: + raise ValueError(f"{where} files must be a non-empty array of tables") + files = {} + for index, item in enumerate(entry["files"]): + at = f"{where} files[{index}]" + _keys(item, {"ext", "file", "sha256"}, at) + ext = item["ext"] + if not isinstance(ext, str) or ext not in extensions: + raise ValueError(f"{at} ext {ext!r} is not a {pipeline} translation file ({', '.join(extensions)})") + if ext in files: + raise ValueError(f"{where} lists {ext} twice") + files[ext] = {"ext": ext, "file": _text(item["file"], f"{at} file"), + "sha256": _sha256(item["sha256"], f"{at} sha256")} + if missing := [ext for ext in required if ext not in files]: + raise ValueError(f"{where} {pipeline} override is missing: {', '.join(missing)}") + return {"key": key, "pipeline": pipeline, "revision": revision, "files": list(files.values())} + + def parse(text): """Return (input_sha256, patches) from manifest text, or raise ValueError.""" try: @@ -76,6 +124,13 @@ def parse(text): if any(p["id"] == pid for p in patches): raise ValueError(f"duplicate patch id: {pid}") where = f"patch {pid}" + if kind == "shader": + patch = {"id": pid, "kind": kind, "why": _text(entry["why"], f"{where} why"), + "remove_when": _text(entry["remove_when"], f"{where} remove_when"), **_shader(entry, where)} + if other := next((p["id"] for p in patches if p.get("key") == patch["key"]), None): + raise ValueError(f"patches {other} and {pid} override the same key {patch['key']}") + patches.append(patch) + continue rva = entry["rva"] if type(rva) is not int or not 0 <= rva < 1 << 32: raise ValueError(f"{where} rva must be an integer in [0, 2^32)") From 4ce7470c8e666822bb6bb3d9d35b097f8247564d Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:20:04 +1000 Subject: [PATCH 03/14] tooling: gate a patch manifest on input bytes the caller already read --- docs/experiments/patch-manifests.md | 3 +++ tests/patch_manifest_check.py | 12 ++++++++++++ tools/patch_manifest.py | 12 ++++++++++++ 3 files changed, 27 insertions(+) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 5f463fc025..aba196e221 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -22,6 +22,7 @@ bytes = "90c3" # the replacement, lowercase hex ``` - **Hash gate:** the manifest applies only to the file whose SHA-256 equals `input_sha256`. Any other input is refused with `manifest is for another input`. +- **Bytes already read:** `load_data(manifest, data)` is `load` for a caller that has already read the input: it hashes `data`, so the bytes that pass the gate are the bytes the caller goes on to use, even if the file changes in between. - **No partial apply:** the whole manifest is validated, and the input hash compared, before the loader returns anything. One bad patch refuses the manifest. - **Every patch** needs a unique `id`, a `kind`, and non-empty `why` and `remove_when`. - **Strict keys:** unknown keys and missing keys are refused at every level, so a misspelled key fails instead of being ignored. @@ -80,6 +81,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, no patches, and a TOML syntax error. - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. +- **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. - **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. - **Revisions pinned:** each pipeline's `revision` is found as written in the runtime source and in the translator that writes the cache (`tools/startup/gfx2hlsl.py`, `tools/startup/mesh86_cache.py`). - **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. @@ -92,6 +94,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | String check on `kind` removed | Both wrong-type cases raise `TypeError`, and the CLI prints a traceback. | | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | + | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | | Shader revision comparison removed | The wrong-revision case is accepted. | | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index b0605c8574..0740946e50 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -127,6 +127,18 @@ def test_malformed_manifests_are_refused(self): self.assertIn("patch manifest: [[patch]] 0: kind ['memory'] is not supported", result.stderr) self.assertNotIn("Traceback", result.stderr) + def test_load_data_gates_the_bytes_given(self): + image, other = self.input.read_bytes(), self.other.read_bytes() + self.assertEqual(patch_manifest.load_data(self.manifest, image), patch_manifest.load(self.manifest, self.input)) + with self.assertRaises(ValueError) as caught: + patch_manifest.load_data(self.manifest, other) + self.assertIn("manifest is for another input", str(caught.exception)) + # The bytes in hand decide, not the file they came from: the input file now holds the other image. + self.input.write_bytes(other) + self.assertEqual(patch_manifest.load_data(self.manifest, bytearray(image))["input_sha256"], self.digest) + with self.assertRaises(ValueError): + patch_manifest.load(self.manifest, self.input) + def test_shader_patches(self): sha = self.digest ok = manifest_text(sha, self.original) diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 390b34cbc3..470628fe0a 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -163,6 +163,18 @@ def load(manifest_path, input_path): target, patches = parse(raw.decode("utf-8")) with open(input_path, "rb") as handle: digest = hashlib.file_digest(handle, "sha256").hexdigest() + return _bound(raw, target, patches, digest) + + +def load_data(manifest_path, data): + """load() for an input the caller has already read: data is hashed, so the bytes that pass the gate are + the bytes the caller goes on to use, even if the file on disk changes in between.""" + raw = Path(manifest_path).read_bytes() + target, patches = parse(raw.decode("utf-8")) + return _bound(raw, target, patches, hashlib.sha256(data).hexdigest()) + + +def _bound(raw, target, patches, digest): if digest != target: raise ValueError(f"manifest is for another input: manifest input_sha256 {target}, input sha256 {digest}") return {"manifest_sha256": hashlib.sha256(raw).hexdigest(), "input_sha256": digest, "patches": patches} From e272a433a55d799e9ca22f62c90f20130460144d Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:22:34 +1000 Subject: [PATCH 04/14] tooling: check the shader revision's form, not the runtime's current number --- docs/experiments/patch-manifests.md | 16 ++++---- tests/patch_manifest_check.py | 60 +++++++++++++++++------------ tools/patch_manifest.py | 20 ++++++---- 3 files changed, 56 insertions(+), 40 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index aba196e221..bd581f6f23 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -51,13 +51,13 @@ files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "" }] ``` -| `pipeline` | `revision` | Files the runtime reads | Required | +| `pipeline` | `revision` form | Files the runtime reads | Required | |---|---|---|---| -| `graphics` | `x2w-startup-shader-29` | `.txt`, `.vs.cso`, `.ps.cso` | all three | -| `compute` | `x2w-startup-shader-29cs` | `.txt`, `.cs.cso` | both | -| `mesh86` | `x2w-startup-mesh-86-1` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | +| `graphics` | `x2w-startup-shader-` | `.txt`, `.vs.cso`, `.ps.cso` | all three | +| `compute` | `x2w-startup-shader-cs` | `.txt`, `.cs.cso` | both | +| `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | -- **Revision:** `revision` must equal the runtime's key revision for the pipeline (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`). A new revision changes every key, so a manifest written for the old one is refused instead of matching nothing. +- **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. - **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a non-empty path for the consumer to resolve; `sha256` is lowercase. - **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. @@ -82,8 +82,8 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. -- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. -- **Revisions pinned:** each pipeline's `revision` is found as written in the runtime source and in the translator that writes the cache (`tools/startup/gfx2hlsl.py`, `tools/startup/mesh86_cache.py`). +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** @@ -95,7 +95,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | - | Shader revision comparison removed | The wrong-revision case is accepted. | + | Revision form check removed | The other-pipeline and malformed revision cases are accepted. | | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`, and the CLI prints a traceback. | diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 0740946e50..041d409b64 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -3,6 +3,7 @@ import hashlib import json from pathlib import Path +import re import subprocess import sys import tempfile @@ -19,6 +20,9 @@ from call_evidence_check import SECTION_RVA, build_pe32_plus # noqa: E402 REPLACEMENT = "90c3" +# Revisions of each pipeline's form, not the runtime's current ones: the loader checks the form only. +REVISION = {"graphics": "x2w-startup-shader-12", "compute": "x2w-startup-shader-12cs", + "mesh86": "x2w-startup-mesh-86-4"} def manifest_text(input_sha256, original, patches=None): @@ -38,10 +42,10 @@ def manifest_text(input_sha256, original, patches=None): def shader_patch(pid="s001", key="00c0ffee0badf00d", pipeline="compute", revision=None, exts=None): """One [[patch]] of kind shader; its files are named after the patch and hashed from their names.""" - revision = revision or patch_manifest.PIPELINES[pipeline][0] + revision = revision or REVISION[pipeline] exts = patch_manifest.PIPELINES[pipeline][2] if exts is None else exts - files = ", ".join(f'{{ ext = "{ext}", file = "{pid}{ext}", sha256 = "{hashlib.sha256((pid + ext).encode()).hexdigest()}" }}' - for ext in exts) + files = ", ".join(f'{{ ext = "{ext}", file = "{pid}{ext}", ' + f'sha256 = "{hashlib.sha256((pid + ext).encode()).hexdigest()}" }}' for ext in exts) return f""" [[patch]] id = "{pid}" @@ -147,11 +151,11 @@ def test_shader_patches(self): + shader_patch("s003", "fedcba9876543210", "mesh86") + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso"))) target, patches = patch_manifest.parse(text) - self.assertEqual([(p["id"], p["kind"]) for p in patches], - [("p001", "memory"), ("s001", "shader"), ("s002", "shader"), ("s003", "shader"), ("s004", "shader")]) + self.assertEqual([(p["id"], p["kind"]) for p in patches], [("p001", "memory")] + [ + (pid, "shader") for pid in ("s001", "s002", "s003", "s004")]) s001 = patches[1] self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), - ("00c0ffee0badf00d", "compute", "x2w-startup-shader-29cs")) + ("00c0ffee0badf00d", "compute", "x2w-startup-shader-12cs")) self.assertEqual(s001["files"], [ {"ext": ".txt", "file": "s001.txt", "sha256": hashlib.sha256(b"s001.txt").hexdigest()}, {"ext": ".cs.cso", "file": "s001.cs.cso", "sha256": hashlib.sha256(b"s001.cs.cso").hexdigest()}]) @@ -166,8 +170,16 @@ def test_shader_patches(self): "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), "s001 key must be 16 lowercase hex": ok + shader_patch(key="00C0FFEE0BADF00D"), "pipeline must be one of: graphics, compute, mesh86": ok + shader_patch().replace('"compute"', '"vertex"'), - "revision 'x2w-startup-shader-29' is not the runtime's compute key revision x2w-startup-shader-29cs": - ok + shader_patch(revision="x2w-startup-shader-29"), + "revision 'x2w-startup-shader-12' is not a compute key revision (x2w-startup-shader-cs)": + ok + shader_patch(revision="x2w-startup-shader-12"), + "s002 revision 'x2w-startup-shader-12cs' is not a graphics key revision (x2w-startup-shader-)": + ok + shader_patch("s002", pipeline="graphics", revision="x2w-startup-shader-12cs"), + "revision 'x2w-startup-mesh-57-3' is not a mesh86 key revision (x2w-startup-mesh-86-)": + ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-3"), + "revision 'x2w-startup-shader-cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-cs"), + "revision 'x2w-startup-shader-012cs' is not a compute": + ok + shader_patch(revision="x2w-startup-shader-012cs"), + "revision 29 is not a compute": ok + shader_patch().replace('"x2w-startup-shader-12cs"', "29"), "files must be a non-empty array": ok + good.replace(good[good.index("files = "):], "files = []\n"), "files[0] has unknown keys: size": ok + good.replace('{ ext = ".txt",', '{ size = 1, ext = ".txt",'), "files[1] is missing: sha256": ok + good.replace( @@ -176,7 +188,8 @@ def test_shader_patches(self): ok + shader_patch(exts=(".txt", ".vs.cso")), "s001 lists .txt twice": ok + shader_patch(exts=(".txt", ".cs.cso", ".txt")), "s001 compute override is missing: .cs.cso": ok + shader_patch(exts=(".txt",)), - "s002 graphics override is missing: .vs.cso, .ps.cso": ok + shader_patch("s002", pipeline="graphics", exts=(".txt",)), + "s002 graphics override is missing: .vs.cso, .ps.cso": + ok + shader_patch("s002", pipeline="graphics", exts=(".txt",)), "files[0] file must be a non-empty string": ok + good.replace('file = "s001.txt"', 'file = ""'), "files[0] sha256 must be 64 lowercase hex digits": ok + good.replace( hashlib.sha256(b"s001.txt").hexdigest(), hashlib.sha256(b"s001.txt").hexdigest().upper()), @@ -191,22 +204,21 @@ def test_shader_patches(self): patch_manifest.parse(case) self.assertIn(message, str(caught.exception)) - def test_shader_revisions_match_the_runtime(self): - # Each pipeline's revision, where the runtime and the translator that writes the cache spell it. - sites = { - "graphics": (("src/startup_stubs/d3d12_draw.inl", 'constexpr char revision[] = "{}";'), - ("tools/startup/gfx2hlsl.py", "fnv(b'{}')")), - "compute": (("src/startup_stubs/d3d12_draw.inl", 'constexpr char compute_revision[] = "{}";'), - ("tools/startup/gfx2hlsl.py", "fnv(b'{}')")), - "mesh86": (("src/startup_stubs/mesh86_cache.inl", 'constexpr char revision[] = "{}";'), - ("tools/startup/mesh86_cache.py", "fnv(b'{}')")), + def test_shader_revision_forms_match_the_runtime(self): + # The runtime's current revision of each pipeline has the loader's form, so a bump (a new ) still loads. + # Whether a manifest names the current revision is for a later consumer to check against the runtime. + draw = (ROOT / "src/startup_stubs/d3d12_draw.inl").read_text(encoding="utf-8") + mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") + found = { + "graphics": re.findall(r'constexpr char revision\[\] = "(x2w-startup-shader-[^"]*)";', draw), + "compute": re.findall(r'constexpr char compute_revision\[\] = "([^"]*)";', draw), + "mesh86": re.findall(r'constexpr char revision\[\] = "([^"]*)";', mesh86), } - self.assertEqual(set(sites), set(patch_manifest.PIPELINES)) - for pipeline, places in sites.items(): - revision = patch_manifest.PIPELINES[pipeline][0] - for path, spelling in places: - with self.subTest(f"{pipeline} in {path}"): - self.assertIn(spelling.format(revision), (ROOT / path).read_text(encoding="utf-8")) + self.assertEqual(set(found), set(patch_manifest.PIPELINES)) + for pipeline, revisions in found.items(): + with self.subTest(pipeline): + self.assertEqual(len(revisions), 1, revisions) + self.assertTrue(patch_manifest.REVISIONS[pipeline].fullmatch(revisions[0]), revisions[0]) def test_deep_nesting_is_refused(self): def nested(depth): diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 470628fe0a..5c9852d554 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -43,13 +43,16 @@ COMMON = {"id", "kind", "why", "remove_when"} # Every key of a kind is required. hook and data get their tables with their stages. KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} -# Shader patches, per pipeline: the runtime's key revision (src/startup_stubs/d3d12_draw.inl and mesh86_cache.inl), -# the translation files it reads for one key, and the ones without which it has no translation. +# Shader patches, per pipeline: the form of the runtime's key revision (src/startup_stubs/d3d12_draw.inl and +# mesh86_cache.inl; is the number each revision bump raises), the translation files the runtime reads for one +# key, and the ones without which it has no translation. A later consumer must check which is current. PIPELINES = { - "graphics": ("x2w-startup-shader-29", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), - "compute": ("x2w-startup-shader-29cs", (".txt", ".cs.cso"), (".txt", ".cs.cso")), - "mesh86": ("x2w-startup-mesh-86-1", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), + "graphics": ("x2w-startup-shader-", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), + "compute": ("x2w-startup-shader-cs", (".txt", ".cs.cso"), (".txt", ".cs.cso")), + "mesh86": ("x2w-startup-mesh-86-", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), } +REVISIONS = {name: re.compile(re.escape(form).replace("", "[1-9][0-9]*")) + for name, (form, _, _) in PIPELINES.items()} def _keys(table, keys, where): @@ -81,9 +84,10 @@ def _shader(entry, where): pipeline = entry["pipeline"] if not isinstance(pipeline, str) or pipeline not in PIPELINES: raise ValueError(f"{where} pipeline must be one of: {', '.join(PIPELINES)}") - revision, extensions, required = PIPELINES[pipeline] - if entry["revision"] != revision: - raise ValueError(f"{where} revision {entry['revision']!r} is not the runtime's {pipeline} key revision {revision}") + form, extensions, required = PIPELINES[pipeline] + revision = entry["revision"] + if not isinstance(revision, str) or not REVISIONS[pipeline].fullmatch(revision): + raise ValueError(f"{where} revision {revision!r} is not a {pipeline} key revision ({form})") if not isinstance(entry["files"], list) or not entry["files"]: raise ValueError(f"{where} files must be a non-empty array of tables") files = {} From 7a8740e6cb6afdd721fc0554e61d457c1a594009 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:23:12 +1000 Subject: [PATCH 05/14] tooling: a shader patch names its files by bare file name --- docs/experiments/patch-manifests.md | 5 +++-- tests/patch_manifest_check.py | 3 +++ tools/patch_manifest.py | 10 +++++++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index bd581f6f23..4b4db44323 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -58,7 +58,7 @@ files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, | `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | - **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. -- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a non-empty path for the consumer to resolve; `sha256` is lowercase. +- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. `sha256` is lowercase. - **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. Input-specific manifests stay local under `game-files/patches/`, which is gitignored. Do not @@ -82,7 +82,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. -- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** @@ -96,6 +96,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | | Revision form check removed | The other-pipeline and malformed revision cases are accepted. | + | Bare-name check on `file` removed | The six non-bare `file` cases are accepted. | | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`, and the CLI prints a traceback. | diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 041d409b64..b69f36c9ad 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -191,6 +191,9 @@ def test_shader_patches(self): "s002 graphics override is missing: .vs.cso, .ps.cso": ok + shader_patch("s002", pipeline="graphics", exts=(".txt",)), "files[0] file must be a non-empty string": ok + good.replace('file = "s001.txt"', 'file = ""'), + **{f"files[0] file {name!r} must be a bare file name": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("sub/s001.txt", "sub\\s001.txt", "/s001.txt", "C:s001.txt", "..", ".")}, "files[0] sha256 must be 64 lowercase hex digits": ok + good.replace( hashlib.sha256(b"s001.txt").hexdigest(), hashlib.sha256(b"s001.txt").hexdigest().upper()), "patches s001 and s002 override the same key 00c0ffee0badf00d": ok + good + shader_patch("s002"), diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 5c9852d554..5ef8990b74 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -76,6 +76,14 @@ def _sha256(value, where): return value +def _file_name(value, where): + """A bare file name, for a later consumer to resolve in the manifest's directory.""" + name = _text(value, where) + if any(c in name for c in "/\\:") or name in (".", ".."): + raise ValueError(f"{where} {name!r} must be a bare file name, without a directory, drive or '..'") + return name + + def _shader(entry, where): """The key, pipeline, revision and files of a shader patch, checked for shape only.""" key = entry["key"] @@ -99,7 +107,7 @@ def _shader(entry, where): raise ValueError(f"{at} ext {ext!r} is not a {pipeline} translation file ({', '.join(extensions)})") if ext in files: raise ValueError(f"{where} lists {ext} twice") - files[ext] = {"ext": ext, "file": _text(item["file"], f"{at} file"), + files[ext] = {"ext": ext, "file": _file_name(item["file"], f"{at} file"), "sha256": _sha256(item["sha256"], f"{at} sha256")} if missing := [ext for ext in required if ext not in files]: raise ValueError(f"{where} {pipeline} override is missing: {', '.join(missing)}") From d36d56d7dd11be0d6405462e4d91dc8355638860 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:23:34 +1000 Subject: [PATCH 06/14] tests: pin the shader patch files to what the runtime reads --- docs/experiments/patch-manifests.md | 2 ++ tests/patch_manifest_check.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 4b4db44323..4e4a85e6dc 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -83,6 +83,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. - **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and mesh86's `.ps.cso` is the only optional one, read only for a request with a pixel shader. - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** @@ -97,6 +98,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | | Revision form check removed | The other-pipeline and malformed revision cases are accepted. | | Bare-name check on `file` removed | The six non-bare `file` cases are accepted. | + | The runtime reads `.vx.cso` instead of `.vs.cso` (`d3d12_draw.inl`) | The files pin fails for graphics. | | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`, and the CLI prints a traceback. | diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index b69f36c9ad..8660d02db7 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -223,6 +223,21 @@ def test_shader_revision_forms_match_the_runtime(self): self.assertEqual(len(revisions), 1, revisions) self.assertTrue(patch_manifest.REVISIONS[pipeline].fullmatch(revisions[0]), revisions[0]) + def test_shader_files_match_the_runtime(self): + # The translation files each pipeline's loader in the runtime reads for one key: cache_path(..., L"", key, ext) + # and mesh86's load_stage(ext, ...). mesh86 reads its .ps.cso only for a request with a pixel shader. + reads = re.compile(r'(?:cache_path\(\w+, L"", [\w.]+, |load_stage\()L"(\.[a-z0-9.]+)"') + sources = {"graphics": "d3d12_draw.inl", "compute": "d3d12_compute_dispatch.inl", "mesh86": "mesh86_cache.inl"} + self.assertEqual(set(sources), set(patch_manifest.PIPELINES)) + for pipeline, name in sources.items(): + text = (ROOT / "src/startup_stubs" / name).read_text(encoding="utf-8") + with self.subTest(pipeline): + self.assertEqual(set(reads.findall(text)), set(patch_manifest.PIPELINES[pipeline][1])) + mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") + self.assertIn('(!request.ps.empty() && !load_stage(L".ps.cso", ps))', mesh86) + self.assertEqual(set(patch_manifest.PIPELINES["mesh86"][1]) - set(patch_manifest.PIPELINES["mesh86"][2]), + {".ps.cso"}) + def test_deep_nesting_is_refused(self): def nested(depth): return "x = " + "[" * depth + "]" * depth + "\n" + manifest_text(self.digest, self.original) From 195d9bdbac1c41be60e926b2c81c9ac4e9ea6a4b Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:23:57 +1000 Subject: [PATCH 07/14] tests: set the recursion limit in the patch manifest nesting case --- docs/experiments/patch-manifests.md | 2 +- tests/patch_manifest_check.py | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 4e4a85e6dc..8c210f73ab 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -85,7 +85,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. - **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and mesh86's `.ps.cso` is the only optional one, read only for a request with a pixel shader. - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. -- **Deep nesting:** an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. +- **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** | Change | Result | diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 8660d02db7..59ab8d9737 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -246,7 +246,11 @@ def nested(depth): with self.assertRaises(ValueError) as caught: patch_manifest.parse(nested(50)) self.assertIn("manifest has unknown keys: x", str(caught.exception)) - # Far past the interpreter's recursion limit (1000 by default): refused, not a RecursionError. + # Twice the recursion limit, set here so a runner that raised it cannot parse the array: refused, not a + # RecursionError. The CLI runs in a new interpreter, whose limit is the default 1000. + limit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, limit) + sys.setrecursionlimit(1000) with self.assertRaises(ValueError) as caught: patch_manifest.parse(nested(2000)) self.assertIn("manifest is nested too deeply to parse", str(caught.exception)) From af7a562771308bd56f9059ada00f38c8a8160657 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:25:10 +1000 Subject: [PATCH 08/14] docs: list the shader patch mutations and controls --- docs/experiments/patch-manifests.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 8c210f73ab..23e70e9bbe 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -96,12 +96,14 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | - | Revision form check removed | The other-pipeline and malformed revision cases are accepted. | + | Revision form check removed | The other-pipeline, number-less and leading-zero revision cases are accepted. | + | The runtime's graphics revision gets a suffix (`x2w-startup-shader-29b`) | The revision-form pin fails for graphics. | + | The runtime's graphics revision is bumped (`-29` to `-30`), loader untouched | Control: the check stays green. | | Bare-name check on `file` removed | The six non-bare `file` cases are accepted. | | The runtime reads `.vx.cso` instead of `.vs.cso` (`d3d12_draw.inl`) | The files pin fails for graphics. | | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | - | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`, and the CLI prints a traceback. | + | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`. | Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` CI job ran the first version of the check with Python 3.12 and passed. From 13269fb517b497a3490bfb2ae895f5e31363ad48 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:25:36 +1000 Subject: [PATCH 09/14] docs: record the patch manifest loader measurements --- docs/experiments/patch-manifests.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 23e70e9bbe..654ca34323 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -107,3 +107,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` CI job ran the first version of the check with Python 3.12 and passed. + +With the nesting, shader and `load_data` cases: 8 tests, all passed on Linux (Debian 13) with Python +3.13.5 and pefile 2024.8.26. Each mutation in the table above made the check fail, and the revision-bump +control stayed green. Not yet run on Windows. From 439da51188dbc4d9753ec2badef6d52c88538a56 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:48:10 +1000 Subject: [PATCH 10/14] tests: pin patch manifest geometry, trailing text, empty bytes and the CLI's OSError Four memory patches in descending RVA, three adjacent and one at RVA 0, load; a one-byte overlap is refused in either order. A hash or key with trailing text and an empty bytes are refused, the bound patch is compared field by field, and a missing input file reaches the CLI as a diagnostic. Each kills one of the eight mutations that survived the fixture. --- tests/patch_manifest_check.py | 48 ++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 59ab8d9737..f261ab005f 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -40,6 +40,20 @@ def manifest_text(input_sha256, original, patches=None): return f'[target]\ninput_sha256 = "{input_sha256}"\n{patches}' +def memory_patch(pid, rva, replacement=REPLACEMENT): + """One [[patch]] of kind memory; parse checks the shape of expect_sha256, not the bytes it hashes.""" + return f""" +[[patch]] +id = "{pid}" +kind = "memory" +why = "synthetic fixture" +remove_when = "never; this is a test" +rva = {rva:#x} +expect_sha256 = "{hashlib.sha256(pid.encode()).hexdigest()}" +bytes = "{replacement}" +""" + + def shader_patch(pid="s001", key="00c0ffee0badf00d", pipeline="compute", revision=None, exts=None): """One [[patch]] of kind shader; its files are named after the patch and hashed from their names.""" revision = revision or REVISION[pipeline] @@ -83,7 +97,10 @@ def test_bound_input_loads(self): self.assertEqual(plan["manifest_sha256"], hashlib.sha256(self.manifest.read_bytes()).hexdigest()) self.assertEqual(plan["input_sha256"], self.digest) [patch] = plan["patches"] - self.assertEqual((patch["id"], patch["rva"], patch["bytes"]), ("p001", SECTION_RVA, bytes.fromhex(REPLACEMENT))) + self.assertEqual(patch, {"id": "p001", "kind": "memory", "why": "synthetic fixture", + "remove_when": "never; this is a test", "rva": SECTION_RVA, + "expect_sha256": hashlib.sha256(self.original).hexdigest(), + "bytes": bytes.fromhex(REPLACEMENT)}) result = self.cli(self.input) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn('"p001"', result.stdout) @@ -93,6 +110,29 @@ def test_wrong_input_is_refused(self): self.assertEqual(result.returncode, 1, result.stdout) self.assertIn("manifest is for another input", result.stderr) self.assertEqual(result.stdout, "") + # An input that cannot be opened is a diagnostic too, not a traceback. + result = self.cli(self.input.with_name("absent.bin")) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn("patch manifest: [Errno", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(result.stdout, "") + + def test_memory_patches_side_by_side(self): + # Adjacent spans do not overlap, the order of the [[patch]] tables does not matter, and RVA 0 is in range. + text = manifest_text(self.digest, self.original, patches="".join( + memory_patch(pid, rva) for pid, rva in (("p003", SECTION_RVA + 4), ("p002", SECTION_RVA + 2), + ("p001", SECTION_RVA), ("p000", 0)))) + _, patches = patch_manifest.parse(text) + self.assertEqual([(p["id"], p["rva"]) for p in patches], + [("p003", SECTION_RVA + 4), ("p002", SECTION_RVA + 2), ("p001", SECTION_RVA), ("p000", 0)]) + # One shared byte is an overlap, in either order. + for first, second in ((SECTION_RVA, SECTION_RVA + 1), (SECTION_RVA + 1, SECTION_RVA)): + with self.subTest(first=first, second=second): + text = manifest_text(self.digest, self.original, + patches=memory_patch("p001", first) + memory_patch("p002", second)) + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(text) + self.assertRegex(str(caught.exception), r"patches p00[12] and p00[12] overlap") def test_malformed_manifests_are_refused(self): sha = self.digest @@ -109,8 +149,13 @@ def test_malformed_manifests_are_refused(self): "duplicate patch id: p001": ok + ok.split("[target]", 1)[1].split("\n", 2)[2], "patches p001 and p002 overlap": ok + second, "bytes must be": ok.replace(REPLACEMENT, "90c"), + "p001 bytes must be a non-empty": ok.replace(f'bytes = "{REPLACEMENT}"', 'bytes = ""'), "rva must be": ok.replace(f"rva = {SECTION_RVA:#x}", "rva = true"), "input_sha256 must be": ok.replace(sha, sha.upper()), + # A hash or key with trailing text is malformed, not a hash of another input. + "input_sha256 must be 64 lowercase hex digits": ok.replace(sha, sha + "0"), + "p001 expect_sha256 must be 64": ok.replace(hashlib.sha256(self.original).hexdigest(), + hashlib.sha256(self.original).hexdigest() + "x"), "at least one [[patch]]": "patch = []\n" + manifest_text(sha, self.original, patches=""), } for message, text in cases.items(): @@ -169,6 +214,7 @@ def test_shader_patches(self): cases = { "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), "s001 key must be 16 lowercase hex": ok + shader_patch(key="00C0FFEE0BADF00D"), + "patch s001 key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00d0"), "pipeline must be one of: graphics, compute, mesh86": ok + shader_patch().replace('"compute"', '"vertex"'), "revision 'x2w-startup-shader-12' is not a compute key revision (x2w-startup-shader-cs)": ok + shader_patch(revision="x2w-startup-shader-12"), From 4968e12475aec89f35bbb2a5b28b6cc1ddae4d2c Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:48:10 +1000 Subject: [PATCH 11/14] docs: list the patch manifest cases and mutations added for the fixture audit --- docs/experiments/patch-manifests.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 654ca34323..01e95633a2 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -76,13 +76,14 @@ On Windows: `ctest --preset dev --no-tests=error -R '^patch_manifest_controls$' The check builds a synthetic PE32+ at run time with `build_pe32_plus` from `tests/call_evidence_check.py`. Its manifest replaces two bytes at the start of the `.rdata` section. -- **Bound input:** the manifest loads, and the CLI prints the manifest hash and `p001`. -- **Wrong input:** the same image with its last byte flipped makes the CLI exit with status 1 and `manifest is for another input`, with nothing on stdout. -- **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, no patches, and a TOML syntax error. +- **Bound input:** the manifest loads with every field of `p001` as written, and the CLI prints the manifest hash and `p001`. +- **Wrong input:** the same image with its last byte flipped makes the CLI exit with status 1 and `manifest is for another input`, with nothing on stdout. An input file that does not exist also gives status 1, with a `patch manifest: [Errno ...]` message and no traceback. +- **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length or empty `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, an `input_sha256` or `expect_sha256` with trailing text, no patches, and a TOML syntax error. - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. +- **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Two patches that share one byte are refused as an overlap, in either order. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. -- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. - **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and mesh86's `.ps.cso` is the only optional one, read only for a request with a pixel shader. - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. @@ -104,10 +105,18 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`. | + | `SHA256.fullmatch` changed to `match` | The `input_sha256` and `expect_sha256` cases with trailing text are accepted. | + | Shader `KEY.fullmatch` changed to `match` | The 17-digit key is accepted. | + | `bytes` pattern allows zero digit pairs (`*`) | The empty `bytes` case is accepted. | + | Overlap check `<` changed to `<=` | The side-by-side case refuses its adjacent patches. | + | Spans no longer sorted before the overlap check | The side-by-side case refuses its descending order. | + | `rva` lower bound `0 <=` changed to `0 <` | The side-by-side case refuses its patch at RVA 0. | + | `why` dropped from a memory patch | The bound-input case finds a patch without `why`. | + | The CLI catches `ValueError` only | The missing input file ends in a traceback. | Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` CI job ran the first version of the check with Python 3.12 and passed. -With the nesting, shader and `load_data` cases: 8 tests, all passed on Linux (Debian 13) with Python -3.13.5 and pefile 2024.8.26. Each mutation in the table above made the check fail, and the revision-bump -control stayed green. Not yet run on Windows. +With the nesting, shader, `load_data` and side-by-side memory cases: 9 tests, all passed on Linux +(Debian 13) with Python 3.13.5 and pefile 2024.8.26. Each mutation in the table above made the check +fail, and the revision-bump control stayed green. Not yet run on Windows. From 609a17867f55ddd26fd10ffde3b45e20a50bbc05 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:32:20 +1000 Subject: [PATCH 12/14] tests: give the side-by-side patches ids out of step with their addresses A sort of the spans by id instead of by address passed the fixture, because the accept case listed ids that followed the addresses. Use ids that follow neither the addresses nor their reverse, and list the mutation. --- docs/experiments/patch-manifests.md | 9 ++++++++- tests/patch_manifest_check.py | 7 ++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 01e95633a2..10ac9c8699 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -80,7 +80,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Wrong input:** the same image with its last byte flipped makes the CLI exit with status 1 and `manifest is for another input`, with nothing on stdout. An input file that does not exist also gives status 1, with a `patch manifest: [Errno ...]` message and no traceback. - **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length or empty `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, an `input_sha256` or `expect_sha256` with trailing text, no patches, and a TOML syntax error. - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. -- **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Two patches that share one byte are refused as an overlap, in either order. +- **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Their ids follow neither the RVA order nor its reverse, so no order by id is an order by address. Two patches that share one byte are refused as an overlap, in either order. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. - **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. @@ -110,6 +110,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | `bytes` pattern allows zero digit pairs (`*`) | The empty `bytes` case is accepted. | | Overlap check `<` changed to `<=` | The side-by-side case refuses its adjacent patches. | | Spans no longer sorted before the overlap check | The side-by-side case refuses its descending order. | + | Spans sorted by id (`key=lambda s: s[2]`), ascending or descending, instead of by address | The side-by-side case refuses its patches, whose ids do not follow the addresses. | | `rva` lower bound `0 <=` changed to `0 <` | The side-by-side case refuses its patch at RVA 0. | | `why` dropped from a memory patch | The bound-input case finds a patch without `why`. | | The CLI catches `ValueError` only | The missing input file ends in a traceback. | @@ -120,3 +121,9 @@ CI job ran the first version of the check with Python 3.12 and passed. With the nesting, shader, `load_data` and side-by-side memory cases: 9 tests, all passed on Linux (Debian 13) with Python 3.13.5 and pefile 2024.8.26. Each mutation in the table above made the check fail, and the revision-bump control stayed green. Not yet run on Windows. + +With the side-by-side ids out of step with the addresses: 9 tests, all passed on Linux (Debian 13) with +Python 3.13.5 and pefile 2024.8.26. The ascending id sort above, which passed before this change, and the +descending one now fail the check on the side-by-side case. A sort by span end (`key=lambda s: s[1]`) +still passes: for spans of at least one byte it flags an overlap exactly when the sort by start does, so +it is not counted as a survivor. diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index f261ab005f..daaa660a63 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -119,12 +119,13 @@ def test_wrong_input_is_refused(self): def test_memory_patches_side_by_side(self): # Adjacent spans do not overlap, the order of the [[patch]] tables does not matter, and RVA 0 is in range. + # The ids follow neither the addresses nor their reverse, so spans sorted by id either way refuse this case. text = manifest_text(self.digest, self.original, patches="".join( - memory_patch(pid, rva) for pid, rva in (("p003", SECTION_RVA + 4), ("p002", SECTION_RVA + 2), - ("p001", SECTION_RVA), ("p000", 0)))) + memory_patch(pid, rva) for pid, rva in (("p001", SECTION_RVA + 4), ("p003", SECTION_RVA + 2), + ("p000", SECTION_RVA), ("p002", 0)))) _, patches = patch_manifest.parse(text) self.assertEqual([(p["id"], p["rva"]) for p in patches], - [("p003", SECTION_RVA + 4), ("p002", SECTION_RVA + 2), ("p001", SECTION_RVA), ("p000", 0)]) + [("p001", SECTION_RVA + 4), ("p003", SECTION_RVA + 2), ("p000", SECTION_RVA), ("p002", 0)]) # One shared byte is an overlap, in either order. for first, second in ((SECTION_RVA, SECTION_RVA + 1), (SECTION_RVA + 1, SECTION_RVA)): with self.subTest(first=first, second=second): From 0d733d9a1765dd3d68558e48a33c0059f9835f58 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:57:41 +1000 Subject: [PATCH 13/14] loader: refuse Windows-invalid manifest file names (#3119) --- docs/experiments/patch-manifests.md | 18 ++++++++++++++++-- tests/patch_manifest_check.py | 16 ++++++++++++++++ tools/patch_manifest.py | 16 +++++++++++++++- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 10ac9c8699..93bf1c540a 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -58,7 +58,7 @@ files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, | `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | - **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. -- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. `sha256` is lowercase. +- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. That consumer is the runtime, which runs on Windows, so a name Windows would not open as a file of that name in the directory is refused too: one with `<`, `>`, `"`, `|`, `?`, `*` or a control character, one ending in a dot or a space (Windows drops them), and a device name (`CON`, `PRN`, `AUX`, `NUL`, `COM0`-`COM9`, `LPT0`-`LPT9`, `COM` and `LPT` with a superscript 1 to 3, `CONIN$`, `CONOUT$`) in any case, alone or before an extension, as Microsoft's "Naming Files, Paths, and Namespaces" lists them. `sha256` is lowercase. - **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. Input-specific manifests stay local under `game-files/patches/`, which is gitignored. Do not @@ -83,7 +83,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Their ids follow neither the RVA order nor its reverse, so no order by id is an order by address. Two patches that share one byte are refused as an overlap, in either order. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. -- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, a `file` with `*`, `?`, `<`, `>`, `|`, `"`, a tab or U+0001, `s001.txt.` and `s001.txt ` (trailing space), the device names `NUL`, `CON.txt`, `Com1`, `nul .txt`, `CONIN$`, `conout$.txt`, `COM` + U+00B9 and `lpt` + U+00B3 + `.cso`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. - **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and mesh86's `.ps.cso` is the only optional one, read only for a request with a pixel shader. - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. @@ -101,6 +101,16 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | The runtime's graphics revision gets a suffix (`x2w-startup-shader-29b`) | The revision-form pin fails for graphics. | | The runtime's graphics revision is bumped (`-29` to `-30`), loader untouched | Control: the check stays green. | | Bare-name check on `file` removed | The six non-bare `file` cases are accepted. | + | Check for `<>"\|?*` in `file` removed | The six cases with one of those characters are accepted. | + | Control-character check on `file` removed | The tab and U+0001 cases are accepted. | + | Trailing dot or space check removed; or it checks the dot only; or the space only | Both cases; the trailing space; the trailing dot are accepted. | + | Device-name check removed | The eight device-name cases are accepted. | + | Device names matched case-sensitively | The upper- and mixed-case ones (`NUL`, `CON.txt`, `Com1`, `CONIN$`, `COM` + U+00B9) are accepted. | + | Device names matched as a prefix (`match`, not `fullmatch`) | `console.txt`, `nulls.cso`, `com10.txt` and `conin.txt` are refused. | + | Device name matched against the whole `file`, not the part before the first dot | `CON.txt`, `nul .txt`, `conout$.txt` and `lpt` + U+00B3 + `.cso` are accepted. | + | Trailing spaces kept on the part before the dot | `nul .txt` is accepted. | + | `CONIN$` and `CONOUT$` dropped from the device names | Both cases are accepted. | + | Superscript `COM` and `LPT` dropped from the device names | Both cases are accepted. | | The runtime reads `.vx.cso` instead of `.vs.cso` (`d3d12_draw.inl`) | The files pin fails for graphics. | | Required-file check removed | Both missing-file cases are accepted. | | Same-key check removed | The two-patches-for-one-key case is accepted. | @@ -127,3 +137,7 @@ Python 3.13.5 and pefile 2024.8.26. The ascending id sort above, which passed be descending one now fail the check on the side-by-side case. A sort by span end (`key=lambda s: s[1]`) still passes: for spans of at least one byte it flags an overlap exactly when the sort by start does, so it is not counted as a survivor. + +With the Windows file-name refusals (review of `4968e124`): 9 tests, all passed on Linux (Debian 13) with +Python 3.13.5 and pefile 2024.8.26. Each of the twelve mutations of the refusal in the table above made the +check fail, and the 24 earlier loader mutations still did. Not run on Windows. diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index daaa660a63..3e0570a9a3 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -241,6 +241,17 @@ def test_shader_patches(self): **{f"files[0] file {name!r} must be a bare file name": ok + good.replace('file = "s001.txt"', f"file = '{name}'") for name in ("sub/s001.txt", "sub\\s001.txt", "/s001.txt", "C:s001.txt", "..", ".")}, + # The runtime that reads these files runs on Windows: names it can't hold, shortens or opens as a device. + **{f"files[0] file {name!r} has a character a Windows file name cannot hold": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("a*b", "a?b", "ab", "a|b", 'a"b', "a\tb")}, + "files[0] file 'a\\x01b' has a character": ok + good.replace('file = "s001.txt"', 'file = "a\\u0001b"'), + **{f"files[0] file {name!r} ends in a dot or a space, which Windows drops": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") for name in ("s001.txt.", "s001.txt ")}, + **{f"files[0] file {name!r} is a Windows device name": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("NUL", "CON.txt", "Com1", "nul .txt", "CONIN$", "conout$.txt", + "COM\u00b9", "lpt\u00b3.cso")}, "files[0] sha256 must be 64 lowercase hex digits": ok + good.replace( hashlib.sha256(b"s001.txt").hexdigest(), hashlib.sha256(b"s001.txt").hexdigest().upper()), "patches s001 and s002 override the same key 00c0ffee0badf00d": ok + good + shader_patch("s002"), @@ -253,6 +264,11 @@ def test_shader_patches(self): with self.assertRaises(ValueError) as caught: patch_manifest.parse(case) self.assertIn(message, str(caught.exception)) + # A device name only as a prefix, a space inside a name and a leading dot are still file names. + for name in ("console.txt", "nulls.cso", "a b.txt", "com10.txt", "conin.txt", ".s001.txt"): + with self.subTest(name): + _, patches = patch_manifest.parse(ok + good.replace('file = "s001.txt"', f"file = '{name}'")) + self.assertEqual(patches[-1]["files"][0]["file"], name) def test_shader_revision_forms_match_the_runtime(self): # The runtime's current revision of each pipeline has the loader's form, so a bump (a new ) still loads. diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 5ef8990b74..54c822f8f8 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -40,6 +40,10 @@ SHA256 = re.compile(r"[0-9a-f]{64}") HEX = re.compile(r"(?:[0-9a-f]{2})+") KEY = re.compile(r"[0-9a-f]{16}") +# Names Windows opens as a device instead of a file in the directory, alone or before an extension (Microsoft, +# "Naming Files, Paths, and Namespaces"). Matched against the part before the first dot, trailing spaces dropped. +DEVICE = re.compile(r"(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)", + re.IGNORECASE) COMMON = {"id", "kind", "why", "remove_when"} # Every key of a kind is required. hook and data get their tables with their stages. KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} @@ -77,10 +81,20 @@ def _sha256(value, where): def _file_name(value, where): - """A bare file name, for a later consumer to resolve in the manifest's directory.""" + """A bare file name, for a later consumer to resolve in the manifest's directory. + + That consumer is the runtime, which runs on Windows, so a name that Windows would not resolve to a file of that + name in the directory is refused too: one it cannot hold, one whose trailing dot or space it drops, a device. + """ name = _text(value, where) if any(c in name for c in "/\\:") or name in (".", ".."): raise ValueError(f"{where} {name!r} must be a bare file name, without a directory, drive or '..'") + if any(c in '<>"|?*' for c in name) or any(ord(c) < 32 for c in name): + raise ValueError(f"{where} {name!r} has a character a Windows file name cannot hold") + if name.endswith((".", " ")): + raise ValueError(f"{where} {name!r} ends in a dot or a space, which Windows drops") + if DEVICE.fullmatch(name.split(".", 1)[0].rstrip(" ")): + raise ValueError(f"{where} {name!r} is a Windows device name") return name From 2d890437d53e09baf0ac22427e4969f13d9a2062 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:52:06 +1000 Subject: [PATCH 14/14] loader: accept the .cs.hlsl a compute key may need (#3119) Since #3006 the runtime's compute loader also looks for .cs.hlsl when the key's .txt has no native line, and refuses the translation without it. List it as a compute translation file, optional like mesh86's .ps.cso, since the loader does not read the .txt. Pin it beside the runtime's unmarked-manifest check. --- docs/experiments/patch-manifests.md | 8 +++++--- tests/patch_manifest_check.py | 20 ++++++++++++++------ tools/patch_manifest.py | 6 ++++-- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index 93bf1c540a..c755a9a746 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -54,9 +54,11 @@ files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, | `pipeline` | `revision` form | Files the runtime reads | Required | |---|---|---|---| | `graphics` | `x2w-startup-shader-` | `.txt`, `.vs.cso`, `.ps.cso` | all three | -| `compute` | `x2w-startup-shader-cs` | `.txt`, `.cs.cso` | both | +| `compute` | `x2w-startup-shader-cs` | `.txt`, `.cs.cso`, `.cs.hlsl` | `.txt`, `.cs.cso` | | `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | +The runtime looks for a compute key's `.cs.hlsl`, the Python translator's output, only when its `.txt` has no `native` line, and reads a mesh86 key's `.ps.cso` only for a request with a pixel shader. The loader does not read the `.txt` or the request, so both stay optional. + - **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. - **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. That consumer is the runtime, which runs on Windows, so a name Windows would not open as a file of that name in the directory is refused too: one with `<`, `>`, `"`, `|`, `?`, `*` or a control character, one ending in a dot or a space (Windows drops them), and a device name (`CON`, `PRN`, `AUX`, `NUL`, `COM0`-`COM9`, `LPT0`-`LPT9`, `COM` and `LPT` with a superscript 1 to 3, `CONIN$`, `CONOUT$`) in any case, alone or before an extension, as Microsoft's "Naming Files, Paths, and Namespaces" lists them. `sha256` is lowercase. - **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. @@ -83,8 +85,8 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Their ids follow neither the RVA order nor its reverse, so no order by id is an order by address. Two patches that share one byte are refused as an overlap, in either order. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. -- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, a `file` with `*`, `?`, `<`, `>`, `|`, `"`, a tab or U+0001, `s001.txt.` and `s001.txt ` (trailing space), the device names `NUL`, `CON.txt`, `Com1`, `nul .txt`, `CONIN$`, `conout$.txt`, `COM` + U+00B9 and `lpt` + U+00B3 + `.cso`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. -- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and mesh86's `.ps.cso` is the only optional one, read only for a request with a pixel shader. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, compute with and without its `.cs.hlsl`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, a `file` with `*`, `?`, `<`, `>`, `|`, `"`, a tab or U+0001, `s001.txt.` and `s001.txt ` (trailing space), the device names `NUL`, `CON.txt`, `Com1`, `nul .txt`, `CONIN$`, `conout$.txt`, `COM` + U+00B9 and `lpt` + U+00B3 + `.cso`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and the optional ones are mesh86's `.ps.cso`, read only for a request with a pixel shader, and compute's `.cs.hlsl`, looked for only when the `.txt` has no `native` line (`NativeComputeOutput::unmarked`). - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 3e0570a9a3..8c353bc7d3 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -192,13 +192,15 @@ def test_load_data_gates_the_bytes_given(self): def test_shader_patches(self): sha = self.digest ok = manifest_text(sha, self.original) - # Accepted beside a memory patch: each pipeline with its required files, mesh86 also with its pixel shader. + # Accepted beside a memory patch: each pipeline with its required files, mesh86 also with its pixel shader + # and compute also with its Python translator's HLSL. text = (ok + shader_patch("s001") + shader_patch("s002", "0123456789abcdef", "graphics") + shader_patch("s003", "fedcba9876543210", "mesh86") - + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso"))) + + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso")) + + shader_patch("s005", "0000000000000002", "compute", exts=(".txt", ".cs.cso", ".cs.hlsl"))) target, patches = patch_manifest.parse(text) self.assertEqual([(p["id"], p["kind"]) for p in patches], [("p001", "memory")] + [ - (pid, "shader") for pid in ("s001", "s002", "s003", "s004")]) + (pid, "shader") for pid in ("s001", "s002", "s003", "s004", "s005")]) s001 = patches[1] self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), ("00c0ffee0badf00d", "compute", "x2w-startup-shader-12cs")) @@ -206,11 +208,12 @@ def test_shader_patches(self): {"ext": ".txt", "file": "s001.txt", "sha256": hashlib.sha256(b"s001.txt").hexdigest()}, {"ext": ".cs.cso", "file": "s001.cs.cso", "sha256": hashlib.sha256(b"s001.cs.cso").hexdigest()}]) self.assertEqual([f["ext"] for f in patches[4]["files"]], [".mesh86.txt", ".ms.cso", ".ps.cso"]) + self.assertEqual([f["ext"] for f in patches[5]["files"]], [".txt", ".cs.cso", ".cs.hlsl"]) # The CLI lists shader ids with the memory ones. self.manifest.write_text(text, encoding="utf-8", newline="\n") result = self.cli(self.input) self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004"]) + self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004", "s005"]) good = shader_patch() cases = { "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), @@ -231,7 +234,7 @@ def test_shader_patches(self): "files[0] has unknown keys: size": ok + good.replace('{ ext = ".txt",', '{ size = 1, ext = ".txt",'), "files[1] is missing: sha256": ok + good.replace( f', sha256 = "{hashlib.sha256(b"s001.cs.cso").hexdigest()}"', ""), - "files[1] ext '.vs.cso' is not a compute translation file (.txt, .cs.cso)": + "files[1] ext '.vs.cso' is not a compute translation file (.txt, .cs.cso, .cs.hlsl)": ok + shader_patch(exts=(".txt", ".vs.cso")), "s001 lists .txt twice": ok + shader_patch(exts=(".txt", ".cs.cso", ".txt")), "s001 compute override is missing: .cs.cso": ok + shader_patch(exts=(".txt",)), @@ -288,7 +291,8 @@ def test_shader_revision_forms_match_the_runtime(self): def test_shader_files_match_the_runtime(self): # The translation files each pipeline's loader in the runtime reads for one key: cache_path(..., L"", key, ext) - # and mesh86's load_stage(ext, ...). mesh86 reads its .ps.cso only for a request with a pixel shader. + # and mesh86's load_stage(ext, ...). mesh86 reads its .ps.cso only for a request with a pixel shader, and + # compute looks for its .cs.hlsl only when the .txt has no native line: neither is required. reads = re.compile(r'(?:cache_path\(\w+, L"", [\w.]+, |load_stage\()L"(\.[a-z0-9.]+)"') sources = {"graphics": "d3d12_draw.inl", "compute": "d3d12_compute_dispatch.inl", "mesh86": "mesh86_cache.inl"} self.assertEqual(set(sources), set(patch_manifest.PIPELINES)) @@ -300,6 +304,10 @@ def test_shader_files_match_the_runtime(self): self.assertIn('(!request.ps.empty() && !load_stage(L".ps.cso", ps))', mesh86) self.assertEqual(set(patch_manifest.PIPELINES["mesh86"][1]) - set(patch_manifest.PIPELINES["mesh86"][2]), {".ps.cso"}) + compute = (ROOT / "src/startup_stubs/d3d12_compute_dispatch.inl").read_text(encoding="utf-8") + self.assertIn("if (output == x2w::NativeComputeOutput::unmarked) {", compute) + self.assertEqual(set(patch_manifest.PIPELINES["compute"][1]) - set(patch_manifest.PIPELINES["compute"][2]), + {".cs.hlsl"}) def test_deep_nesting_is_refused(self): def nested(depth): diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 54c822f8f8..b57bb465f2 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -49,10 +49,12 @@ KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} # Shader patches, per pipeline: the form of the runtime's key revision (src/startup_stubs/d3d12_draw.inl and # mesh86_cache.inl; is the number each revision bump raises), the translation files the runtime reads for one -# key, and the ones without which it has no translation. A later consumer must check which is current. +# key, and the ones without which it has no translation. A later consumer must check which is current. compute +# also needs .cs.hlsl when its .txt has no native line, and mesh86 reads .ps.cso only for a request with a pixel +# shader; this loader reads neither, so both stay optional. PIPELINES = { "graphics": ("x2w-startup-shader-", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), - "compute": ("x2w-startup-shader-cs", (".txt", ".cs.cso"), (".txt", ".cs.cso")), + "compute": ("x2w-startup-shader-cs", (".txt", ".cs.cso", ".cs.hlsl"), (".txt", ".cs.cso")), "mesh86": ("x2w-startup-mesh-86-", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), } REVISIONS = {name: re.compile(re.escape(form).replace("", "[1-9][0-9]*"))