diff --git a/docs/rpf.md b/docs/rpf.md index f589ef591..b0f48dbf2 100644 --- a/docs/rpf.md +++ b/docs/rpf.md @@ -77,6 +77,14 @@ The walker advances by `len(chunk)`, not by the 1 MiB read request. A short fina overshoot EOF, so `used` exceeded the real stream size and every trailing stream was skipped; the regression test `tests/test_rpf9_carve.py` builds a two-stream archive to keep that fixed. +A gap between streams counts as zero padding when every byte in it is zero, otherwise as unread. +`rpf9_carve.py` checks a gap in 1 MiB pieces. The other scanners that keep these counts (`rpf9_names`, +`bvh_index`, `navmesh_index`, `navmesh_decode`, `rbf0_index`, `anim_index`, `restofworld_index`, `story_index`) +use `tools/zero_span.py`, which compares the gap with zeros 4 MiB at a time and stops at the first window with a +non-zero byte. They used to slice the gap out of the mapped archive, which copies all of it at once. The largest +gap in `story000.rpf` is 8.9 GiB, so that needed 8.9 GiB of memory. `tests/test_zero_span.py` runs all nine +scanners on a 48 MiB gap and checks that each one's Python heap peak stays under 24 MiB. + The carve is read-only and works on any `.rpf`, `.ttpf` or archive-like file. It does not decrypt the TOC, use keys, or write anything outside the output directory. diff --git a/tests/test_zero_span.py b/tests/test_zero_span.py new file mode 100644 index 000000000..4a0a85bb7 --- /dev/null +++ b/tests/test_zero_span.py @@ -0,0 +1,121 @@ +"""The archive scanners classify the bytes between streams without copying the whole gap. + +`gap = m[last:s]` on an mmap copies the gap, so one large gap costs as much memory as its size: story000.rpf +(about 20 GB) could not be indexed on a 16 GB machine. tools/zero_span.py compares the gap with zeros a window +at a time. This checks its counts against the old expression, then runs every scanner that used it on an archive +with a 48 MiB gap and measures the Python heap peak with tracemalloc. +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(ROOT, "tools") +sys.path.insert(0, TOOLS) +import zero_span # noqa: E402 + +GAP = 48 << 20 +PEAK_LIMIT = 24 << 20 # well under the gap: a whole-gap copy alone would be 48 MiB + +# Each scanner and its arguments; "{arc}" is the archive and "{out}" a fresh output directory. +SCANNERS = { + "rpf9_carve": ["{arc}", "{out}/carve", "--index-only"], + "rpf9_names": ["{arc}", "{out}/names.json", "--quiet"], + "bvh_index": ["{arc}", "--out", "{out}/bvh.json"], + "navmesh_index": ["{arc}", "--out", "{out}/navmesh.json"], + "navmesh_decode": ["{arc}", "--out", "{out}/decode.json", "--quiet"], + "rbf0_index": ["{arc}", "{out}/rbf0.json"], + "anim_index": ["{arc}", "{out}/anim.json", "--quiet"], + "restofworld_index": ["{arc}", "{out}/row.json", "--quiet"], + "story_index": ["{arc}", "{out}/story.json", "--quiet"], +} + +# Runs a tool as __main__ under tracemalloc and prints its exit code and heap peak as JSON on the last line. +RUNNER = r""" +import json, runpy, sys, tracemalloc +tool, args = sys.argv[1], sys.argv[2:] +sys.argv = [tool] + args +tracemalloc.start() +code = 0 +try: + runpy.run_path(tool, run_name="__main__") +except SystemExit as e: + code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1) +peak = tracemalloc.get_traced_memory()[1] +sys.stdout.flush() +print("\n" + json.dumps({"code": code, "peak": peak})) +""" + + +def old_split(buf, start, end): + gap = buf[start:end] + return (len(gap), 0) if gap.count(0) == len(gap) else (0, len(gap)) + + +class GapSplitTest(unittest.TestCase): + def test_counts_match_the_slice_expression(self): + w = zero_span.WINDOW + buf = bytearray(3 * w + 100) + cases = [(0, 0), (5, 5), (10, 3), (0, len(buf)), (w - 1, w + 1), (0, len(buf) + 50), + (len(buf) + 10, len(buf) + 20), (w, 2 * w)] + for nz in (None, 0, w - 1, w, 2 * w + 7, len(buf) - 1): + data = bytearray(buf) + if nz is not None: + data[nz] = 1 + for start, end in cases: + with self.subTest(nonzero=nz, start=start, end=end): + self.assertEqual(zero_span.gap_split(bytes(data), start, end), old_split(bytes(data), start, end)) + + def test_all_zero_stops_at_the_first_non_zero_window(self): + class Probe(bytes): + def __getitem__(self, key): + self.reads.append(key) + return bytes.__getitem__(self, key) + p = Probe(b"\x01" + bytes(3 * zero_span.WINDOW)) + p.reads = [] + self.assertFalse(zero_span.all_zero(p, 0, len(p))) + self.assertEqual(len(p.reads), 1) + + +def make_archive(path): + """RPF9 data area: one stream, a GAP of zero bytes, one more stream, and a short zero tail.""" + a = zlib.compress(b"A" * 1000) + b = zlib.compress(b"B" * 2000) + with open(path, "wb") as f: + f.write(b"9FPR" + struct.pack("> 20} MiB") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/anim_index.py b/tools/anim_index.py index fa3d0d589..bf913ed6a 100644 --- a/tools/anim_index.py +++ b/tools/anim_index.py @@ -30,6 +30,11 @@ import sys import unicodedata import zlib +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +from zero_span import gap_split # noqa: E402 + # zlib stream start, or a Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") PACK_NAMES = re.compile(rb"pack:/[^\x00]{1,200}") @@ -367,9 +372,6 @@ def collect_rbf0_dir(path): return bytes(blob) -def _gap(gap): - return (len(gap), 0) if gap.count(0) == len(gap) else (0, len(gap)) - def scan_rpf(path, start=None, limit=None, progress=None): """Walk an RPF9 data area. Returns (records, summary). No tables of contents are read or decrypted.""" @@ -396,7 +398,7 @@ def scan_rpf(path, start=None, limit=None, progress=None): if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): pos = s + 1 continue - z, u = _gap(m[last:s]) + z, u = gap_split(m, last, s) zero += z unread += u head = m[s:s + min(blen, 0x20)] @@ -422,14 +424,14 @@ def scan_rpf(path, start=None, limit=None, progress=None): pos = s + 1 continue used = p - s - len(d.unused_data) - z, u = _gap(m[last:s]) + z, u = gap_split(m, last, s) zero += z unread += u rows.append(classify(out, s, used)) last = pos = s + used if progress and len(rows) % 2000 == 0: progress(len(rows), pos, end) - z, u = _gap(m[last:end]) + z, u = gap_split(m, last, end) zero += z unread += u summary = summarise(rows, end - span_start, zero, unread) diff --git a/tools/bvh_index.py b/tools/bvh_index.py index 60ecd4b12..61478d8d2 100644 --- a/tools/bvh_index.py +++ b/tools/bvh_index.py @@ -45,6 +45,11 @@ from contextlib import suppress sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +from zero_span import gap_split # noqa: E402 + ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") TAG = 0x81020006 HEAD = 0x140 @@ -268,11 +273,9 @@ def scan_rpf(path, start=None, limit=None, max_inflate=1 << 28): pos = s + 1 continue head, kept, total, used = got - gap = m[last:s] - if gap.count(0) == len(gap): - zero += len(gap) - else: - unread += len(gap) + gap_zero, gap_unread = gap_split(m, last, s) + zero += gap_zero + unread += gap_unread row = classify(head, total, kept[-HEAD:] if len(kept) >= HEAD else kept) row.update(source=path, offset=s, stored=used, size=total) if row["kind"] in ("bvh4", "bvh4-chunk") and row["declared_bytes"] <= len(kept): @@ -281,11 +284,9 @@ def scan_rpf(path, start=None, limit=None, max_inflate=1 << 28): row["fill"]["total"] = len(body) rows.append(row) last = pos = s + used - tailgap = m[last:end] - if tailgap.count(0) == len(tailgap): - zero += len(tailgap) - else: - unread += len(tailgap) + gap_zero, gap_unread = gap_split(m, last, end) + zero += gap_zero + unread += gap_unread finally: m.close() return rows, [summarize(rows, path, span, zero, unread, time.time() - t0)] diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py index 87bcc7e78..30006e703 100644 --- a/tools/navmesh_decode.py +++ b/tools/navmesh_decode.py @@ -54,6 +54,11 @@ import zlib from collections import Counter from collections.abc import Iterator +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +from zero_span import gap_split # noqa: E402 + BASE = 0x50000000 ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") HEX_PREFIX = re.compile(r"^(?:0[xX])?([0-9a-fA-F]{6,})(?:[^0-9a-zA-Z]|$)") @@ -795,8 +800,8 @@ def _scan_rpf(path, start, limit, deep, rows): "checks_failed": " ".join(k for k, v in sorted(chk.items()) if not v)}) rows.append(row) if last < end: - gap = m[last:end] - carver["zero_padding" if gap.count(0) == len(gap) else "unread"] += len(gap) + gap_zero, gap_unread = gap_split(m, last, end) + carver["zero_padding" if not gap_unread else "unread"] += gap_zero + gap_unread return _summary(path, "rpf", start, end, carver, classes, checks, stats, time.time() - t0) @@ -811,8 +816,8 @@ def _account(m, carver, last, s, used, inflated, end): carver["past_window_stored"] += used return last if s > last and last < end: - gap = m[last:min(s, end)] - carver["zero_padding" if gap.count(0) == len(gap) else "unread"] += len(gap) + gap_zero, gap_unread = gap_split(m, last, min(s, end)) + carver["zero_padding" if not gap_unread else "unread"] += gap_zero + gap_unread carver["streams"] += 1 carver["stored"] += used carver["inflated"] += inflated diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py index ac6cb1984..14dc5a196 100644 --- a/tools/navmesh_index.py +++ b/tools/navmesh_index.py @@ -41,6 +41,7 @@ from file_mode import published_mode # noqa: E402 # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from report_paths import same_report_path # noqa: E402 +from zero_span import gap_split # noqa: E402 CHUNK = 1 << 20 HEAD = 0x80 @@ -129,11 +130,9 @@ def scan_archive(path, start=None, limit=None): pos = s + 1 continue used = p - s - len(d.unused_data) - gap = m[last:s] - if gap.count(0) == len(gap): - zero += len(gap) - else: - unread += len(gap) + gap_zero, gap_unread = gap_split(m, last, s) + zero += gap_zero + unread += gap_unread fields = page_fields(head) total += 1 total_stored += used @@ -141,11 +140,9 @@ def scan_archive(path, start=None, limit=None): if fields: rows.append({"source": path, "offset": s, "stored": used, "size": total_out, **fields}) last = pos = s + used - tail = m[last:end] - if tail.count(0) == len(tail): - zero += len(tail) - else: - unread += len(tail) + gap_zero, gap_unread = gap_split(m, last, end) + zero += gap_zero + unread += gap_unread span = end - start summary = { "input": path, "mode": "rpf", "start": start, "span": span, "streams": total, diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py index 628041574..d52925971 100644 --- a/tools/rbf0_index.py +++ b/tools/rbf0_index.py @@ -30,6 +30,11 @@ import struct import sys import zlib +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +from zero_span import gap_split # noqa: E402 + MAGIC = b"RBF0" PROLOGUE = b"\xfb\xff\x01\x00" # zlib stream start, or a Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. @@ -386,10 +391,9 @@ def scan_rpf(path, start=None, limit=None, progress=None, string_limit=16): if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): pos = s + 1 continue - gap = mm[last:s] - z = gap.count(0) == len(gap) - zero += len(gap) if z else 0 - unread += 0 if z else len(gap) + gap_zero, gap_unread = gap_split(mm, last, s) + zero += gap_zero + unread += gap_unread rows.append({"offset": s, "stored": blen, "size": blen, "head": mm[s:s + 8]}) last = pos = s + blen continue @@ -410,18 +414,16 @@ def scan_rpf(path, start=None, limit=None, progress=None, string_limit=16): pos = s + 1 continue used = p - s - len(d.unused_data) - gap = mm[last:s] - z = gap.count(0) == len(gap) - zero += len(gap) if z else 0 - unread += 0 if z else len(gap) + gap_zero, gap_unread = gap_split(mm, last, s) + zero += gap_zero + unread += gap_unread rows.append(_row(out, s, used)) last = pos = s + used if progress and len(rows) % 2000 == 0: progress(len(rows), pos, end) - gap = mm[last:end] - z = gap.count(0) == len(gap) - zero += len(gap) if z else 0 - unread += 0 if z else len(gap) + gap_zero, gap_unread = gap_split(mm, last, end) + zero += gap_zero + unread += gap_unread mspan = end - span_start with ArchiveReader(path) as reader: records = resources_from_rows(rows, reader.read, check_gap=True, string_limit=string_limit) diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py index 8ffbfe630..cc3905a41 100644 --- a/tools/restofworld_index.py +++ b/tools/restofworld_index.py @@ -29,6 +29,11 @@ import sys import time import zlib +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +from zero_span import gap_split # noqa: E402 + # zlib stream start, or Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") PSIN_TAGS = (b"LSCH", b"LENM", b"LSNS", b"LGID", b"LRSC", b"CHKS") @@ -269,9 +274,6 @@ def classify(data, offset, stored): return row -def _gap(gap): - return (len(gap), 0) if gap.count(0) == len(gap) else (0, len(gap)) - def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): """Walk an RPF9 data area. Returns (rows, summary). No TOC is read or decrypted.""" @@ -301,7 +303,7 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): pos = s + 1 continue - z, u = _gap(m[last:s]) + z, u = gap_split(m, last, s) zero += z unread += u rows.append(classify(m[s:s + 256], s, blen)) @@ -348,14 +350,14 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): pos = s + 1 continue used = p - s - len(d.unused_data) - z, u = _gap(m[last:s]) + z, u = gap_split(m, last, s) zero += z unread += u row = classify(bytes(body) if keep_body and body else head, s, used) row["size"] = total rows.append(row) last = pos = s + used - z, u = _gap(m[last:end]) + z, u = gap_split(m, last, end) zero += z unread += u summary = summarise(rows, end - span_start, zero, unread) diff --git a/tools/rpf9_names.py b/tools/rpf9_names.py index 862be4622..af823c0a6 100644 --- a/tools/rpf9_names.py +++ b/tools/rpf9_names.py @@ -27,6 +27,7 @@ import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 +from zero_span import gap_split # noqa: E402 # zlib stream start, or a Bink 2 video ('KB2' + revision letter, then u32 size-8). ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") @@ -114,11 +115,9 @@ def scan_archive(archive, start=None, limit=None, max_inflate=1 << 20, types=("d if not (64 <= blen <= end - s and 16 <= w <= 8192 and 16 <= h <= 8192): pos = s + 1 continue - gap = m[last:s] - if gap.count(0) == len(gap): - zero += len(gap) - else: - unread += len(gap) + gap_zero, gap_unread = gap_split(m, last, s) + zero += gap_zero + unread += gap_unread bink2_files += 1 bink2_bytes += blen last = pos = s + blen @@ -153,11 +152,9 @@ def scan_archive(archive, start=None, limit=None, max_inflate=1 << 20, types=("d if used <= 0: pos = s + 1 continue - gap = m[last:s] - if gap.count(0) == len(gap): - zero += len(gap) - else: - unread += len(gap) + gap_zero, gap_unread = gap_split(m, last, s) + zero += gap_zero + unread += gap_unread streams += 1 names = extract_names(prefix, types) if b".#" in prefix else [] if names: @@ -172,11 +169,9 @@ def scan_archive(archive, start=None, limit=None, max_inflate=1 << 20, types=("d progress(f"{streams} streams, {len(rows)} with names, " f"{(pos - (data_start if start is None else start)) / span:.1%}, " f"{time.time() - t0:.0f}s") - tail = m[last:end] - if tail.count(0) == len(tail): - zero += len(tail) - else: - unread += len(tail) + gap_zero, gap_unread = gap_split(m, last, end) + zero += gap_zero + unread += gap_unread span = end - (data_start if start is None else start) by_type = {} for suffix in unique.values(): diff --git a/tools/story_index.py b/tools/story_index.py index ced0c3240..35a53ed56 100644 --- a/tools/story_index.py +++ b/tools/story_index.py @@ -36,6 +36,7 @@ import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from anim_index import aux_table # noqa: E402 from file_mode import published_mode # noqa: E402 +from zero_span import gap_split # noqa: E402 # zlib stream start, or a Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") @@ -159,9 +160,6 @@ def classify(data, offset, stored): return record -def _gap(gap): - return (len(gap), 0) if gap.count(0) == len(gap) else (0, len(gap)) - def scan_rpf(path, start=None, limit=None, progress=None): """Walk an RPF9 data area. Returns (records, summary). No tables of contents are read or decrypted.""" @@ -192,7 +190,7 @@ def scan_rpf(path, start=None, limit=None, progress=None): if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): pos = s + 1 continue - z, u = _gap(m[last:s]) + z, u = gap_split(m, last, s) zero += z unread += u record = classify(head, s, blen) @@ -217,14 +215,14 @@ def scan_rpf(path, start=None, limit=None, progress=None): pos = s + 1 continue used = p - s - len(d.unused_data) - z, u = _gap(m[last:s]) + z, u = gap_split(m, last, s) zero += z unread += u rows.append(classify(out, s, used)) last = pos = s + used if progress and len(rows) % 2000 == 0: progress(len(rows), pos, end) - z, u = _gap(m[last:end]) + z, u = gap_split(m, last, end) zero += z unread += u if size: diff --git a/tools/zero_span.py b/tools/zero_span.py new file mode 100644 index 000000000..a1938522e --- /dev/null +++ b/tools/zero_span.py @@ -0,0 +1,33 @@ +"""Classify the bytes between two carved streams without copying them. + +The archive scanners count the bytes they could not read as either zero padding or unread data: a gap counts as +padding only when every byte in it is zero. Slicing an mmap copies the slice, so `gap = m[last:s]` allocates the +whole gap at once. On a large archive a gap can run to gigabytes (story000.rpf, about 20 GB, cannot be indexed on +a 16 GB machine that way), so the gap is compared against zeros one window at a time instead, and the first +non-zero window ends the check. +""" + +WINDOW = 1 << 22 # 4 MiB: the most a check allocates, besides the shared zero block +_ZEROS = bytes(WINDOW) + + +def all_zero(buf, start: int, end: int) -> bool: + """True when buf[start:end] is empty or all zero bytes. Reads at most WINDOW bytes at a time.""" + end = min(end, len(buf)) + p = start + while p < end: + q = min(end, p + WINDOW) + if buf[p:q] != _ZEROS[:q - p]: + return False + p = q + return True + + +def gap_split(buf, start: int, end: int) -> tuple[int, int]: + """(zero_padding, unread) bytes for the gap buf[start:end], counted as the scanners always have: all of + it is padding when every byte is zero, otherwise all of it is unread. The range is clipped to the buffer + the way a slice is, so the counts match len(buf[start:end]).""" + end = min(end, len(buf)) + start = min(start, end) + n = end - start + return (n, 0) if all_zero(buf, start, end) else (0, n)