From 62137d42f8e5ed3974f6b537fb825f9cea26e4b5 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:08:09 -0500 Subject: [PATCH] tools: fssm_root_layout reads each program's root-layout and used-resource tables, with a census (FSSM-ROOT-LAYOUT-TABLES) docs/d3d12_vulkan.md section 3.5 infers where root arguments arrive from the user SGPRs the shaders read and calls the graphics bases (s8 for VS/PS/GS, s16 for mesh) a hypothesis: the SGPR census cannot see root-parameter indices or a spill. Each native program's FSSM record names two tables that state it directly: a root-layout table (root type, user-data dwords, first user-data dword and root parameter index per parameter) and a used-resource table. The record layout is the one VIctory reads (Marvisak/VIctory, GPL-3.0, crates/victory-shader/src/native.rs). The parser is written for this repository from that layout and contains no VIctory code. tools/fssm_root_layout.py is a new module on its own. root_tables(fssm) returns the programs of one blob with both tables. It raises FssmLayoutError (a ValueError) for a header that is not version 0x101 with a matching payload size, a record or code range outside the payload, records that overlap each other or the slot table, and a table that runs past the payload or overlaps a record, its program's code or the program's other table. Unnamed types and non-zero reserved fields are kept so they can be counted. Its command line prints the tables of a file or a folder as JSON, or writes them with --out, one file in memory at a time. tools/root_layout_census.py reads the user's own .fssm blobs or carved containers and prints counts per hardware stage: the lowest SGPR a parameter arrives in, the dwords each root type takes, root types and used-resource kinds, compute programs with a spilled parameter and the first spilled dword, and how many programs agree with the section 3.5 hypothesis, with the reasons for the rest. It also counts what would show the reading to be wrong (unread blobs by reason, record offsets, reserved fields, unnamed types). With no input it says so. No retranslation: tools/fssm_unpack.py and every other file in make_game's TRANSLATION_SOURCES are untouched, and neither new file is imported by the translator or make_game.py, so a translated shader library stays valid. A test holds the two new names out of make_game.py, translator_deps.cmake, fssm_unpack.py, rdna2spirv.py and shader_meta.py. Nothing here was run on real shader data. Which fields are VIctory's reading and which this corpus's earlier measurements already support (the two table offsets are the header's `code_end` and `meta_ptr`) is in section 3.5, with the commands and the open questions. The runtime does not use the tables yet. Tested: tests/test_fssm_root_layout.py (32 tests: hand-built records with constants, a root descriptor, tables, an immediate sampler, a heap and a spilled compute layout; truncated, overlapping and overflowing tables; every prefix and 4,000 seeded corruptions of a three-program blob; both command lines) and the fssm_unpack, pal_stages, fssm_header, fssm_crosscheck, missing-input, line-ending and CI-registration tests pass. The repository-consistency set gives 578 passed, 5 skipped. No game files. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- docs/d3d12_vulkan.md | 73 ++- docs/fssm_crosscheck.md | 7 +- tests/test_fssm_root_layout.py | 652 +++++++++++++++++++++++++ tests/test_missing_input_exit_codes.py | 2 + tools/fssm_root_layout.py | 293 +++++++++++ tools/root_layout_census.py | 322 ++++++++++++ 6 files changed, 1347 insertions(+), 2 deletions(-) create mode 100644 tests/test_fssm_root_layout.py create mode 100644 tools/fssm_root_layout.py create mode 100644 tools/root_layout_census.py diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index be932f1e9c..04dc3820ae 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1762,7 +1762,9 @@ below 4 GiB). A parameter that does not fit goes, with every later one, to the s two dwords from s6). The `pack()` layout contradicts 7 of them, which read the second table at s5, the first table's high half in that layout. - **Vertex/pixel/geometry s8 and mesh s16: a hypothesis.** It rests on the census above only; no signature - confirms these bases, and visibility is not modelled (every parameter takes its place in every stage). + confirms these bases, and visibility is not modelled (every parameter takes its place in every stage). Each + shader's own root-layout table would make it a per-shader fact; it is parsed but not counted yet ("Per-shader + root tables in the FSSM record" below). The runtime uses the console layout for the **compute** bind point only. Graphics keeps `pack()`: every stage of a pipeline reads `s0..s31` from one push-constant block at offset 0 (`tools/rdna2spirv.py`, `ShaderUserData` in @@ -1810,6 +1812,75 @@ Still open: which CBV index lands in which pair. The four pairs do appear in dec package proves that order, and every parameter in these 29 is `D3D12_SHADER_VISIBILITY_ALL`, so they say nothing about the visibility question below. +**Per-shader root tables in the FSSM record (FSSM-ROOT-LAYOUT-TABLES): parsed, not measured yet.** The census +above reads the code. Each native program's record also names two tables that state the layout directly: a +root-layout table (where each root parameter arrives in the program's user data) and a used-resource table (which +descriptors the program reads, by root parameter). This is the record layout as read by VIctory (Marvisak/VIctory, +GPL-3.0, `native.rs` in its `crates/victory-shader/src`), which builds its user data from these tables instead of +inferring a base. `root_tables()` in `tools/fssm_root_layout.py` is a parser written for this repository from that +layout; it contains no VIctory code. **Nothing here has been run on a real shader**: the parser and +`tools/root_layout_census.py` are tested on hand-built records only (`tests/test_fssm_root_layout.py`). Neither +file is a translation source and `tools/fssm_unpack.py` is unchanged, so a translated shader library stays valid +with them. + +Offsets stored in the blob count from the payload, which starts at blob offset `0x10`; the offsets other pages +give for the header (`0xC0`, `0xE8`, ...) are blob offsets. + +| Where | What | Basis | +|---|---|---| +| payload `+0x08` | `u64` record offset per hardware stage: LS, HS, ES, GS, VS, PS at `+0x08`..`+0x30`, mesh at `+0x48`, compute at `+0x60`; `0xDEADBEEFDEADBEEF` when the blob has no program for the stage | VIctory's reading. [fssm_crosscheck.md](fssm_crosscheck.md) measured blob `0x18`/`0x20` (the LS and HS slots here) as that sentinel in 26,503 of 26,503, and the code offset at blob `0xC0`, where a first record at payload `0xB0` puts it. Which slot holds which record offset is not checked, and the qwords between those slots (`+0x38`, `+0x40`, `+0x50`, `+0x58`) are not read. | +| record `+0x00`, `+0x08` | `u64` code offset and size | Measured before as blob `0xC0`/`0xC8`. The first instruction is `0x18` bytes into this range (the `u32[0xC0] + 0x28` rule, with the offset counted from the payload). | +| record `+0x28` | `u64` offset of the root-layout table | VIctory's reading. It is the field fssm_crosscheck.md calls `code_end` (blob `0xE8`): equal to code offset + size in 26,486 blobs, so the table starts where the code ends, and the unset sentinel in the other 17. | +| record `+0x30` | `u64` offset of the used-resource table | VIctory's reading. The `meta_ptr` of fssm_crosscheck.md (blob `0xF0`), the sentinel in 635 blobs. | +| record `+0x38`, `+0x3c` | `u32` entry count of each table | VIctory's reading, unconfirmed. | +| root-layout entry, 20 bytes | `u32` root type (0 constants, 1 root descriptor, 3 descriptor table, 4 immediate sampler, 5 resource heap, 6 sampler heap), `u32` offset of the range in its table in dwords, `u32` user-data dwords it takes, `u32` shader register of the first descriptor, `u8` first user-data dword, `u8` root parameter index, `u16` 0 | VIctory's reading, unconfirmed. `fssm_header.binding_table` already found 20-byte records at this place in all 26,503 blobs (5,640,704 of them) without naming their fields. It starts at the same byte, so its "header" word is this table's first root type: it is 4 in 24,572 blobs and 3 in 1,914, an immediate sampler and a table. Its records begin 8 bytes later, so each straddles two entries. That follows from the two descriptions; it is not checked on data. | +| used-resource entry, 20 bytes | `u8` resource type (0 SRV, 1 sampler, 2 CBV, 3 UAV), `u8` root type, `u16` 0, `u32` offset in the table in dwords, `u32` lower-bound register, `u32` stride, `u8` dwords per descriptor, `u8` first user-data dword, `u8` root parameter index, `u8` 0 | VIctory's reading, unconfirmed. | +| user-data dword n → SGPR | `s` in the VS, PS and compute stages; `s` in the merged and mesh stages (LS, HS, ES, GS, MS), which have 8 system SGPRs first | VIctory's reading. With it the bases above are first user-data dwords: 8 for a PS, VS or mesh shader (`s8`, `s8`, `s16`), 4 for compute, 0 for a GS (`s8`). Section 7 has the mesh user data at `s16`-`s24` from a corpus measurement. | +| spill (compute) | 16 user SGPRs; a parameter whose first user-data dword is 16 or more is in memory behind the 40-bit pointer in user data 0-1, and that memory starts with dword 16 | VIctory's reading. The pointer in `s[0:1]` is also section 7's (console-compiler output). The 16 is not measured here: the game's compute shaders launch with at most 14 user SGPRs. VIctory reads a spill for compute only. | + +What the parser refuses (`FssmLayoutError`, a `ValueError`): a header that is not version `0x101` with a matching +payload size, a record or code range outside the payload, records that overlap each other or the slot table, and a +table that runs past the payload or overlaps a record, its program's code or the program's other table. A count of +0 is an empty table whatever its offset is. Unnamed types and non-zero reserved fields are kept, so the census can +count them. + +``` +python -I tools/root_layout_census.py /shaders/dxbc --json +python -I tools/root_layout_census.py /shaders/dxbc --base ps=8 vs=8 gs=8 cs=4 ms=16 --expect-agree +python -I tools/fssm_root_layout.py /shaders/dxbc --out +``` + +The census reads your own carved containers (every tag-`0x0D` payload) or unpacked `.fssm` blobs and prints counts +only, per hardware stage: the lowest SGPR a parameter arrives in and the lowest that holds an address (the number +the SGPR census above measured from the code), the dwords each root type takes (one or two per table), the root +types and used-resource kinds, the compute programs with a spilled parameter and the first spilled dword, and how +many programs agree with this section's hypothesis: no parameter below the stage base, one dword per table, two per +root descriptor, parameters in root order. It lists the reasons for the ones that disagree. `--expect-agree` exits +1 on a disagreement, a blob that does not parse or an empty run. It also counts what would show the reading to be +wrong: blobs it cannot read (by reason), record offsets (the first is expected at `0xc0`), whether the root-layout +table follows the code, the number of entries in each table, used resources with no layout entry for their +parameter, non-zero reserved fields, unnamed types and parameters past `s31`. With no path, or a folder that has +no `.fssm` or `.dxbc` file, it prints `no input`. `fssm_root_layout.py` writes the tables themselves as JSON, one +line per file with an entry per blob (the programs, or why they could not be read); without `--out` it prints +them, and for a whole library the output is large. + +Open: +- **Every offset and field marked "VIctory's reading" is unconfirmed on this corpus.** A census of a real library + settles it: no unread blob, record offsets as expected, a lowest-pointer SGPR per stage that matches the SGPR + census (`s8` in 9,830 PS and 1,660 VS, `s4` in 2,364 CS, `s16` in 7,977 MS), and entry totals that can be held + against the 5,640,704 records `binding_table` counted in the same region. +- **Does a table list every parameter of the root signature, or only the ones the program reads?** If only those, + a lowest parameter above the base is expected; if all of them, it contradicts the base. The census therefore + counts "above the base" apart from "at the base" and calls neither a disagreement. +- **Root type 2 and the reserved fields** have no reading; the census counts them. +- **Blobs with two programs.** The 195 GS blobs carry a second PAL stage descriptor, the shader's VS copy + ([design.md](design.md), "PAL stage descriptors"), so they should have two records here. Whether each has its + own tables is not known: the parser reads each record's tables on their own and lets two records name the same + table. +- **A graphics-stage spill** has no reading at all. +- **The runtime does not use the tables.** Feeding them to `rt::rootsig::pack_stage` and `ShaderUserData` is the + follow-up once the counts are in; until then the hypothesis above stays a hypothesis. + Spill policy: a signature needing more than 32 user SGPRs, or more than the 64-dword D3D12 cost limit, is refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through `__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour. diff --git a/docs/fssm_crosscheck.md b/docs/fssm_crosscheck.md index 7b85df1eac..7ccf4aedda 100644 --- a/docs/fssm_crosscheck.md +++ b/docs/fssm_crosscheck.md @@ -240,7 +240,12 @@ PR description. - The vendor disassembler's `asic(CI)` label is unexplained; it does not override the gfx1013 decode result. - The post-`code_end` binding table is parsed, but the meaning of its five words and the bytes - after the name are not established. + after the name are not established. VIctory (Marvisak/VIctory) reads the same region as two + tables of 20-byte entries, a root-layout table and a used-resource table, which the record + names at `0xE8` and `0xF0` with their entry counts at `0xF8` and `0xFC`; in that reading + `code_end` and `meta_ptr` are the two table offsets, counted from `0x10`. + `tools/fssm_root_layout.py` parses that reading. It is not confirmed on this corpus yet + ([d3d12_vulkan.md](d3d12_vulkan.md), section 3.5, "Per-shader root tables in the FSSM record"). - The negative prior-art claim (`FSSM`/`0x101`/`0xDEADBEEF` have no public prior art) was not re-run; it is a web-search result, not a format fact. diff --git a/tests/test_fssm_root_layout.py b/tests/test_fssm_root_layout.py new file mode 100644 index 0000000000..ef304262c0 --- /dev/null +++ b/tests/test_fssm_root_layout.py @@ -0,0 +1,652 @@ +"""The root-layout and used-resource tables of an FSSM program record: tools/fssm_root_layout.py (root_tables() +and its command line) and tools/root_layout_census.py. + + python -I tests/test_fssm_root_layout.py + +Zero game data: every blob here is built by hand from the layout in tools/fssm_root_layout.py's docstring, with +placeholder words for code. The numbers in the tables are made up to cover the entry kinds (constants, a root +descriptor, tables, an immediate sampler, the heaps, a spilled parameter), not copied from a shader. +""" +import json +import os +import random +import struct +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +sys.path.insert(0, os.path.join(ROOT, "tests")) + +import fssm_root_layout # noqa: E402 +import fssm_unpack # noqa: E402 +import root_layout_census as census # noqa: E402 +from test_fssm_unpack import make_dxbc, make_xbch, make_xdat_list # noqa: E402 + +DUMP = os.path.join(ROOT, "tools", "fssm_root_layout.py") +CENSUS = os.path.join(ROOT, "tools", "root_layout_census.py") +PAYLOAD = 0x10 +RECORD = 0x54 +FIRST_RECORD = 0xB0 # in the payload; any offset past the slot table would do +ABSENT = 0xDEADBEEFDEADBEEF +SLOTS = dict(fssm_root_layout.FSSM_STAGE_SLOTS) +CODE = struct.pack("<4I", 0xBF810000, 0xBF9F0000, 0xBF9F0000, 0xBF9F0000) # s_endpgm and s_code_end padding +CONSTANTS, DESCRIPTOR, TABLE, IMMEDIATE_SAMPLER, RESOURCE_HEAP, SAMPLER_HEAP = 0, 1, 3, 4, 5, 6 +SRV, SAMPLER, CBV, UAV = 0, 1, 2, 3 + + +def param(root_type, user_data, sgprs, slot, register=0, table_offset=0, reserved=0): + """A 20-byte root-layout entry.""" + return struct.pack(" (bytearray, {stage: blob offset of its record}). + + programs: {stage: (root-layout entries, used-resource entries)}. The records follow the slot table, then for + each program its code, its root-layout table and its used-resource table. An empty table gets a count of 0 and + the 0xDEADBEEFDEADBEEF offset.""" + stages = [stage for stage, _ in fssm_root_layout.FSSM_STAGE_SLOTS if stage in programs] + payload = bytearray(FIRST_RECORD + 0x88 * len(stages)) + struct.pack_into("= 16: + struct.pack_into(" [--out FILE] + (prints one JSON object, a file per line: file name -> one entry per FSSM blob in it, each + {"programs": root_tables()} or {"error": why its tables could not be read}. A bare .fssm has one blob, a + container one per tag-0x0D payload. In a folder, a .dxbc with a .fssm of the same name beside it is + skipped. --out writes the object to FILE instead and prints a one-line summary; it is large for a whole + library. These are the user's own files: there are no game files in this repository.) + +A path that does not exist, a folder or file that cannot be read and an --out path that cannot be written each give +one ERROR line and exit 2. A folder with no .fssm or .dxbc file prints "no input" and exits 0. +""" +import argparse +import json +import os +import struct +import sys +import zlib +from collections import Counter + +# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling modules. +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import fssm_unpack # noqa: E402 +from report_paths import same_report_path # noqa: E402 + +FSSM_VERSION = 0x101 +FSSM_PAYLOAD = 0x10 # stored offsets count from here +FSSM_GRAPHICS_SLOTS = 6 # the u64 that starts the payload +FSSM_STAGE_SLOTS = (("ls", 0x08), ("hs", 0x10), ("es", 0x18), ("gs", 0x20), ("vs", 0x28), ("ps", 0x30), + ("ms", 0x48), ("cs", 0x60)) # hardware stage, payload offset of its record offset +FSSM_SLOT_TABLE_END = 0x68 +FSSM_ABSENT = 0xDEADBEEFDEADBEEF +FSSM_RECORD_SIZE = 0x54 +FSSM_RECORD_TABLES = 0x28 # u64 root-layout offset, u64 used-resource offset, u32 and u32 their counts +ROOT_ENTRY_SIZE = 20 +ROOT_LAYOUT_ENTRY = struct.Struct(" bool: + """offset + length <= size, for a stored 64-bit offset that may be anything.""" + return offset <= size and length <= size - offset + + +def _overlap(a: tuple, b: tuple) -> bool: + """Do two non-empty (offset, length) ranges share a byte?""" + return a[0] < b[0] + b[1] and b[0] < a[0] + a[1] + + +def root_type_name(value: int) -> str: + return ROOT_TYPES.get(value, f"root{value}") + + +def resource_type_name(value: int) -> str: + return RESOURCE_TYPES.get(value, f"resource{value}") + + +def user_sgpr(stage: str, dword: int) -> int: + """The SGPR that holds user-data dword `dword` on entry to a program of this hardware stage.""" + return SYSTEM_SGPRS[stage] + dword + + +def _entries(fssm: bytes, span, entry: struct.Struct, keys: tuple) -> list: + """The 20-byte entries of one table as dicts; span is the checked (payload offset, length) or None.""" + if not span: + return [] + start = FSSM_PAYLOAD + span[0] + return [dict(zip(keys, entry.unpack_from(fssm, at))) for at in range(start, start + span[1], ROOT_ENTRY_SIZE)] + + +def root_tables(fssm: bytes) -> list: + """The native programs of one FSSM blob with their root-layout and used-resource tables, in slot order. + + One dict per program: `stage` (the hardware stage of the slot that names the record), `record`, `code_offset`, + `layout_offset` and `used_offset` (offsets in the blob, 0x10 more than the stored ones; None for a table with + no entries), `code_size`, `layout` and `used`. A `layout` entry has `root_type`, `table_offset`, `user_sgprs`, + `base_register`, `user_data`, `root_slot` and `reserved`; a `used` entry has `resource_type`, `root_type`, + `table_offset`, `lower_bound`, `stride`, `descriptor_dwords`, `user_data`, `root_slot` and `reserved` (the u16 + at +2, with the u8 at +19 above it). The values are the stored ones: a type this reading has no name for and a + non-zero reserved field are kept, not refused, so that a census can count them. + + Raises FssmLayoutError when the header is not version 0x101 with a matching payload size, when a record or a + program's code lies outside the payload, when records overlap each other or the slot table, or when a table + runs past the payload or overlaps a record, its program's code or the program's other table. A table with a + count of 0 is empty whatever its offset is. Nothing outside the blob is read.""" + if len(fssm) < FSSM_PAYLOAD + FSSM_SLOT_TABLE_END: + raise FssmLayoutError("truncated FSSM header") + if fssm[:4] != b"FSSM": + raise FssmLayoutError("not an FSSM blob") + version, stored_size, slots = struct.unpack_from(" list: + """Files to read: every .fssm, plus a .dxbc whose stem has no .fssm beside it (as tools/pal_stages.py).""" + if os.path.isfile(path): + return [path] + with os.scandir(path) as entries: + names = sorted(entry.path for entry in entries if entry.is_file()) + fssm = [name for name in names if name.endswith(".fssm")] + taken = {os.path.splitext(os.path.basename(name))[0] for name in fssm} + dxbc = [name for name in names + if name.endswith(".dxbc") and os.path.splitext(os.path.basename(name))[0] not in taken] + return sorted(fssm + dxbc) + + +def blobs_of(data: bytes) -> list: + """The FSSM blobs of one file's bytes: the file itself, or every tag-0x0D payload of a DXBC container. + ValueError when it is neither.""" + if data[:4] == b"FSSM": + return [data] + try: + return fssm_unpack.unpack_all(data) + except (ValueError, struct.error, IndexError, zlib.error): + raise ValueError("not an FSSM blob or a container that unpacks") from None + + +def write_root_layouts(f, files: list) -> tuple: + """Write the root tables of `files` to the text file `f` as one JSON object, a file per line: file name -> a + list with one entry per FSSM blob in the file, {"programs": root_tables()} or {"error": message} (a file that + holds no blob has one error entry). One file is in memory at a time. Returns (counts of files, blobs read, + programs, layout and used entries; blobs or files not read per message). OSError when a file cannot be read + or `f` cannot be written.""" + counts, problems = Counter(), Counter() + f.write("{") + for k, path in enumerate(files): + with open(path, "rb") as source: + data = source.read() + counts["files"] += 1 + try: + blobs = blobs_of(data) + if not blobs: + raise ValueError("a container with no tag-0x0D payload") + except ValueError as e: + blobs, entries = [], [{"error": str(e)}] + problems[str(e)] += 1 + else: + entries = [] + for blob in blobs: + try: + programs = root_tables(blob) + except FssmLayoutError as e: + entries.append({"error": str(e)}) + problems[str(e)] += 1 + continue + entries.append({"programs": programs}) + counts["blobs"] += 1 + counts["programs"] += len(programs) + counts["layout"] += sum(len(p["layout"]) for p in programs) + counts["used"] += sum(len(p["used"]) for p in programs) + f.write(("," if k else "") + "\n" + json.dumps(os.path.basename(path)) + ": " + json.dumps(entries)) + f.write("\n}\n") + f.flush() + return counts, problems + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("path", help="an .fssm file, a DXBC container, or a folder of either (your own files)") + ap.add_argument("--out", help="write the JSON here instead of printing it") + a = ap.parse_args(argv) + if a.out and same_report_path(a.path, a.out): + ap.error("--out must not overwrite the input") + if not os.path.exists(a.path): + print(f"ERROR: {a.path} does not exist", file=sys.stderr) + return 2 + try: + files = files_of(a.path) + except OSError as e: + print(f"ERROR: cannot list {a.path}: {e.strerror or e}", file=sys.stderr) + return 2 + if not files: + print(f"no input: {a.path} holds no .fssm or .dxbc file", file=sys.stderr) + return 0 + try: + if a.out: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: + counts, problems = write_root_layouts(f, files) + else: + counts, problems = write_root_layouts(sys.stdout, files) + except OSError as e: + print(f"ERROR: cannot read or write {e.filename or a.out or a.path}: {e.strerror or e}", file=sys.stderr) + return 2 + # Beside the JSON on stdout the summary would break the document, so it goes to stderr there. + print(f"root layout: {counts['programs']} programs in {counts['blobs']} blobs of {counts['files']} files " + f"({counts['layout']} root-layout and {counts['used']} used-resource entries), not read: " + f"{dict(sorted(problems.items()))}", file=sys.stdout if a.out else sys.stderr) + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/root_layout_census.py b/tools/root_layout_census.py new file mode 100644 index 0000000000..f95d6a4b34 --- /dev/null +++ b/tools/root_layout_census.py @@ -0,0 +1,322 @@ +r"""Census of the root-layout and used-resource tables in FSSM program records (stdlib only). + +Each native program in an FSSM blob names two tables in its record: where the root signature's parameters arrive in +the program's user data, and which descriptors it reads (`fssm_root_layout.root_tables()`; the record layout is the one +VIctory reads, Marvisak/VIctory, GPL-3.0, crates/victory-shader/src/native.rs). docs/d3d12_vulkan.md section 3.5 +has so far inferred that layout from the user SGPRs the shaders read (`tools/user_sgpr_census.py`) and calls the +graphics bases a hypothesis. This tool counts what the tables themselves say, per hardware stage: + + * base user SGPR: the lowest SGPR a root parameter arrives in, per program, and the lowest one that holds an + address (a root descriptor, a table or a heap), which is what the SGPR census measured; + * dwords per parameter: how many user-data dwords the entries of each root type take (a table: 1 or 2?); + * root types and the used-resource kinds (resource type / root type); + * spill start: in a compute program, VIctory reads the parameters from user-data dword 16 on as living in memory + behind a 40-bit pointer in user data 0-1. The census counts the programs with such an entry, the first spilled + dword and whether dwords 0-1 are free of parameters there; + * the section 3.5 hypothesis: the parameters start at the stage base (ps/vs/gs s8, cs s4, ms s16; --base + overrides), a table takes one dword, a root descriptor two, and they lie in root order. A program agrees when + none of its register-held parameters contradicts that; the reasons for the others are counted. + +It also counts what would show the reading itself to be wrong: blobs that do not parse (by reason), record offsets, +the number of entries, reserved fields that are not zero, types the reading has no name for, used resources with no +layout entry for their root parameter, parameters that would end past s31, and whether the root-layout table +follows the code and the used-resource table follows the root-layout table. + +What it does NOT measure: the root signatures. A table says where a parameter arrives, not what the game passes +there; and whether a table lists every parameter of the signature or only the ones the program reads is open, so a +lowest parameter above the base does not contradict the base (it is counted apart from "at the base"). + +It reads the user's own files and prints counts only: no shader name, no bytes. There are no game files in this +repository; give it your work folder. + +Usage: + python -I tools/root_layout_census.py [--json OUT] + (/shaders/dxbc reads every tag-0x0D payload of every container; /shaders/dxbc/fssm reads the + one payload per container that fssm_root_layout.py wrote. In a folder, a .dxbc with a .fssm of the same name + beside it is skipped.) + python -I tools/root_layout_census.py --base ps=8 vs=8 gs=8 cs=4 ms=16 --expect-agree + (exit 1 if a blob does not parse, a program disagrees with the hypothesis, or nothing was read) + +Without a path, or for a folder with no .fssm or .dxbc file, it prints "no input" and exits 0 (1 with +--expect-agree). A path that does not exist, a folder or file that cannot be read and a --json path that cannot be +written each give one ERROR line and exit 2. +""" +import argparse +import json +import os +import sys +from collections import Counter, defaultdict + +# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling modules. +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import fssm_root_layout # noqa: E402 +from report_paths import same_report_path # noqa: E402 + +# docs/d3d12_vulkan.md section 3.5: the first root-argument SGPR per stage. The merged stages have no entry there. +DEFAULT_BASE = {"ps": 8, "vs": 8, "gs": 8, "cs": 4, "ms": 16} +# VIctory's reading: a compute program has 16 user SGPRs; a parameter from user-data dword 16 on is in memory. +SPILL_FROM = {"cs": 16} +SPILL_POINTER_DWORDS = 2 +DESCRIPTOR, TABLE = 1, 3 +ADDRESS_ROOT_TYPES = (1, 3, 5, 6) # root descriptor, table, resource heap, sampler heap +LAST_USER_SGPR = 31 + + +def _sgprs(counter): + return {f"s{k}": v for k, v in sorted(counter.items())} + + +def _counts(counter): + return {str(k): v for k, v in sorted(counter.items())} + + +class Census: + """Counts over fssm_root_layout.root_tables() programs: add() each one, then summary().""" + + def __init__(self, base=None): + self.base = DEFAULT_BASE if base is None else base + self.stages = defaultdict(lambda: defaultdict(Counter)) # stage -> counter name -> key -> count + self.reading = Counter() + self.record_offsets = Counter() + + def add(self, program): + stage = program["stage"] + s = self.stages[stage] + s["n"]["programs"] += 1 + layout, used = program["layout"], program["used"] + if not layout: + s["n"]["without_layout"] += 1 + self.record_offsets[program["record"]] += 1 + self.reading["layout_entries"] += len(layout) + self.reading["used_entries"] += len(used) + if layout: + follows = program["layout_offset"] == program["code_offset"] + program["code_size"] + self.reading["layout_follows_code" if follows else "layout_not_after_code"] += 1 + if layout and used: + layout_end = program["layout_offset"] + fssm_root_layout.ROOT_ENTRY_SIZE * len(layout) + follows = program["used_offset"] == layout_end + self.reading["used_follows_layout" if follows else "used_not_after_layout"] += 1 + + placed = set() + for e in layout: + name = fssm_root_layout.root_type_name(e["root_type"]) + s["root_types"][name] += 1 + s["dwords:" + name][e["user_sgprs"]] += 1 + self.reading["nonzero_reserved"] += bool(e["reserved"]) + self.reading["unknown_root_type"] += e["root_type"] not in fssm_root_layout.ROOT_TYPES + placed.add((e["root_slot"], e["user_data"])) + for e in used: + s["used_kinds"][f"{fssm_root_layout.resource_type_name(e['resource_type'])}/" + f"{fssm_root_layout.root_type_name(e['root_type'])}"] += 1 + self.reading["nonzero_reserved"] += bool(e["reserved"]) + self.reading["unknown_root_type"] += e["root_type"] not in fssm_root_layout.ROOT_TYPES + self.reading["unknown_resource_type"] += e["resource_type"] not in fssm_root_layout.RESOURCE_TYPES + if e["root_type"] in (DESCRIPTOR, TABLE): + known = (e["root_slot"], e["user_data"]) in placed + self.reading["used_with_layout_entry" if known else "used_without_layout_entry"] += 1 + + spill_from = SPILL_FROM.get(stage) + held = [e for e in layout if e["user_sgprs"]] + spilled = [e for e in held if spill_from is not None and e["user_data"] >= spill_from] + registers = [e for e in held if spill_from is None or e["user_data"] < spill_from] + if spilled: + s["n"]["spilled_programs"] += 1 + s["spill_start"][min(e["user_data"] for e in spilled)] += 1 + s["n"]["spill_pointer_dwords_free"] += not any(e["user_data"] < SPILL_POINTER_DWORDS for e in registers) + if not registers: + s["n"]["no_register_parameters"] += 1 + return + + def first(e): + return fssm_root_layout.user_sgpr(stage, e["user_data"]) + + lowest = min(first(e) for e in registers) + highest = max(first(e) + e["user_sgprs"] - 1 for e in registers) + s["lowest_sgpr"][lowest] += 1 + s["highest_sgpr"][highest] += 1 + self.reading["programs_past_s31"] += highest > LAST_USER_SGPR + addresses = [first(e) for e in registers if e["root_type"] in ADDRESS_ROOT_TYPES] + if addresses: + s["lowest_pointer_sgpr"][min(addresses)] += 1 + + reasons = [] + base = self.base.get(stage) + if base is not None: + if lowest < base: + reasons.append("a parameter below the base") + else: + s["n"]["at_base" if lowest == base else "above_base"] += 1 + if any(e["root_type"] == TABLE and e["user_sgprs"] != 1 for e in registers): + reasons.append("a table that is not one dword") + if any(e["root_type"] == DESCRIPTOR and e["user_sgprs"] != 2 for e in registers): + reasons.append("a root descriptor that is not two dwords") + slots = {} + for e in registers: + slots[e["root_slot"]] = min(slots.get(e["root_slot"], e["user_data"]), e["user_data"]) + order = [slots[k] for k in sorted(slots)] + if any(b <= a for a, b in zip(order, order[1:])): + reasons.append("parameters not in root order") + s["n"]["disagree" if reasons else "agree"] += 1 + for reason in reasons: + s["disagree_reasons"][reason] += 1 + + def summary(self): + stages = {} + for stage in sorted(self.stages): + s = self.stages[stage] + n = s["n"] + stages[stage] = { + "programs": n["programs"], + "programs_without_layout": n["without_layout"], + "root_types": dict(sorted(s["root_types"].items())), + "used_kinds": dict(sorted(s["used_kinds"].items())), + "dwords_per_parameter": {k[7:]: _counts(v) for k, v in sorted(s.items()) if k.startswith("dwords:")}, + "lowest_sgpr": _sgprs(s["lowest_sgpr"]), + "lowest_pointer_sgpr": _sgprs(s["lowest_pointer_sgpr"]), + "highest_sgpr": _sgprs(s["highest_sgpr"]), + "spill": {"programs": n["spilled_programs"], "start": _counts(s["spill_start"]), + "pointer_dwords_free": n["spill_pointer_dwords_free"]}, + "hypothesis": {"base": self.base.get(stage), "agree": n["agree"], "disagree": n["disagree"], + "at_base": n["at_base"], "above_base": n["above_base"], + "no_register_parameters": n["no_register_parameters"], + "disagree_reasons": dict(sorted(s["disagree_reasons"].items()))}, + } + keys = ("layout_entries", "used_entries", "layout_follows_code", "layout_not_after_code", + "used_follows_layout", "used_not_after_layout", "used_with_layout_entry", "used_without_layout_entry", + "nonzero_reserved", "unknown_root_type", "unknown_resource_type", "programs_past_s31") + reading = {k: self.reading[k] for k in keys} + reading["record_offsets"] = {f"0x{k:x}": v for k, v in sorted(self.record_offsets.items())} + return {"stages": stages, "reading": reading} + + +def census(programs, base=None): + """programs: fssm_root_layout.root_tables() dicts; base: {stage: first root-argument SGPR} -> summary dict.""" + c = Census(base) + for program in programs: + c.add(program) + return c.summary() + + +def read_files(files, base=None): + """Census over files -> (summary, blobs read, {reason: blobs not read}). OSError when a file cannot be read.""" + c = Census(base) + blobs, unread = 0, Counter() + for path in files: + with open(path, "rb") as f: + data = f.read() + try: + found = fssm_root_layout.blobs_of(data) + except ValueError as e: + unread[str(e)] += 1 + continue + if not found: + unread["a container with no tag-0x0D payload"] += 1 + for blob in found: + try: + programs = fssm_root_layout.root_tables(blob) + except fssm_root_layout.FssmLayoutError as e: + unread[str(e)] += 1 + continue + blobs += 1 + for program in programs: + c.add(program) + return c.summary(), blobs, dict(sorted(unread.items())) + + +def stage_sgpr(text): + stage, _, value = text.partition("=") + message = f"expected STAGE=SGPR with a known stage and a nonnegative SGPR: {text!r}" + try: + sgpr = int(value) + except ValueError: + raise argparse.ArgumentTypeError(message) from None + if stage not in fssm_root_layout.SYSTEM_SGPRS or sgpr < 0: + raise argparse.ArgumentTypeError(message) + return stage, sgpr + + +def print_summary(summary, blobs, unread): + programs = sum(s["programs"] for s in summary["stages"].values()) + print(f"{blobs} blobs, {programs} programs, blobs not read: {unread}") + for stage, s in summary["stages"].items(): + h = s["hypothesis"] + print(f"{stage}: {s['programs']} programs ({s['programs_without_layout']} without a root-layout table); " + f"root types {s['root_types']}; used resources {s['used_kinds']}") + print(f" base: lowest user SGPR {s['lowest_sgpr']}, lowest pointer SGPR {s['lowest_pointer_sgpr']}, " + f"highest SGPR {s['highest_sgpr']}") + print(f" dwords per parameter: {s['dwords_per_parameter']}") + print(f" spill: {s['spill']['programs']} programs, first spilled user-data dword {s['spill']['start']}, " + f"user data 0-1 free in {s['spill']['pointer_dwords_free']}") + print(f" section 3.5 hypothesis (base {'s%d' % h['base'] if h['base'] is not None else 'none given'}, " + f"one dword per table, root order): {h['agree']} agree ({h['at_base']} at the base, " + f"{h['above_base']} above it), {h['disagree']} disagree {h['disagree_reasons']}, " + f"{h['no_register_parameters']} with no parameter in a register") + r = summary["reading"] + print(f"reading checks: record offsets {r['record_offsets']}; root-layout table right after the code in " + f"{r['layout_follows_code']} programs, elsewhere in {r['layout_not_after_code']}; used-resource table right " + f"after it in {r['used_follows_layout']}, elsewhere in {r['used_not_after_layout']}") + print(f" {r['layout_entries']} root-layout and {r['used_entries']} used-resource entries; " + f"used descriptors and tables with a root-layout entry {r['used_with_layout_entry']}, without " + f"{r['used_without_layout_entry']}; entries with a non-zero reserved field {r['nonzero_reserved']}; unnamed " + f"root types {r['unknown_root_type']}, resource types {r['unknown_resource_type']}; programs with a " + f"parameter past s{LAST_USER_SGPR}: {r['programs_past_s31']}") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("path", nargs="?", help="an .fssm file, a DXBC container, or a folder of either (your own files)") + ap.add_argument("--json", help="also write the summary here") + ap.add_argument("--base", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR", + help="first root-argument SGPR of a stage, instead of the section 3.5 one") + ap.add_argument("--expect-agree", action="store_true", + help="exit 1 if a blob is not read, a program disagrees with the hypothesis or nothing was read") + a = ap.parse_args(argv) + if a.json and a.path and same_report_path(a.path, a.json): + ap.error("--json must not overwrite the input") + files = [] + if a.path: + if not os.path.exists(a.path): + print(f"ERROR: no input: {a.path} does not exist", file=sys.stderr) + return 2 + try: + files = fssm_root_layout.files_of(a.path) + except OSError as e: + print(f"ERROR: cannot list {a.path}: {e.strerror or e}", file=sys.stderr) + return 2 + if not files: + where = f"{a.path} holds no .fssm or .dxbc file" if a.path else "give the folder with your own unpacked " \ + ".fssm blobs or carved .dxbc containers" + print(f"no input: {where}") + return 1 if a.expect_agree else 0 + try: + summary, blobs, unread = read_files(files, {**DEFAULT_BASE, **dict(a.base)}) + except OSError as e: + print(f"ERROR: cannot read {e.filename or a.path}: {e.strerror or e}", file=sys.stderr) + return 2 + print_summary(summary, blobs, unread) + report = {**summary, "blobs": blobs, "blobs_not_read": unread} + if a.json: + try: + with open(a.json, "w", encoding="utf-8", newline="\n") as f: + json.dump(report, f, indent=1, sort_keys=True) + except OSError as e: + print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) + return 2 + if not a.expect_agree: + return 0 + bad = [f"{count} blobs not read: {reason}" for reason, count in unread.items()] + bad += [f"{stage}: {s['hypothesis']['disagree']} programs disagree {s['hypothesis']['disagree_reasons']}" + for stage, s in summary["stages"].items() if s["hypothesis"]["disagree"]] + if not blobs: + bad.append("no blob was read") + for b in bad: + print("MISMATCH", b, file=sys.stderr) + return 1 if bad else 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main())