Files
mandy/scripts/check_no_game_data.py
Jan Trencansky 39879ce0fd Merge main into RT-PROTON-STORY-LOAD (#984)
Merges main at 1154976d4 into the integration branch at 273b3bdf9 (merge base ece4ba5b3). 42 files conflicted;
this commit is the resolution only. Build and test repairs follow in their own commits.

Rule of resolution: where both sides added different things, both stay; where both made the same change in two
forms, main's reviewed form stays and whatever #984's form did in addition is carried into it; where the two
changed the same code for different purposes, both purposes are kept.

Xbox proxy code (runtime/shims/d3d12_xs_device.cpp, d3d12_xs_device.h, d3d12_xs.cpp, d3d12_xs_alloc_size.h,
d3d12_xs_desc_clean.h, registry.cpp):
- d3d12_xs_device.cpp is #984's file with main's differing pieces ported in: env_slot and the configurable device
  routes, XboxQueueSlotRoutes, PresentationHandler / set_presentation_handler, the console caller rule for device
  slots 61 and 74 (#383, #385), route_xbox_device_slot, slot 81 as GetFrameStatisticsX, create_host_device, the
  console-form rule for slots 25 and 56, the console list IID of #359, and the forms of queue slot 18 (#403) and
  list slot 139 (#396).
- Kept from #984: the list proxy with handle translation, queue slots 16/17 as Signal/Wait, the fence's
  completed-value mirror, the shared FrameTokenSource, PresentX through queue_present_x when no handler is
  attached (slot 30, or 32 on a queue detected as the newer layout), slots 27/53/55/57/70/71/133, the wider
  pc_resource_desc, S_OK for queue slots past the PC table.
- Dropped: #984's GetFrameEventsX and LEONIDA_XS_FRAME_EVENTS_SLOT, its second-word rule for slot 61, its
  undetected-layout rule for queue slot 18, its list IID mapping to GraphicsCommandList6; main's copy of the base
  list proxy, its null-view slot 70 and its refusing slot 133.

Proxy tests (runtime/test/xs_proxy_mock_test.cpp, device_proxy_test.cpp, queue_proxy_test.cpp):
- Checks of both sides, each run once; main's forms of the render-target size and layout checks with #984's extra
  cases added; main's --env-slots-74 and #984's --env-slots-70.
- Adapted to the merged code: the queue tail answers S_OK, slot 73 answers an unknown IID with the list proxy,
  the queue slot 18 case installs a console caller. Dropped: #984's slot 81 GetFrameEventsX cases.

D3D12/Vulkan layer (runtime/shims/d3d12_com.cpp, d3d12_vulkan_device.cpp, runtime/src/command_list.h,
frame_pacer.h, shader_library.h, vulkan_backend.h, vulkan_replay.h, runtime/test/command_list_test.cpp,
d3d12_close_parity_test.cpp, d3d12_execute_indirect_validation_test.cpp, replay_texture_barrier_test.cpp,
vk_pipeline_check.cpp, vk_test_device.h):
- Resource::create_texture: #984's title images (deferred placed, pending streamed, title pool) and main's
  ordinary textures (#1413 shared blocks, #1364 staging fallback) are exclusive branches chosen by the texture's
  origin, so both pools run on disjoint sets of textures.
- frame_pacer.h is main's pacer (#402) with #984's FrameTokenSource as the token counter.
- main's forms kept for ExecuteIndirect (#1066, #377), the barrier into LAYOUT_UNDEFINED (#1055), the B4G4R4A4
  stand-in, per-face stencil masks, the unaligned tile staging (#528) and the device-lost flag (#980).
- shader_library.h: main's block inflate; #984's `bulk` parameter now defaults to true so main's callers keep it.
- Dropped: #984's B8G8R8A8 stand-in for B4G4R4A4 targets, its refusal of separate stencil masks, its zero-count
  refusal in ExecuteIndirect, its wider UNDEFINED -> UNDEFINED release and the test case for it.

Other shims (runtime/shims/dstorage.cpp, file_system.cpp, gameinput.cpp, xgameruntime_offline.cpp,
runtime/test/xgameruntime_offline_test.cpp, xmem_test.cpp):
- ReadFile and DirectStorage reads: #984's pinned kernel_writes read, then main's touch_pages retry on
  ERROR_NOACCESS. main's rt::fs::read_file is folded into #984's read_file.
- gameinput: main's strict LEONIDA_INPUT_SCRIPT parser with #984's rsup/rsdown entries.
- Speech synthesis: main's one silent voice and handle checks; #984's accept-anything form dropped.

Build, tools, docs (runtime/CMakeLists.txt, runtime/cmake/translator_deps.cmake, scripts/build_runtime.ps1,
make_game.py, tools/rdna2spirv.py, shader_disasm.py, shader_ir.py, shader_library.py,
runtime/test/shaders/cs_imgload_tfe.asm, cs_imgload_d16_tfe.asm, docs/README.md, boot.md, d3d12_vulkan.md,
runtime/README.md):
- Unions of the test, target and source lists; spirv_loop_guard.py added to translator_deps.cmake.
- rdna2spirv.py: main's DPP compare rule (#957), SMEM vcc base (#647) and widen_wave64_masks (#1021); #984's
  restore_skipped_instructions and restore_dot4_inline_sel. #984's duplicate widen_wave64_valu_masks dropped.
- shader_disasm.py and shader_ir.py: main's structure with #984's one-line-per-dword llvm-mc input and wave flags.
- shader_library.py: main's structure with #984's --compute-hashes and per-state compute variants.

One file that did not conflict is changed here: tools/rdna2_decode.py. Git kept both sides' decoders for a VOPC
compare with a DPP operand, and #984's narrower one shadowed main's; it is main's file again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 19:38:04 -05:00

324 lines
13 KiB
Python

"""Fail when a tracked file starts like game data, whatever its name.
python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists
python3 -I scripts/check_no_game_data.py PATH... # only these files
The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable
as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the
files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader
containers, SPIR-V, DDS, AWC audio, PSIN/PAMH/MHIU/SPS1/SGD5/RDS5 containers, YSC/SCRP compiled scripts, the
animation MoVE container and SKEL_ bone table, Ogg, RIFF WAVE, Bink, glTF binaries, PE executables and XVD
images, the player's saves (JSAV, ASAV and SLAYER1) and world_build.py's LPK1 staging packs of the game's
geometry. The magics are the ones docs/ measures (docs/gamedata.md, docs/saves.md and the shader and audio
notes). Text formats (disassembly, .obj, .spvasm)
have no magic and stay with the extension check.
A compressed file hides those magics from both checks, so the script looks inside what the standard library opens:
each member of a zip (found by its central directory too, so with bytes in front of it) or a tar, and the stream of
a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory
under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long.
7-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are
reported as archives that can't be checked.
Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and
exits 1 if there is any. It exits 2 when a file cannot be read or git cannot list the tracked files (outside a
repository, or git not installed). Standard library only, no game files.
"""
import bz2
import gzip
import io
import lzma
import os
import subprocess
import sys
import tarfile
import zipfile
import zlib
HEAD = 0x208 # enough for the XVD magic at 0x200
# (format, offset, magic). Matched at the start of the file only, so the same bytes inside text don't count.
MAGICS = (
("RPF9 archive", 0, b"9FPR"),
("RPF9 archive", 0, b"RPF9"),
("TTPF texture pool", 0, b"TTPF"),
("local BCPack predictor profile", 0, b"BCPHIST1"),
("RAGE resource", 0, b"RSC7"),
("RAGE resource", 0, b"RSC8"),
("RAGE resource", 0, b"RSCC"),
("RAGE page directory", 0, b"0DRP"),
("RBF0 tree", 0, b"RBF0"),
("XBCH shader container", 0, b"XBCH"),
("FSSM shader", 0, b"FSSM"),
("DXBC container", 0, b"DXBC"),
("SPIR-V module", 0, b"\x03\x02\x23\x07"),
("SPIR-V module", 0, b"\x07\x23\x02\x03"),
("DDS texture", 0, b"DDS "),
("AWC audio bank", 0, b"ADAT"),
("AWC audio bank", 0, b"TADA"),
("AWC audio bank", 0, b"AWC\x00"),
("PSIN metadata container", 0, b"PSIN"),
("PAMH heightmap", 0, b"PAMH"),
("MHIU heightmap", 0, b"MHIU"),
("SPS1 shader-preset table", 0, b"SPS1"),
("SGD5 effects database", 0, b"SGD5"),
("RDS5 texture container", 0, b"RDS5"),
("YSC compiled script", 0, b"YSC\x00"),
("MoVE animation container", 0, b"MoVE"),
("SKEL_ bone table", 0, b"SKEL_"),
("SCRP compiled script", 0, b"SCRP"),
# docs/saves.md: "Never commit or attach real saves"; and the geometry world_build.py packs from the game's models.
("JSAV story save", 0, b"JSAV"),
("ASAV save record", 0, b"ASAV"),
("SLAYER1 packed save", 0, b"SLAYER1\0"),
("LPK1 world staging pack", 0, b"LPK1"),
("Ogg stream", 0, b"OggS"),
("Bink 2 video", 0, b"KB2"),
("Bink video", 0, b"BIK"),
("glTF binary", 0, b"glTF"),
("XVD image", 0x200, b"msft-xvd"),
)
def classify(head, pe_signature=None):
"""The format a file starts like, or None. `head` is its first bytes; `pe_signature` the 4 bytes at e_lfanew."""
for name, offset, magic in MAGICS:
if head[offset:offset + len(magic)] == magic:
return name
if head.startswith(b"RIFF") and head[8:12] == b"WAVE":
return "RIFF WAVE audio"
if head.startswith(b"MZ") and pe_signature == b"PE\0\0":
return "PE executable"
return None
def read_head_from(f):
"""(first bytes, the 4 bytes at e_lfanew or None) of the open binary file `f`. The PE signature is read where
e_lfanew points, even past the first bytes or straddling their end; a file too short for it gives fewer than 4
bytes and no match."""
head = f.read(HEAD)
if not head.startswith(b"MZ") or len(head) < 0x40:
return head, None
offset = int.from_bytes(head[0x3C:0x40], "little")
if offset + 4 <= len(head):
return head, head[offset:offset + 4]
f.seek(offset)
return head, f.read(4)
def read_head(path):
"""(first bytes, the 4 bytes at e_lfanew or None). The PE signature is read where e_lfanew points, even past
the first bytes or straddling their end; a file too short for it gives fewer than 4 bytes and no match."""
with open(path, "rb") as f:
return read_head_from(f)
ZIP = b"PK\x03\x04"
# Single compressed streams the standard library opens: (name, magic, opener of a binary file object). GzipFile
# gets its mode explicitly: it reads the file object's own `mode`, which for a GzipFile inside it isn't a string.
STREAMS = (
("gzip stream", b"\x1f\x8b", lambda f: gzip.GzipFile(fileobj=f, mode="rb")),
("bzip2 stream", b"BZh", lambda f: bz2.BZ2File(f)),
("xz stream", b"\xfd7zXZ\x00", lambda f: lzma.LZMAFile(f)),
)
# Archives the standard library can't open, so what they hold can't be checked.
OPAQUE = (
("7-Zip archive", b"7z\xbc\xaf\x27\x1c"),
("Zstandard stream", b"\x28\xb5\x2f\xfd"),
("RAR archive", b"Rar!\x1a\x07"),
)
MAX_DEPTH = 3 # an archive inside an archive inside an archive; deeper ones are reported as unchecked
# What looking into one file may cost: the bytes decompressed or copied out of its archives in all, and the archive
# members listed. Everything inside an archive is read into memory under this budget before it is looked at, so a
# zip bomb, or a zip inside a gzip (whose central directory sits at the end of the expanded stream), can't make the
# check run long or grow; past either limit the file is reported as too large to check, not passed.
MAX_EXPANDED = 64 << 20
MAX_MEMBERS = 10000
CHUNK = 1 << 20
TAR_MAGIC = (257, b"ustar") # POSIX and GNU tar headers
# What a damaged archive raises while it is opened or read.
ARCHIVE_ERRORS = (OSError, EOFError, ValueError, zipfile.BadZipFile, tarfile.TarError, lzma.LZMAError, zlib.error,
NotImplementedError, RuntimeError)
class TooLarge(Exception):
"""Looking into an archive would take more than its file's budget."""
class Budget:
"""The bytes and members left for one checked file."""
def __init__(self):
self.bytes = MAX_EXPANDED
self.members = MAX_MEMBERS
def spool(self, f):
"""The rest of `f` read into memory, counted against the byte budget."""
out = io.BytesIO()
while True:
chunk = f.read(min(CHUNK, self.bytes + 1))
if not chunk:
break
self.bytes -= len(chunk)
if self.bytes < 0:
raise TooLarge
out.write(chunk)
out.seek(0)
return out
def member(self):
self.members -= 1
if self.members < 0:
raise TooLarge
def printable(name):
"""A member name on one output line: control characters (a newline in a name, say) shown as '?'."""
return "".join(c if c.isprintable() else "?" for c in name)
def archive_kind(f, head):
"""The kind of archive the seekable file `f` (first bytes `head`) is, or None."""
stream = next((s for s in STREAMS if head.startswith(s[1])), None)
if stream:
return stream[0]
if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]:
return "tar archive"
# is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting
# archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it.
if head.startswith(ZIP) or zipfile.is_zipfile(f):
return "zip archive"
return None
def classify_open(f, first, depth=0, budget=None):
"""The format of the seekable file `f`, whose read_head_from() is `first`: a game-data format, the game-data
format of the first match inside it if it's an archive, an archive that can't be checked, or None. Members and
streams inside are read into memory under `budget` (one per checked file) before they are looked at."""
budget = budget or Budget()
head = first[0]
name = classify(*first)
if name:
return name
for kind, magic in OPAQUE:
if head.startswith(magic):
return f"{kind} (contents can't be checked)"
kind = archive_kind(f, head)
if not kind:
return None
if depth >= MAX_DEPTH:
return f"{kind} nested more than {MAX_DEPTH} deep (contents can't be checked)"
def look_into(member):
inner = budget.spool(member)
return classify_open(inner, read_head_from(inner), depth + 1, budget)
try:
f.seek(0)
if kind == "zip archive":
with zipfile.ZipFile(f) as archive:
for info in archive.infolist():
budget.member()
if info.is_dir():
continue
with archive.open(info) as member:
inner = look_into(member)
if inner:
return f"{inner} in {kind} ({printable(info.filename)})"
return None
if kind == "tar archive":
with tarfile.open(fileobj=f, mode="r:") as archive:
for info in archive:
budget.member()
if not info.isfile():
continue
with archive.extractfile(info) as member:
inner = look_into(member)
if inner:
return f"{inner} in {kind} ({printable(info.name)})"
return None
opener = next(s[2] for s in STREAMS if s[0] == kind)
with opener(f) as member:
inner = look_into(member)
return f"{inner} in {kind}" if inner else None
except TooLarge:
return (f"{kind} too large to check (over {MAX_EXPANDED >> 20} MiB expanded or {MAX_MEMBERS} members; "
"contents can't be checked)")
except ARCHIVE_ERRORS:
return f"{kind} that can't be opened (contents can't be checked)"
def classify_file(path):
"""The format the file at `path` starts like (looking inside archives), or None."""
with open(path, "rb") as f:
return classify_open(f, read_head_from(f))
def tracked_files(root):
out = subprocess.run(["git", "ls-files", "-z"], cwd=root, check=True, capture_output=True).stdout
return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p]
def git_error(e):
"""One line on why git could not list the files: the first line git printed, or the OS error."""
if isinstance(e, subprocess.CalledProcessError):
lines = (e.stderr or b"").decode("utf-8", "replace").splitlines()
return next((line.strip() for line in lines if line.strip()), f"exit status {e.returncode}")
return e.strerror or str(e)
def check(paths, unreadable=None):
"""[(path, format)] for every regular file in `paths` that starts like game data.
A file that exists but cannot be opened or read is appended to `unreadable` (when given) as (path, error)."""
found = []
for path in paths:
if os.path.islink(path) or not os.path.isfile(path):
continue # submodules, symlinks, files deleted in the working tree
try:
name = classify_file(path)
except OSError as e:
if unreadable is not None:
unreadable.append((path, e))
continue
if name:
found.append((path, name))
return found
def display(path):
try:
path = os.path.relpath(path)
except ValueError: # Windows: another drive than the working directory
pass
return path.replace("\n", "\\n").replace("\r", "\\r") # one line per file, even for a name with a newline
def main(argv):
if argv:
paths = argv
else:
try:
paths = tracked_files(os.getcwd())
except (OSError, subprocess.CalledProcessError) as e:
print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr)
return 2 # not 1: that is the 'game data found' code
unreadable = []
found = check(paths, unreadable)
for path, name in found:
print(f"{display(path)}: {name}")
for path, e in unreadable:
print(f"check_no_game_data: cannot read {display(path)}: {e.strerror or e}", file=sys.stderr)
if found:
print(f"{len(found)} file(s) start like game data. Remove them; see CONTRIBUTING.md.", file=sys.stderr)
return 1
return 2 if unreadable else 0 # 2: some files could not be checked and none of the others matched
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(sys.argv[1:]))