shader: inventory candidate programs for a named SGD5 effect #310

Merged
Vonsek merged 2 commits from upstream-pr/315 into main 2026-11-21 21:59:59 +00:00
Vonsek commented 2026-11-21 21:49:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T21:49:42Z.


Change

Fixes #307. Given an independently located SGD5 group, its program-array offset, and one named effect record, report each referenced program in stored order. The JSON includes the stored group, group-local index, program name, DXIL shader kind and decoded-container SHA-256. Repeated names can identify different containers. The stored VS group can include a mesh shader.

Verification

Tested on Windows with Python 3.12.10 at a08f34d9b8d3aa15642d151c038156f6f3bfd9e1.

  • python -B tests/sgd5_effects_check.py -v passed both test methods. The CLI test initially failed because the command was missing. A subsequent regression claimed a second effect while the selected record occupied the entire remaining group. It was accepted before the count check accounted for the selected span and rejected afterward.
  • cmake --fresh --preset dev -DINTAKE_PYTHON=<worktree-python> and ctest --preset dev --no-tests=error -R "^(sgd5_effect_candidates|docs_links)$" -V passed. The documentation check covered 67 links in 10 files.
  • python -B tools/sgd5_effects.py archive.bin EFFECT --group GROUP_START GROUP_END --arrays ARRAY_OFFSET --record EFFECT_START EFFECT_END on two independently located local effects reported 5 and 81 candidates, including 2 and 41 pixel candidates respectively. All pixel ordinals and container digests agreed with a separate decode.

Evidence and follow-up

The tests generate their SGD5 records, raw-DEFLATE wrappers and minimal DXBC/DXIL headers from repository-licensed Python source. Controls cover duplicate names across and within groups, reversed candidate order, neighboring records, an out-of-group index, truncated framing and a byte budget verified before payload access. An instrumented reader limits individual reads to seven bytes and rejects reads from an unselected compressed payload.

Effect bounds and the table offset come from the caller. The parser treats the intervening technique/state bytes as opaque. Determining which candidate a draw selects still requires pass-selection evidence. README entry · CLI and sample measurements · Public SGD5 program table · Related SGD2 effect layout

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.

AI-assisted contribution.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6534831555 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T21:49:42Z. --- ## Change Fixes #307. Given an independently located SGD5 group, its program-array offset, and one named effect record, report each referenced program in stored order. The JSON includes the stored group, group-local index, program name, DXIL shader kind and decoded-container SHA-256. Repeated names can identify different containers. The stored VS group can include a mesh shader. ## Verification Tested on Windows with Python 3.12.10 at `a08f34d9b8d3aa15642d151c038156f6f3bfd9e1`. - `python -B tests/sgd5_effects_check.py -v` passed both test methods. The CLI test initially failed because the command was missing. A subsequent regression claimed a second effect while the selected record occupied the entire remaining group. It was accepted before the count check accounted for the selected span and rejected afterward. - `cmake --fresh --preset dev -DINTAKE_PYTHON=<worktree-python>` and `ctest --preset dev --no-tests=error -R "^(sgd5_effect_candidates|docs_links)$" -V` passed. The documentation check covered 67 links in 10 files. - `python -B tools/sgd5_effects.py archive.bin EFFECT --group GROUP_START GROUP_END --arrays ARRAY_OFFSET --record EFFECT_START EFFECT_END` on two independently located local effects reported 5 and 81 candidates, including 2 and 41 pixel candidates respectively. All pixel ordinals and container digests agreed with a separate decode. ## Evidence and follow-up The tests generate their SGD5 records, raw-DEFLATE wrappers and minimal DXBC/DXIL headers from repository-licensed Python source. Controls cover duplicate names across and within groups, reversed candidate order, neighboring records, an out-of-group index, truncated framing and a byte budget verified before payload access. An instrumented reader limits individual reads to seven bytes and rejects reads from an unselected compressed payload. Effect bounds and the table offset come from the caller. The parser treats the intervening technique/state bytes as opaque. Determining which candidate a draw selects still requires pass-selection evidence. [README entry](https://github.com/Vonsek/Xbox2Windows/blob/a08f34d9b8d3aa15642d151c038156f6f3bfd9e1/README.md#choose-an-experiment) · [CLI and sample measurements](https://github.com/Vonsek/Xbox2Windows/blob/a08f34d9b8d3aa15642d151c038156f6f3bfd9e1/docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) · [Public SGD5 program table](https://github.com/rpatty-dev/PercyStar/blob/1b710c5349ef1911d94092f19173e9813dfb300c/src/sgd5.rs#L208-L238) · [Related SGD2 effect layout](https://github.com/Kalmarv/rage-engine-formats/blob/91e5abb68476709fac80f256bc64f928c6fc2d19/src/sgd2.rs#L20-L32) ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets. AI-assisted contribution.
upstream-sync closed this pull request 2026-11-24 06:42:22 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 06:42:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T21:54:53Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a08f34d9b8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6008446659 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315#pullrequestreview-6008446659). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T21:54:53Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `a08f34d9b8` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
Vonsek commented 2026-11-24 06:42:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T21:56:57Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6008461262 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315#pullrequestreview-6008461262). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T21:56:57Z. **Review:** COMMENTED --- _No description provided._
chatgpt-codex-connector[bot commented 2026-11-24 06:48:04 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T21:49:52Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T21:54:55.551670Z a08f34d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7069749914 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315#issuecomment-7069749914). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T21:49:52Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"a08f34d9b8d3aa15642d151c038156f6f3bfd9e1","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-21T21:54:55.551670Z">2026-11-21T21:54:55.551670Z</relative-time> | `a08f34d` | PR opened | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
Vonsek commented 2026-11-24 06:48:06 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T22:00:22Z.


@codex review

Please recheck dc21141ee0, including the padded DXIL part and its two adjacent size controls. All three CI jobs passed.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7069871687 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315#issuecomment-7069871687). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T22:00:22Z. --- @codex review Please recheck dc21141ee0567c25745439a6c0840a3c1b1d572e, including the padded DXIL part and its two adjacent size controls. All three CI jobs passed.
chatgpt-codex-connector[bot commented 2026-11-24 06:50:36 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T21:54:53Z.

Code review location: tools/sgd5_effects.py; line 102

@@ -0,0 +1,174 @@
+"""Inventory program candidates from an explicitly located SGD5 effect record."""
+import argparse
+from dataclasses import asdict, dataclass
+import hashlib
+import json
+from pathlib import Path
+import struct
+from typing import BinaryIO
+import zlib
+
+from paged_resource import PagedResource, Segment
+from resource_inventory import parts
+
+
+GROUPS = ("VS", "PS", "GS", "DS", "HS", "CS")
+
+
+class Cursor:
+    def __init__(self, view: PagedResource, start: int, end: int):
+        self.view = view
+        self.pos = start
+        self.end = end
+
+    def skip(self, size: int) -> int:
+        start = self.pos
+        if size > self.end - start:
+            raise ValueError("SGD5 field exceeds supplied range")
+        self.pos += size
+        return start
+
+    def read(self, size: int) -> bytes:
+        return self.view.read(self.skip(size), size)
+
+    def word(self) -> int:
+        return int.from_bytes(self.read(4), "little")
+
+    def name(self) -> str:
+        length = self.read(1)[0]
+        raw = self.read(length)
+        if len(raw) < 2 or raw[-1] or not all(32 <= c < 127 for c in raw[:-1]):
+            raise ValueError("Invalid length-prefixed SGD5 name")
+        return raw[:-1].decode("ascii")
+
+
+@dataclass(frozen=True)
+class Program:
+    name: str
+    offset: int
+    stored: int
+    decoded: int
+
+
+def read_program(cursor: Cursor) -> Program:
+    name = cursor.name()
+    cursor.skip(1)
+    size = cursor.word()
+    magic, repeated, decoded = struct.unpack("<3I", cursor.read(12))
+    if magic != 0xddce7 or size != repeated or not 12 < size <= 8 << 20 or not 32 <= decoded <= 16 << 20:
+        raise ValueError("Invalid bounded SGD5 compressed container")
+    offset = cursor.skip(size - 12)
+    cursor.skip(152)  # Hash and root signature.
+    reflection = cursor.word()
+    registers, buffers, _, repeated = struct.unpack("<4H", cursor.read(8))
+    if reflection != repeated or reflection != 9 + 24 * (registers + buffers):
+        raise ValueError("Invalid SGD5 reflection block length")
+    cursor.skip(reflection - 8)
+    return Program(name, offset, size - 12, decoded)
+
+
+def validate_name_block(tail: bytes) -> None:
+    # The size word of the final NUL-delimited name block must consume the
+    # supplied record exactly. Other state/technique bytes are opaque.
+    if len(tail) < 5 or tail[-1]:
+        raise ValueError("Missing trailing SGD5 name block")
+    suffix = len(tail)
+    while suffix and (tail[suffix - 1] == 0 or 32 <= tail[suffix - 1] < 127):
+        suffix -= 1
+    starts = sum(tail[i + 4] == 0 and struct.unpack_from("<I", tail, i)[0] == len(tail) - i - 4
+                 for i in range(max(0, suffix - 4), len(tail) - 4))
+    if starts != 1:
+        raise ValueError("Expected one sized name block ending at the supplied record boundary")
+
+
+@dataclass(frozen=True)
+class Candidate:
+    group: str
+    index: int
+    name: str
+    dxil_kind: int
+    container_sha256: str
+
+
+def inspect_container(view: PagedResource, program: Program, group: str, index: int) -> Candidate:
+    decoder = zlib.decompressobj(-15)
+    try:
+        blob = decoder.decompress(view.read(program.offset, program.stored), program.decoded + 1)
+    except zlib.error as exc:
+        raise ValueError("Invalid compressed SGD5 candidate") from exc
+    if not decoder.eof or decoder.unused_data or len(blob) != program.decoded:
+        raise ValueError("Candidate container disagrees with its declared extents")
+    dxil = parts(blob).get(b"DXIL", b"")
+    if len(dxil) < 24 or dxil[8:12] != b"DXIL" or struct.unpack_from("<I", dxil, 4)[0] * 4 != len(dxil):

P2 Badge Allow DXIL parts to extend beyond the declared program

For a DXIL part containing trailing padding or extension data after the program's declared SizeInUint32 extent, this equality check rejects the candidate and aborts the entire effect inventory. The existing resource_inventory.dxil_program and dxil_retarget.unpack_dxil_program validators allow 4 * words <= len(program). Appending four bytes to the synthetic DXIL part while updating its part/container extents is accepted by both shared validators but rejected here. Validate that the declared program fits inside the part rather than requiring it to occupy the whole part.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4655179478 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315#discussion_r4655179478). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T21:54:53Z. **Code review location:** `tools/sgd5_effects.py`; line 102 ~~~~diff @@ -0,0 +1,174 @@ +"""Inventory program candidates from an explicitly located SGD5 effect record.""" +import argparse +from dataclasses import asdict, dataclass +import hashlib +import json +from pathlib import Path +import struct +from typing import BinaryIO +import zlib + +from paged_resource import PagedResource, Segment +from resource_inventory import parts + + +GROUPS = ("VS", "PS", "GS", "DS", "HS", "CS") + + +class Cursor: + def __init__(self, view: PagedResource, start: int, end: int): + self.view = view + self.pos = start + self.end = end + + def skip(self, size: int) -> int: + start = self.pos + if size > self.end - start: + raise ValueError("SGD5 field exceeds supplied range") + self.pos += size + return start + + def read(self, size: int) -> bytes: + return self.view.read(self.skip(size), size) + + def word(self) -> int: + return int.from_bytes(self.read(4), "little") + + def name(self) -> str: + length = self.read(1)[0] + raw = self.read(length) + if len(raw) < 2 or raw[-1] or not all(32 <= c < 127 for c in raw[:-1]): + raise ValueError("Invalid length-prefixed SGD5 name") + return raw[:-1].decode("ascii") + + +@dataclass(frozen=True) +class Program: + name: str + offset: int + stored: int + decoded: int + + +def read_program(cursor: Cursor) -> Program: + name = cursor.name() + cursor.skip(1) + size = cursor.word() + magic, repeated, decoded = struct.unpack("<3I", cursor.read(12)) + if magic != 0xddce7 or size != repeated or not 12 < size <= 8 << 20 or not 32 <= decoded <= 16 << 20: + raise ValueError("Invalid bounded SGD5 compressed container") + offset = cursor.skip(size - 12) + cursor.skip(152) # Hash and root signature. + reflection = cursor.word() + registers, buffers, _, repeated = struct.unpack("<4H", cursor.read(8)) + if reflection != repeated or reflection != 9 + 24 * (registers + buffers): + raise ValueError("Invalid SGD5 reflection block length") + cursor.skip(reflection - 8) + return Program(name, offset, size - 12, decoded) + + +def validate_name_block(tail: bytes) -> None: + # The size word of the final NUL-delimited name block must consume the + # supplied record exactly. Other state/technique bytes are opaque. + if len(tail) < 5 or tail[-1]: + raise ValueError("Missing trailing SGD5 name block") + suffix = len(tail) + while suffix and (tail[suffix - 1] == 0 or 32 <= tail[suffix - 1] < 127): + suffix -= 1 + starts = sum(tail[i + 4] == 0 and struct.unpack_from("<I", tail, i)[0] == len(tail) - i - 4 + for i in range(max(0, suffix - 4), len(tail) - 4)) + if starts != 1: + raise ValueError("Expected one sized name block ending at the supplied record boundary") + + +@dataclass(frozen=True) +class Candidate: + group: str + index: int + name: str + dxil_kind: int + container_sha256: str + + +def inspect_container(view: PagedResource, program: Program, group: str, index: int) -> Candidate: + decoder = zlib.decompressobj(-15) + try: + blob = decoder.decompress(view.read(program.offset, program.stored), program.decoded + 1) + except zlib.error as exc: + raise ValueError("Invalid compressed SGD5 candidate") from exc + if not decoder.eof or decoder.unused_data or len(blob) != program.decoded: + raise ValueError("Candidate container disagrees with its declared extents") + dxil = parts(blob).get(b"DXIL", b"") + if len(dxil) < 24 or dxil[8:12] != b"DXIL" or struct.unpack_from("<I", dxil, 4)[0] * 4 != len(dxil): ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Allow DXIL parts to extend beyond the declared program** For a DXIL part containing trailing padding or extension data after the program's declared `SizeInUint32` extent, this equality check rejects the candidate and aborts the entire effect inventory. The existing `resource_inventory.dxil_program` and `dxil_retarget.unpack_dxil_program` validators allow `4 * words <= len(program)`. Appending four bytes to the synthetic DXIL part while updating its part/container extents is accepted by both shared validators but rejected here. Validate that the declared program fits inside the part rather than requiring it to occupy the whole part. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Vonsek commented 2026-11-24 06:50:36 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T21:56:57Z.

Code review location: tools/sgd5_effects.py; line 102

@@ -0,0 +1,174 @@
+"""Inventory program candidates from an explicitly located SGD5 effect record."""
+import argparse
+from dataclasses import asdict, dataclass
+import hashlib
+import json
+from pathlib import Path
+import struct
+from typing import BinaryIO
+import zlib
+
+from paged_resource import PagedResource, Segment
+from resource_inventory import parts
+
+
+GROUPS = ("VS", "PS", "GS", "DS", "HS", "CS")
+
+
+class Cursor:
+    def __init__(self, view: PagedResource, start: int, end: int):
+        self.view = view
+        self.pos = start
+        self.end = end
+
+    def skip(self, size: int) -> int:
+        start = self.pos
+        if size > self.end - start:
+            raise ValueError("SGD5 field exceeds supplied range")
+        self.pos += size
+        return start
+
+    def read(self, size: int) -> bytes:
+        return self.view.read(self.skip(size), size)
+
+    def word(self) -> int:
+        return int.from_bytes(self.read(4), "little")
+
+    def name(self) -> str:
+        length = self.read(1)[0]
+        raw = self.read(length)
+        if len(raw) < 2 or raw[-1] or not all(32 <= c < 127 for c in raw[:-1]):
+            raise ValueError("Invalid length-prefixed SGD5 name")
+        return raw[:-1].decode("ascii")
+
+
+@dataclass(frozen=True)
+class Program:
+    name: str
+    offset: int
+    stored: int
+    decoded: int
+
+
+def read_program(cursor: Cursor) -> Program:
+    name = cursor.name()
+    cursor.skip(1)
+    size = cursor.word()
+    magic, repeated, decoded = struct.unpack("<3I", cursor.read(12))
+    if magic != 0xddce7 or size != repeated or not 12 < size <= 8 << 20 or not 32 <= decoded <= 16 << 20:
+        raise ValueError("Invalid bounded SGD5 compressed container")
+    offset = cursor.skip(size - 12)
+    cursor.skip(152)  # Hash and root signature.
+    reflection = cursor.word()
+    registers, buffers, _, repeated = struct.unpack("<4H", cursor.read(8))
+    if reflection != repeated or reflection != 9 + 24 * (registers + buffers):
+        raise ValueError("Invalid SGD5 reflection block length")
+    cursor.skip(reflection - 8)
+    return Program(name, offset, size - 12, decoded)
+
+
+def validate_name_block(tail: bytes) -> None:
+    # The size word of the final NUL-delimited name block must consume the
+    # supplied record exactly. Other state/technique bytes are opaque.
+    if len(tail) < 5 or tail[-1]:
+        raise ValueError("Missing trailing SGD5 name block")
+    suffix = len(tail)
+    while suffix and (tail[suffix - 1] == 0 or 32 <= tail[suffix - 1] < 127):
+        suffix -= 1
+    starts = sum(tail[i + 4] == 0 and struct.unpack_from("<I", tail, i)[0] == len(tail) - i - 4
+                 for i in range(max(0, suffix - 4), len(tail) - 4))
+    if starts != 1:
+        raise ValueError("Expected one sized name block ending at the supplied record boundary")
+
+
+@dataclass(frozen=True)
+class Candidate:
+    group: str
+    index: int
+    name: str
+    dxil_kind: int
+    container_sha256: str
+
+
+def inspect_container(view: PagedResource, program: Program, group: str, index: int) -> Candidate:
+    decoder = zlib.decompressobj(-15)
+    try:
+        blob = decoder.decompress(view.read(program.offset, program.stored), program.decoded + 1)
+    except zlib.error as exc:
+        raise ValueError("Invalid compressed SGD5 candidate") from exc
+    if not decoder.eof or decoder.unused_data or len(blob) != program.decoded:
+        raise ValueError("Candidate container disagrees with its declared extents")
+    dxil = parts(blob).get(b"DXIL", b"")
+    if len(dxil) < 24 or dxil[8:12] != b"DXIL" or struct.unpack_from("<I", dxil, 4)[0] * 4 != len(dxil):

Reproduced on a08f34d with an eight-word program inside a nine-word DXIL part. Both resource_inventory.dxil_program and dxil_retarget.unpack_dxil_program accepted it while the effect inventory rejected it. Commit dc21141 checks the payload end against the declared program end and the program end against the part end. The padded case now retains its full-container digest. Declaring seven words truncates the payload and ten words overruns the part; both are rejected. The two local effect runs still report 5 and 81 candidates, including 2 and 41 pixel programs with independently matching digests. Their framed payloads use a different signature from desktop LLVM bitcode, so the inventory validates their extents without requiring that signature. Direct Python (three tests) and the focused CTest run passed.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4655189750 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/315#discussion_r4655189750). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T21:56:57Z. **Code review location:** `tools/sgd5_effects.py`; line 102 ~~~~diff @@ -0,0 +1,174 @@ +"""Inventory program candidates from an explicitly located SGD5 effect record.""" +import argparse +from dataclasses import asdict, dataclass +import hashlib +import json +from pathlib import Path +import struct +from typing import BinaryIO +import zlib + +from paged_resource import PagedResource, Segment +from resource_inventory import parts + + +GROUPS = ("VS", "PS", "GS", "DS", "HS", "CS") + + +class Cursor: + def __init__(self, view: PagedResource, start: int, end: int): + self.view = view + self.pos = start + self.end = end + + def skip(self, size: int) -> int: + start = self.pos + if size > self.end - start: + raise ValueError("SGD5 field exceeds supplied range") + self.pos += size + return start + + def read(self, size: int) -> bytes: + return self.view.read(self.skip(size), size) + + def word(self) -> int: + return int.from_bytes(self.read(4), "little") + + def name(self) -> str: + length = self.read(1)[0] + raw = self.read(length) + if len(raw) < 2 or raw[-1] or not all(32 <= c < 127 for c in raw[:-1]): + raise ValueError("Invalid length-prefixed SGD5 name") + return raw[:-1].decode("ascii") + + +@dataclass(frozen=True) +class Program: + name: str + offset: int + stored: int + decoded: int + + +def read_program(cursor: Cursor) -> Program: + name = cursor.name() + cursor.skip(1) + size = cursor.word() + magic, repeated, decoded = struct.unpack("<3I", cursor.read(12)) + if magic != 0xddce7 or size != repeated or not 12 < size <= 8 << 20 or not 32 <= decoded <= 16 << 20: + raise ValueError("Invalid bounded SGD5 compressed container") + offset = cursor.skip(size - 12) + cursor.skip(152) # Hash and root signature. + reflection = cursor.word() + registers, buffers, _, repeated = struct.unpack("<4H", cursor.read(8)) + if reflection != repeated or reflection != 9 + 24 * (registers + buffers): + raise ValueError("Invalid SGD5 reflection block length") + cursor.skip(reflection - 8) + return Program(name, offset, size - 12, decoded) + + +def validate_name_block(tail: bytes) -> None: + # The size word of the final NUL-delimited name block must consume the + # supplied record exactly. Other state/technique bytes are opaque. + if len(tail) < 5 or tail[-1]: + raise ValueError("Missing trailing SGD5 name block") + suffix = len(tail) + while suffix and (tail[suffix - 1] == 0 or 32 <= tail[suffix - 1] < 127): + suffix -= 1 + starts = sum(tail[i + 4] == 0 and struct.unpack_from("<I", tail, i)[0] == len(tail) - i - 4 + for i in range(max(0, suffix - 4), len(tail) - 4)) + if starts != 1: + raise ValueError("Expected one sized name block ending at the supplied record boundary") + + +@dataclass(frozen=True) +class Candidate: + group: str + index: int + name: str + dxil_kind: int + container_sha256: str + + +def inspect_container(view: PagedResource, program: Program, group: str, index: int) -> Candidate: + decoder = zlib.decompressobj(-15) + try: + blob = decoder.decompress(view.read(program.offset, program.stored), program.decoded + 1) + except zlib.error as exc: + raise ValueError("Invalid compressed SGD5 candidate") from exc + if not decoder.eof or decoder.unused_data or len(blob) != program.decoded: + raise ValueError("Candidate container disagrees with its declared extents") + dxil = parts(blob).get(b"DXIL", b"") + if len(dxil) < 24 or dxil[8:12] != b"DXIL" or struct.unpack_from("<I", dxil, 4)[0] * 4 != len(dxil): ~~~~ --- Reproduced on a08f34d with an eight-word program inside a nine-word DXIL part. Both resource_inventory.dxil_program and dxil_retarget.unpack_dxil_program accepted it while the effect inventory rejected it. Commit dc21141 checks the payload end against the declared program end and the program end against the part end. The padded case now retains its full-container digest. Declaring seven words truncates the payload and ten words overruns the part; both are rejected. The two local effect runs still report 5 and 81 candidates, including 2 and 41 pixel programs with independently matching digests. Their framed payloads use a different signature from desktop LLVM bitcode, so the inventory validates their extents without requiring that signature. Direct Python (three tests) and the focused CTest run passed.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!310
No description provided.