diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index c5ab890304..c755a9a746 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -22,14 +22,47 @@ 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. -- **Kinds:** `kind` must be a string, and only `memory` is defined. `hook` and `data` are refused as `not supported` until their stages land. +- **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 `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` 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`, `.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. + Input-specific manifests stay local under `game-files/patches/`, which is gitignored. Do not publish them or the hashes in them. @@ -45,11 +78,17 @@ 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. 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`, 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:** | Change | Result | @@ -59,6 +98,48 @@ 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`. | + | 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. | + | 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. | + | `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. | + | 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. | 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, `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. + +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 8f2f7477ad..8c353bc7d3 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -1,7 +1,9 @@ """Schema, loader and hash-gate controls for tools/patch_manifest.py on a synthetic PE32+.""" import hashlib +import json from pathlib import Path +import re import subprocess import sys import tempfile @@ -18,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): @@ -35,6 +40,39 @@ 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] + exts = patch_manifest.PIPELINES[pipeline][2] if exts is None else 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}" +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() @@ -59,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) @@ -69,6 +110,30 @@ 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. + # 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 (("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], + [("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): + 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 @@ -85,8 +150,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(): @@ -107,6 +177,161 @@ 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) + # 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("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", "s005")]) + s001 = patches[1] + self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), + ("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()}]) + 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", "s005"]) + 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"), + "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"), + "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( + f', sha256 = "{hashlib.sha256(b"s001.cs.cso").hexdigest()}"', ""), + "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",)), + "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", "..", ".")}, + # 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"), + "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)) + # 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. + # 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(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_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 + # 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)) + 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"}) + 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): + 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)) + # 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)) + 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..b57bb465f2 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,26 @@ 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"}} +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. 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", ".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]*")) + for name, (form, _, _) in PIPELINES.items()} def _keys(table, keys, where): @@ -54,9 +82,60 @@ 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. + + 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 + + +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)}") + 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 = {} + 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": _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)}") + return {"key": key, "pipeline": pipeline, "revision": revision, "files": list(files.values())} + + 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") @@ -73,6 +152,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)") @@ -105,6 +191,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}