"""Carve the PSO/shader cache out of an RPF9 archive, reproducibly and without the encrypted TOC. The cache starts with the magic ``PS\\0\\x09``. In the measured package it is one resource stored as a chain of zlib streams in an archive's data area: 4,205 adjacent streams, 4,204 of 64 KiB and a 27,436-byte last one, 31,437 bytes of zero padding between them, 275,540,780 inflated bytes in total. It is the last resource in its archive, but that is not assumed here. How the search stays bounded and deterministic: 1. The archive header gives the data start (`u32` at +4). From there the tool walks the stream table in archive order, the same walk `rpf9_carve.py` uses. A stream starts at a zlib header (`78 01/5e/9c/da`); anything else between streams is zero padding or unread bytes. Every stream is inflated in 1 MiB pieces so the walk learns where it ends; only the first 4 inflated bytes are kept for the test. The output is discarded otherwise. 2. The first stream whose inflated bytes start with ``PS\\0\\x09`` wins and the scan stops. If none is found before ``--budget`` compressed bytes (default 8 GiB) or ``--max-streams`` streams (default 200,000), or at the end of the archive, the tool exits 2 without writing anything. 3. The header of that stream declares the total: ``0x80 + graphics*0x70 + compute*0x18 + meta_index*8 + shader_index*8 + meta_size + code_size``. The tool appends following streams after at most 1 MiB of zero padding until exactly that many inflated bytes exist. A stream that would overshoot, a missing stream, or a missing header is reported with the byte counts, not guessed. 4. The file is written to ``--out``, which must be inside the system temporary directory, and then checked with ``psocache_inspect.inspect``. The exit code is 0 only when that model holds. Usage: python -I psocache_extract.py [--budget BYTES] [--max-streams N] [--quiet] Exit code: 0 extracted and the model holds, 1 extracted but the model disagrees, 2 not found, unreadable input, a source budget exhausted, or an output path outside the temporary directory. The tool prints counts, offsets and sizes only, never an archive name or a path from the package. """ import argparse import mmap import os import re import struct import sys import tempfile import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 import psocache_inspect # noqa: E402 from replace_retry import replace as replace_file # noqa: E402 from report_paths import case_insensitive_volume, same_report_path # noqa: E402 ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") MAGIC = psocache_inspect.MAGIC HEADER_SIZE = psocache_inspect.HEADER_SIZE GRAPHICS_STRIDE = psocache_inspect.GRAPHICS_STRIDE COMPUTE_STRIDE = psocache_inspect.COMPUTE_STRIDE INDEX_STRIDE = psocache_inspect.INDEX_STRIDE COUNT_OFFS = psocache_inspect.COUNT_OFFS SIZE_OFFS = psocache_inspect.SIZE_OFFS MAX_GAP = 1 << 20 # zero padding allowed between two streams of one resource DEFAULT_BUDGET = 1 << 33 # compressed bytes examined before the search gives up DEFAULT_MAX_STREAMS = 200000 class NotFound(Exception): """The cache was not found inside the search budget.""" def inflate(m, start, end, keep_all=False): """Inflate one zlib stream at ``start``. Returns ``(used, head)`` where ``used`` is the first byte after the stream (the decompressor may have read past its end) and ``head`` is the first 4 inflated bytes, or ``(None, None)`` when it does not decode. With ``keep_all`` the inflated bytes are returned in place of the 4-byte head; memory then grows with the stream, which is why the search path does not use it. """ d = zlib.decompressobj() head = bytearray() out = bytearray() if keep_all else None p = start try: while p < end and not d.eof: piece = m[p : min(p + (1 << 20), end)] chunk = d.decompress(piece) p += len(piece) if keep_all: out += chunk elif len(head) < len(MAGIC): head += chunk[: len(MAGIC) - len(head)] except zlib.error: return None, None if not d.eof: return None, None used = p - len(d.unused_data) return used, bytes(out if keep_all else head) def declared_total(header): """The total the cache header declares, or None when the header is too short.""" if len(header) < HEADER_SIZE: return None counts = tuple(struct.unpack_from(" total: raise ValueError( "first stream is %d bytes, more than the declared %d" % (len(data), total) ) pos = used while len(data) < total: gap = 0 while pos < size and m[pos] == 0 and gap <= MAX_GAP: pos += 1 gap += 1 if gap > MAX_GAP or pos >= size or not ZHDR.match(m, pos): raise ValueError( "only %d of %d declared bytes are in contiguous streams" % (len(data), total) ) used, chunk = inflate(m, pos, size, keep_all=True) if used is None: raise ValueError("stream after %d bytes does not inflate" % len(data)) if len(data) + len(chunk) > total: raise ValueError( "stream after %d bytes adds %d, past the declared %d" % (len(data), len(chunk), total) ) data += chunk pos = used return bytes(data) def inside_tempdir(path): if not isinstance(path, (str, os.PathLike)) or not os.fspath(path).strip(): return False root = os.path.realpath(tempfile.gettempdir()) target = os.path.realpath(os.path.abspath(path)) root_norm = os.path.normcase(root) target_norm = os.path.normcase(target) if sys.platform == "darwin" and case_insensitive_volume(root): root_norm = root_norm.casefold() target_norm = target_norm.casefold() try: return ( os.path.commonpath([root_norm, target_norm]) == root_norm and target_norm != root_norm ) except ValueError: return False def archives(source): if os.path.isdir(source): try: names = sorted(os.listdir(source)) except OSError as e: raise ValueError( "source folder cannot be listed: %s" % (e.strerror or "I/O error") ) from None return [ os.path.join(source, name) for name in names if os.path.isfile(os.path.join(source, name)) ] return [source] def _write_bytes_atomic(path, data): abs_path = os.path.abspath(path) parent = os.path.dirname(abs_path) or "." tmp_path = None try: with tempfile.NamedTemporaryFile( "wb", dir=parent, prefix=".psocache-", suffix=".tmp", delete=False ) as f: tmp_path = f.name f.write(data) os.chmod(tmp_path, published_mode(abs_path)) replace_file(tmp_path, abs_path) tmp_path = None finally: if tmp_path is not None: try: os.unlink(tmp_path) except OSError: pass def extract( source, out, budget=DEFAULT_BUDGET, max_streams=DEFAULT_MAX_STREAMS, quiet=False ): """Find, carve and validate the cache. Returns ``(archive_index, report, search)`` or raises NotFound.""" if budget < 1: raise ValueError("--budget must be at least 1") if max_streams < 1: raise ValueError("--max-streams must be at least 1") if not inside_tempdir(out): raise ValueError("--out must be a file inside the temporary directory") if os.path.isdir(out): raise ValueError("--out is a directory, not a file") parent = os.path.dirname(os.path.abspath(out)) or "." if not os.path.isdir(parent): raise ValueError("--out parent directory does not exist") paths = archives(source) if same_report_path(source, out) or any(same_report_path(p, out) for p in paths): raise ValueError("--out must not overwrite a source archive") left = budget spent = 0 streams = 0 found = None for index, path in enumerate(paths, 1): if left <= 0 or streams >= max_streams: break try: fh = open(path, "rb") except OSError as e: raise ValueError( "archive #%d cannot be opened: %s" % (index, e.strerror or "I/O error") ) with fh: size = os.fstat(fh.fileno()).st_size if size < 8: continue with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: if bytes(m[:4]) not in (b"RPF9", b"9FPR"): continue data_start = struct.unpack_from("