"""Synthetic tests for tools/navmesh_decode.py. No game files are read or needed.""" import csv 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__))) sys.path.insert(0, os.path.join(ROOT, "tools")) import navmesh_decode as nd # noqa: E402 TOOL = os.path.join(ROOT, "tools", "navmesh_decode.py") BASE = nd.BASE def make_rpf(path, streams, data_start=0x40, pad_between=0): buf = bytearray(data_start) buf[0:4] = b"9FPR" struct.pack_into("= cur) else ((cur + 7) & ~7) need = q40_off + 4 + 8 * len(q40_items) + sum(sz for _, sz in q40_items) if need > len(buf): buf.extend(bytes(need - len(buf))) struct.pack_into("> 9 x0, y0, dx, dy, dz = (sx - 256) * 128.0, (sy - 256) * 128.0, 128.0, 128.0, 16.0 if not has_links: n_links = n_link_idx = 0 n_polys = len(poly_sizes) pool = sum(poly_sizes) # Fixed header at +0x00..+0xEF. struct.pack_into(" len(buf): buf.extend(bytes(cur - len(buf))) return off # Special links (+0xA8) and index table (+0xB0). if has_links: la = alloc(32 * n_links) lb = alloc(2 * n_link_idx) for k in range(n_link_idx): val = n_links if (corrupt_link_idx and k == 0) else (k % n_links) struct.pack_into(" 1 child leaf node -> leaf_data -> u16[n_polys]. root = alloc(0x60) child = alloc(0x60) leaf = alloc(0x20) lpolys = alloc(2 * n_polys) for k in range(n_polys): struct.pack_into("> 3 for k in keys if k != 1} words = [0x0000FF00 if k in parents else 0x00020001 for k in keys] table_end = 0x60 + nd.GRID_GROUP * groups bm_off = (table_end + 15) & ~15 payload_off = (bm_off + 32 + 15) & ~15 total = payload_off + 4 * entries buf = bytearray(total) sx, sy = sector & 0x1FF, sector >> 9 ox, oy = (sx - 256) * 128.0, (sy - 256) * 128.0 decl = entries if declared_entries is None else declared_entries struct.pack_into("I", 64) + bytes(56) sec2 = b"CHKS" + struct.pack(">I", 20) + bytes(12) table = bytes(0x40) first = 16 + len(table) hdr = b"PSIN" + struct.pack(">I", first) + struct.pack(" 8 -> 64 -> 512 (depths 0..3), plus leaves 9, 10, 65. keys = [1, 8, 64, 512, 9, 10, 65] words = [0xFF00, 0xFF00, 0xFF00, 0x00007803, 0xFF00, 0x00060F01, 0x00000002] good = build_grid(entries=7, keys=keys, words=words) bad = [ build_grid(entries=3, keys=[8, 9, 10]), # no root build_grid(entries=3, keys=[1, 8, 72]), # 72 >> 3 == 9 is absent build_grid(entries=3, keys=[1, 8, 16]), # 16 has its top bit at 4, not 3 or 6 build_grid(entries=3, keys=[1, 0, 8]), # 0 is not a key build_grid(entries=3, keys=[1, 8, 8]), # two slots share key 8 build_grid(entries=3, keys=[1, 8, 9], words=[0x01, 0x01, 0x01]), # inner root without 0xff00 build_grid(entries=3, keys=[1, 8, 64], words=[0xFF00, 0x01, 0x01]), # inner 8 without 0xff00 ] # 17 keys over two groups: 8 sits in slot 15 of group 0 and 9 in group 1, both parents of other keys. two_groups = build_grid(groups=2, entries=17, keys=[1] + list(range(64, 78)) + [8, 9]) # Payload pointer past the end: the table is accepted but the words are not read. oob = bytearray(build_grid(entries=3)[0]) struct.pack_into("0, broken chain, qt cycle. streams += build_navmesh(corrupt_checksum=True, corrupt_vidx=True, corrupt_link_idx=True, corrupt_null_vol=True, corrupt_chain=True, qt_cycle=True) # 4. Corrupt grid: bad control byte + duplicate value. streams += build_grid(bad_ctrl=True, dup_value=True) # 5. Adversarial OOM-DoS grid: u32@0x14 == u32@0x50 == 0xFFFFFFFF with 8 empty groups. streams += build_grid(groups=8, entries=0, declared_entries=0xFFFFFFFF) # 6. Truncated PSIN (placed last so it does not consume later streams). streams += build_psin(truncate=True) with tempfile.TemporaryDirectory() as tmp: arc = os.path.join(tmp, "bad.rpf") make_rpf(arc, streams) rows = [] doc = nd.scan(arc, deep=True, rows=rows) self.assertNotIn("runtime_data_end", rows[1]) # out-of-bounds instance block json.dumps(doc, allow_nan=False) # Separate archives for MAX_STREAMS-capped resources so they cannot swallow other test fixtures. arc_cap_0drp = os.path.join(tmp, "cap_0drp.rpf") make_rpf(arc_cap_0drp, build_0drp(total_size=0x2000, bad_bm_streams=100) + [bytes(64)] * (nd.MAX_STREAMS + 2)) capped_rows = [] doc_cap_0drp = nd.scan(arc_cap_0drp, deep=True, rows=capped_rows) self.assertNotIn("runtime_data_end", capped_rows[0]) # incomplete block map arc_cap_psin = os.path.join(tmp, "cap_psin.rpf") big_psin = b"PSIN" + struct.pack(">I", 0x2000) + struct.pack("4sI", b"PSIN", 64) + bytes(56)) out = os.path.join(tmp, "out.json") proc = subprocess.run([sys.executable, "-I", TOOL, carve, "--quiet", "--out", out], capture_output=True, text=True) self.assertEqual(proc.returncode, 0, proc.stderr) with open(out, encoding="utf-8") as f: doc = json.load(f) self.assertEqual(doc["resources"]["psin"]["resources"], 1) self.assertEqual(doc["resources"]["psin"]["incomplete"], 1) self.assertEqual(doc["psin"]["complete"], 0) def test_header_only_psin_does_not_swallow_the_next_resource(self): with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.mkdir(carve) with open(os.path.join(carve, "000000000000.bin"), "wb") as f: f.write(struct.pack(">4sI", b"PSIN", 64) + bytes(56)) with open(os.path.join(carve, "000000000040.bin"), "wb") as f: f.write(struct.pack(">4sI", b"PSIN", 64) + bytes(56) + struct.pack(">4sI", b"SECT", 64) + bytes(56)) out = os.path.join(tmp, "out.json") proc = subprocess.run([sys.executable, "-I", TOOL, carve, "--quiet", "--out", out], capture_output=True, text=True) self.assertEqual(proc.returncode, 0, proc.stderr) with open(out, encoding="utf-8") as f: doc = json.load(f) self.assertEqual(doc["resources"]["psin"]["resources"], 2) self.assertEqual(doc["resources"]["psin"]["incomplete"], 1) self.assertEqual(doc["psin"]["complete"], 1) def test_carved_directory_mode_and_window_limit(self): sector = (260 << 9) | 250 p0, p1 = build_0drp(total_size=0x1000, split_at=0x1000, node_count=2, override_n4e=0) nav = build_navmesh(sector=sector)[0] g0, g1 = build_grid(sector=sector, two_streams=True) with tempfile.TemporaryDirectory() as tmp: empty_dir = os.path.join(tmp, "empty") os.mkdir(empty_dir) edoc = nd.scan(empty_dir, deep=True) self.assertEqual(edoc["resources"], {}) carve = os.path.join(tmp, "carve") os.mkdir(carve) for off, blob in ((0x001000, p0), (0x002000, p1), (0x003000, nav), (0x004000, g0), (0x005000, g1)): with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f: f.write(blob) doc = nd.scan(carve, deep=True) self.assertEqual(doc["mode"], "directory") self.assertEqual(doc["resources"]["0drp"]["resources"], 1) self.assertEqual(doc["resources"]["navmesh"]["resources"], 1) self.assertEqual(doc["resources"]["grid"]["resources"], 1) self.assertEqual(doc["0drp"]["pages_4k_boundary"], {"zero": 1}) for cls, table in doc["checks"].items(): for name, counts in table.items(): self.assertEqual(counts["fail"], 0, f"{cls}.{name} failed: {counts}") # Window --limit stops after a resource whose >=64 B continuation crosses --limit. arc = os.path.join(tmp, "win.rpf") offs = make_rpf(arc, [g0, g1, nav]) win = nd.scan(arc, start=offs[0], limit=offs[1] - offs[0], deep=True) self.assertEqual(win["resources"]["grid"]["resources"], 1) self.assertNotIn("navmesh", win["resources"]) # The continuation starts at the window's end: decoded as part of the grid, but carved past the # window, so the carver counts match navmesh_index.py on the same window (#766). self.assertEqual(win["carver_streams"]["streams"], 1) self.assertEqual(win["carver_streams"]["past_window"], 1) c = win["carver_streams"] self.assertEqual(c["stored"] + c["zero_padding"] + c["unread"], win["span"]) def test_limit_inside_a_stream_counts_nothing_past_the_window(self): """--limit ending inside the first of two streams: nothing is carved, and the byte classes add up to the span, as navmesh_index.py reports for the same window.""" import hashlib noisy = lambda seed: b"".join(hashlib.sha256(bytes([seed, i])).digest() for i in range(128)) with tempfile.TemporaryDirectory() as tmp: arc = os.path.join(tmp, "w.rpf") offs = make_rpf(arc, [noisy(1), noisy(2)]) doc = nd.scan(arc, start=offs[0], limit=0x100) c = doc["carver_streams"] self.assertEqual((c["streams"], c["stored"]), (0, 0)) self.assertEqual(c["stored"] + c["zero_padding"] + c["unread"], doc["span"]) self.assertEqual(c["past_window"], 1) def test_cli_rejects_shared_report_destination(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) output = os.path.join(tmp, "nav.navmesh-decode.json") result = subprocess.run( [sys.executable, "-I", TOOL, archive, "--csv", output, "--quiet"], cwd=tmp, capture_output=True, text=True, ) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("--out and --csv must use different paths", result.stderr) self.assertFalse(os.path.exists(output)) def test_cli_creates_missing_output_folders(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) out_json = os.path.join(tmp, "reports", "deep", "nav.json") out_csv = os.path.join(tmp, "tables", "nav.csv") result = subprocess.run( [sys.executable, "-I", TOOL, archive, "--out", out_json, "--csv", out_csv, "--quiet"], capture_output=True, text=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertNotIn("Traceback", result.stderr) with open(out_json, encoding="utf-8") as f: self.assertEqual(json.load(f)["resources"]["0drp"]["resources"], 1) with open(out_csv, newline="", encoding="utf-8") as f: self.assertEqual(len(list(csv.DictReader(f))), 1) def test_cli_reports_a_blocked_report_parent(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) blocker = os.path.join(tmp, "blocked") with open(blocker, "wb") as f: f.write(b"keep") for flag in ("--out", "--csv"): with self.subTest(flag=flag): target = os.path.join(blocker, "nav" + (".json" if flag == "--out" else ".csv")) command = [sys.executable, "-I", TOOL, archive, flag, target, "--quiet"] result = subprocess.run(command, cwd=tmp, capture_output=True, text=True) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn(target, result.stderr) self.assertNotIn("Traceback", result.stderr) with open(blocker, "rb") as f: self.assertEqual(f.read(), b"keep") def test_cli_refuses_to_overwrite_its_input(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) with open(archive, "rb") as f: original = f.read() for flag in ("--out", "--csv"): result = subprocess.run( [sys.executable, "-I", TOOL, archive, flag, archive, "--quiet"], capture_output=True, text=True, check=False, ) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("would overwrite the input", result.stderr) self.assertNotIn("Traceback", result.stderr) with open(archive, "rb") as f: self.assertEqual(f.read(), original, f"{flag} touched the input") def test_cli_protects_carved_inputs_from_reports(self) -> None: with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.mkdir(carve) source = os.path.join(carve, "000000.bin") original = build_navmesh()[0] with open(source, "wb") as f: f.write(original) alias = os.path.join(tmp, "alias.csv") targets = [("--out", source), ("--csv", source)] try: os.link(source, alias) except (OSError, NotImplementedError) as e: with self.subTest(flag="--csv", target=alias): self.skipTest(f"hard links unavailable: {e}") else: targets.append(("--csv", alias)) out = os.path.join(carve, "report.json") csv_path = os.path.join(carve, "report.csv") command = [sys.executable, "-I", TOOL, carve, "--quiet"] for _ in range(2): result = subprocess.run([*command, "--out", out, "--csv", csv_path], capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) for flag, target in targets: with self.subTest(flag=flag, target=target): with open(source, "wb") as f: f.write(original) result = subprocess.run([*command, flag, target], cwd=tmp, capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("would overwrite the input", result.stderr) with open(source, "rb") as f: self.assertEqual(f.read(), original) def test_reports_do_not_replace_the_carve_manifest(self): with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.mkdir(carve) manifest = os.path.join(carve, "index.json") before = b'{"files": []}' with open(manifest, "wb") as f: f.write(before) for tool in ("navmesh_decode.py", "navmesh_index.py"): for flag in ("--out", "--csv"): with self.subTest(tool=tool, flag=flag): result = subprocess.run( [sys.executable, "-I", os.path.join(os.path.dirname(TOOL), tool), carve, flag, manifest], cwd=tmp, capture_output=True, text=True, ) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("would overwrite", result.stderr) self.assertIn("index.json", result.stderr) with open(manifest, "rb") as f: self.assertEqual(f.read(), before) def test_cli_rejects_bad_arguments_and_files(self): with tempfile.TemporaryDirectory() as tmp: empty = os.path.join(tmp, "empty.rpf") with open(empty, "wb"): pass tiny = os.path.join(tmp, "tiny.rpf") with open(tiny, "wb") as f: f.write(b"9FPR123") bad_ver = os.path.join(tmp, "badver.rpf") with open(bad_ver, "wb") as f: f.write(b"6FPR" + bytes(32)) arc = os.path.join(tmp, "ok.rpf") make_rpf(arc, build_0drp()) for args in ( [arc, "--limit", "0"], [arc, "--limit", "-5"], [arc, "--start", "-1"], [arc, "--start", "999999"], [empty], [tiny], [bad_ver], [tmp, "--limit", "64"], ): proc = subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) self.assertNotEqual(proc.returncode, 0, f"expected failure for {args}") self.assertNotIn("Traceback", proc.stderr) class OutputPathTest(unittest.TestCase): """A report path that is already a folder is a usage error, not a PermissionError traceback.""" def test_out_that_is_a_directory_is_refused(self): with tempfile.TemporaryDirectory() as tmp: source, out = os.path.join(tmp, "carved"), os.path.join(tmp, "reports") os.makedirs(source) os.makedirs(out) r = subprocess.run([sys.executable, "-I", TOOL, source, "--out", out], capture_output=True, text=True, timeout=120) self.assertEqual(r.returncode, 2, r.stderr) self.assertIn("--out is a directory", r.stderr) self.assertNotIn("Traceback", r.stderr) if __name__ == "__main__": unittest.main()