Merge pull request #882 from quartz-heron-58/bl5-corpus-count

fssm_unpack: count containers and programs apart, per stage (BL-5)
This commit is contained in:
aslan2142
2026-11-24 19:24:26 +01:00
committed by GitHub
4 changed files with 137 additions and 7 deletions

View File

@ -109,6 +109,40 @@ as scalar data. The translator keeps its existing behavior when the source is ab
or the library code has another strict wave64 marker. Synthetic cases are in
`tests/semantic/test_fspx_wave_size.py`.
### Containers and programs
The carved corpus is counted two ways, and the two numbers are both right (BL-5 in
[boot_leads.md](boot_leads.md)):
| Count | What it counts | 1.0.2.1 |
|---|---|---|
| Containers | carved `DXBC` files, one row of the carve index each | 26,503 |
| Programs | tag-`0x0D` payloads (`XBCH` → `FSSM`) inside them | 26,698 |
The difference is 195 containers that hold two payloads. All 195 are vertex shaders; every other container holds
one:
| Stage | Containers | Payloads | Containers with two |
|---|---|---|---|
| `vs` | 2,236 | 2,431 | 195 |
| `ms` | 9,282 | 9,282 | 0 |
| `ps` | 12,101 | 12,101 | 0 |
| `gs` | 195 | 195 | 0 |
| `cs` | 2,689 | 2,689 | 0 |
So 195 is the geometry-shader count because of what the second payload is, not because geometry shaders are
counted twice or missed: it is the same vertex shader built for the export-shader stage of a legacy
geometry-shader pipeline ([design.md](design.md), "VS as ES (two-payload VS containers)"). The carve skips
nothing here.
`tools/fssm_unpack.py` prints these counts after it unpacks (`programs: … payloads in … containers`, then one
line per stage when it is given the carve index, whose `stage` field it reads). It still writes one program per
container, the last payload by default, so the 195 export-stage variants are not translated; which payload a
geometry-shader pipeline selects is open ([fssm_crosscheck.md](fssm_crosscheck.md) §6).
Measured on an own 1.0.2.1 copy from the build's `index.json` and `fssm_index.json`. The synthetic case is
`test_program_counts_separate_containers_from_payloads` in `tests/test_fssm_unpack.py`.
## 4. Tool
```sh

View File

@ -20,6 +20,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import fssm_unpack # noqa: E402
import shader_stage_manifest # noqa: E402
TOOL = os.path.join(ROOT, "tools", "fssm_unpack.py")
S_ENDPGM = b"\x00\x00\x81\xbf"
@ -570,6 +571,60 @@ class TestMainDirectoryProcessing(unittest.TestCase):
self.assertEqual(os.listdir(os.path.join(self.src, "fssm")), ["current.fssm"])
self.assertTrue(os.path.isfile(os.path.join(self.src, "obsolete.dxbc")))
def test_program_counts_separate_containers_from_payloads(self):
# BL-5: a container is one carved file, a program is one tag-0x0D payload. Five containers, six payloads:
# the vertex shader carries two (its ES and VS hardware variants), as 195 of the corpus' containers do.
es = make_fssm(version=0x0101, instructions=[(0x100, S_ENDPGM)])
vs = make_fssm(version=0x0102, instructions=[(0x100, S_ENDPGM)])
one = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(make_fssm())}))])
two = make_dxbc([(b"DXIL", make_xdat_list([(0x0D, make_xbch(es)), (0x0D, make_xbch(vs))]))])
for name, data in (("vertex", two), ("geometry", one), ("unstaged", one), ("blank", one), ("numbered", one)):
with open(os.path.join(self.src, name + ".dxbc"), "wb") as f:
f.write(data)
index = os.path.join(self.src, "index.json")
# Three ways an entry names no stage: no field, an empty one, and one that is not a string.
with open(index, "w", encoding="utf-8") as f:
json.dump([{"file": "vertex.dxbc", "stage": "vs"}, {"file": "geometry.dxbc", "stage": "gs"},
{"file": "unstaged.dxbc"}, {"file": "blank.dxbc", "stage": ""},
{"file": "numbered.dxbc", "stage": 7}], f)
stages = shader_stage_manifest.shader_stages(index, "file", ".dxbc")
self.assertEqual(stages, {"vertex": "vs", "geometry": "gs", "unstaged": None, "blank": None, "numbered": None})
result = subprocess.run([sys.executable, "-I", TOOL, self.src, "--carve-index", index],
capture_output=True, text=True, errors="replace")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("programs: 6 tag-0x0D payloads in 5 containers, 1 containers with more than one "
"(--payload last is the one unpacked)", result.stdout)
self.assertIn(" gs: 1 containers, 1 payloads, 0 with more than one", result.stdout)
self.assertIn(" vs: 1 containers, 2 payloads, 1 with more than one", result.stdout)
# A row the carve index gives no stage is counted, under one heading, not dropped, guessed or split by the
# way its stage is missing: three lines for the breakdown, no fourth for "" or 7.
self.assertIn(" stage unknown: 3 containers, 3 payloads, 0 with more than one", result.stdout)
breakdown = [line for line in result.stdout.splitlines() if line.startswith(" ") and " containers, " in line]
self.assertEqual(len(breakdown), 3, breakdown)
# The file written for the two-payload container is still one program: the last payload.
with open(os.path.join(self.src, "fssm", "vertex.fssm"), "rb") as f:
self.assertEqual(f.read(), vs)
with open(os.path.join(self.src, "fssm_index.json"), encoding="utf-8") as f:
rows = json.load(f)
counts = fssm_unpack.program_counts(rows, stages)
self.assertEqual(counts, {"vs": {"containers": 1, "programs": 2, "multi_payload": 1},
"gs": {"containers": 1, "programs": 1, "multi_payload": 0},
None: {"containers": 3, "programs": 3, "multi_payload": 0}})
def test_program_counts_without_a_carve_index_have_no_stage_breakdown(self):
two = make_dxbc([(b"DXIL", make_xdat_list([(0x0D, make_xbch(make_fssm(version=0x0101))),
(0x0D, make_xbch(make_fssm(version=0x0102)))]))])
with open(os.path.join(self.src, "pair.dxbc"), "wb") as f:
f.write(two)
result = subprocess.run([sys.executable, "-I", TOOL, self.src], capture_output=True, text=True,
errors="replace")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("programs: 2 tag-0x0D payloads in 1 containers, 1 containers with more than one",
result.stdout)
self.assertNotIn("stage unknown", result.stdout)
def test_main_rejects_invalid_fssm_magic(self):
bad_payload = b"JUNK\x01\x01" + bytes(58)
bad_dxbc = make_dxbc([(b"DXIL", make_xdat({0x0D: make_xbch(bad_payload)}))])

View File

@ -37,7 +37,7 @@ from collections import Counter
# `python -I` leaves the script's directory off sys.path.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from shader_stage_manifest import shader_stems # noqa: E402
from shader_stage_manifest import shader_stages # noqa: E402
from replace_retry import replace as replace_retry # noqa: E402
# Defensive per-blob ceiling, not a maximum defined by the XBCH format.
@ -152,6 +152,22 @@ def unpack(dxbc: bytes, payload: str = "last"):
return _inflate_xbch(blob), ents
def program_counts(rows: list, stages: dict) -> dict:
"""Containers, programs (tag-0x0D payloads) and containers with more than one payload, per stage.
A container is one carved DXBC file and one row here; a program is one tag-0x0D payload in it. The two counts
differ wherever a container carries more than one payload (docs/shader_library.md, "Containers and programs").
`stages` maps a row's name to the stage the carve index recorded. A name it lacks, or one it holds without a
stage, is counted under None: its stage is unknown."""
out = {}
for row in rows:
counts = out.setdefault(stages.get(row["name"]), {"containers": 0, "programs": 0, "multi_payload": 0})
counts["containers"] += 1
counts["programs"] += row["xbch_payloads"]
counts["multi_payload"] += row["xbch_payloads"] > 1
return out
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.")
ap.add_argument("src", help="carved shader directory")
@ -165,10 +181,11 @@ def main(argv=None) -> int:
what = "is not a folder" if os.path.exists(src) else "does not exist"
print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr)
return 2
stages = {}
try:
if a.carve_index:
names = shader_stems(a.carve_index, "file", ".dxbc")
shaders = sorted(os.path.join(src, name + ".dxbc") for name in names)
stages = shader_stages(a.carve_index, "file", ".dxbc")
shaders = sorted(os.path.join(src, name + ".dxbc") for name in stages)
for path in shaders:
if not os.path.isfile(path):
raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}")
@ -225,6 +242,15 @@ def main(argv=None) -> int:
replace_retry(tmp, os.path.join(src, "fssm_index.json")) # a scanner or sync client may hold tmp briefly on Windows
print("magic:", dict(Counter(r["magic"] for r in rows)))
print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows)))
counts = program_counts(rows, stages)
print(f"programs: {sum(c['programs'] for c in counts.values())} tag-0x0D payloads in {len(rows)} containers, "
f"{sum(c['multi_payload'] for c in counts.values())} containers with more than one "
f"(--payload {a.payload} is the one unpacked)")
if stages: # a stage comes from the carve index; without one there is nothing to break the counts down by
for stage in sorted(counts, key=lambda s: (s is None, s or "")):
c = counts[stage]
print(f" {stage or 'stage unknown'}: {c['containers']} containers, {c['programs']} payloads, "
f"{c['multi_payload']} with more than one")
sizes = sorted(r["size"] for r in rows)
print(f"size min {sizes[0]}, median {sizes[len(sizes) // 2]}, max {sizes[-1]}, total {sum(sizes) / 2**20:.0f} MiB")
return 0

View File

@ -8,7 +8,8 @@ import ntpath
import posixpath
def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
def _stem_rows(path: str, field: str, suffix: str = "") -> list[tuple[str, dict]]:
"""Each entry of the index as (validated stem, row)."""
try:
# utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM.
with open(path, encoding="utf-8-sig") as f:
@ -19,7 +20,7 @@ def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
raise ValueError(f"{path}: invalid JSON: {exc}") from exc
if not isinstance(rows, list):
raise ValueError(f"{path}: expected an array of shader entries")
stems = set()
out = []
for row in rows:
value = row.get(field) if isinstance(row, dict) else None
if (
@ -39,5 +40,19 @@ def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
stem = value.removesuffix(suffix)
if not stem or stem in (".", ".."):
raise ValueError(f"{path}: expected a shader basename in {field!r}")
stems.add(stem)
return stems
out.append((stem, row))
return out
def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
return {stem for stem, _ in _stem_rows(path, field, suffix)}
def shader_stages(path: str, field: str, suffix: str = "") -> dict[str, str | None]:
"""The stage the index records for each shader, by stem. None where an entry has no stage string: the stage is
then unknown, not absent, and the caller says so."""
stages = {}
for stem, row in _stem_rows(path, field, suffix):
stage = row.get("stage")
stages[stem] = stage if isinstance(stage, str) and stage else None
return stages