"""Synthetic tests for tools/psin_data.py (no game data: every hash is the joaat of an invented name).""" import json import os import struct import subprocess import sys import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOL = os.path.join(ROOT, "tools", "psin_data.py") sys.path.insert(0, os.path.join(ROOT, "tools")) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import psin_data as D # noqa: E402 from test_psin_index import joaat, make_lenm, make_lsch, make_section # noqa: E402 def ptr(block, offset=0): """A PSIN pointer: block number in the low 20 bits, byte offset above.""" return block | (offset << 20) def make_container(blocks, structs, enums=(), root=1, end_row=True, fill=b"\xaa" * 8): """blocks: [(type, bytes)]. Returns a complete PSIN container with LSCH, LENM, LRSC (root at +0x10) and CHKS.""" rows = b"".join(struct.pack("I", first + len(sections) + 16) + b"\0" * 4) return b"PSIN" + struct.pack(">I", first) + rows + bytes(data) + sections ROOT_T, ITEM_T, STR_T = joaat("RootThing"), joaat("ItemThing"), 0x10 KIND = joaat("KindEnum") # RootThing (0x90 bytes): every container shape the decoder reads. ROOT_MEMBERS = [ (0x100, 0, 0x05, 0, 0, ITEM_T), # 0: element descriptor, ItemThing (0x100, 0, 0x15, 0, 0, 0), # 1: element descriptor, u32 (0x100, 0, 0x4A, 0, 0, 0), # 2: element descriptor, u32 hash (map key) (joaat("items"), 0x00, 0x5C, 0, 0, 0), # {u32 count, u32 capacity, ptr} -> ItemThing[] (joaat("values"), 0x10, 0x52, 0, 1, 0), # {ptr, u16 count, u16 capacity} -> u32[] (joaat("sorted"), 0x20, 0x71, 0, 0, 2 | (1 << 16)), # binary map u32 hash -> u32 (joaat("hashed"), 0x38, 0x75, 0, 0, 2 | (1 << 16)), # SwissTable u32 hash -> u32 (joaat("open"), 0x48, 0x73, 0, 0, 2 | (1 << 16)), # open addressing u32 hash -> u32 (joaat("child"), 0x58, 0x07, 0, 0, 0), # pointer to an ItemThing block (joaat("label"), 0x60, 0x42, 0, 0, 0), # string pointer (joaat("short"), 0x68, 0x44, 0, 0, 0), # 16-byte string, stored in place (joaat("kind"), 0x78, 0x62, 0, 0, KIND), # 32-bit enum (joaat("fixed"), 0x7C, 0x50, 0, 1, 3), # u32[3] in place (joaat("odd"), 0x88, 0x77, 0, 0, 0), # a type this tool does not decode ] SCHEMA = [ (ROOT_T, 0x1, 0x90, 3, ROOT_MEMBERS), (ITEM_T, 0x2, 0x8, 2, [(joaat("x"), 0, 0x21, 0, 0, 0), (joaat("n"), 4, 0x15, 0, 0, 0)]), ] ENUMS = [(KIND, 0x3, [(0, joaat("KIND_A")), (1, joaat("KIND_B"))])] def sample(kind=1): """Blocks: 1 root, 2 ItemThing[2], 3 u32[3], 4 map pairs, 5 SwissTable group, 6 open slots, 7 one ItemThing, 8 strings.""" k1, k2 = joaat("alpha"), joaat("beta") lo, hi = sorted((k1, k2)) root = bytearray(0x90) struct.pack_into("I", blob, 4)[0] blocks, fills = D.block_table(blob, first) self.assertTrue(fills) self.assertEqual([(t, s) for t, _, s in blocks], [(0x15, 4), (0x16, 17)]) self.assertEqual(blocks[0][1] % 16, 0) self.assertEqual(blocks[1][1], blocks[0][1] + 16) def test_missing_end_row(self): blob = make_container([(0x15, b"\0" * 4)], [], end_row=False) with self.assertRaisesRegex(ValueError, "fill|padding"): D.block_table(blob, struct.unpack_from(">I", blob, 4)[0]) def test_bad_fill(self): blob = make_container([(0x15, b"\0" * 4)], [], fill=b"\0" * 8) with self.assertRaisesRegex(ValueError, "fill"): D.block_table(blob, struct.unpack_from(">I", blob, 4)[0]) def test_blocks_past_the_region_are_rejected(self): # A damaged size must not make the walker allocate gigabytes (review on #1077). blob = bytearray(make_container([(0x15, b"\0" * 4), (0x16, b"\0" * 32)], [])) struct.pack_into("I", blob, 4)[0]) stats = __import__("collections").Counter() self.assertFalse(D.measure(bytes(blob), stats)) self.assertEqual(stats["containers"], 0) def test_first_row_is_what_psin_index_calls_version(self): blob = make_container([(0x16, b"\0" * 0x230)], []) record = D.psin_index.parse(blob) self.assertEqual((record["version"], record["table_bytes"]), (0x16, 0x230)) def test_first_section_out_of_range_and_overrunning_end_padding_rejected(self): with self.assertRaisesRegex(ValueError, "outside"): D.block_table(b"PSIN" + b"\0" * 12, 32) with self.assertRaisesRegex(ValueError, "outside"): D.block_table(b"PSIN" + b"\0" * 12, 4) # first = 28: one 16-byte row at 8..24, then end padding at 24..32 overruns first. overrun = b"PSIN" + struct.pack(">I", 28) + struct.pack("= 2**31 for 0x62 enums. for listed, stored in ((-1, -1), (0xFFFFFFF0, -16)): c = D.Container(sample(kind=stored)) c.enums[KIND]["values"].append({"value": listed, "name": joaat("KIND_X")}) stats = __import__("collections").Counter() tree = D.Walker(c, stats, keep=True).run() self.assertEqual(stats["enum value listed"], 1) self.assertEqual(stats["enum value not listed"], 0) self.assertEqual(tree[f"{joaat('kind'):08x}"], listed) def test_bad_pointer_is_counted_not_followed(self): blob = bytearray(sample()) root_at = D.Container(bytes(blob)).blocks[0][1] struct.pack_into("I", 16) + b"\x70" * 8 + make_section("CHKS", b"\0" * 8) self.assertFalse(D.measure(blob, stats)) self.assertEqual(stats["skipped: no LSCH or LRSC section"], 1) def test_root_out_of_range(self): blob = make_container([(ROOT_T, b"\0" * 0x90)], SCHEMA, ENUMS, root=3) stats = __import__("collections").Counter() self.assertTrue(D.measure(blob, stats)) self.assertEqual(stats["root out of range"], 1) def test_inline_and_fixed_arrays_are_bounded_to_enclosing_block(self): # 16-byte block with 0x54 inline array of char[4] claiming count=capacity=50000: # must be rejected as out of bounds rather than performing 50,000 OOB reads. inline_schema = [(0xAAAA0002, 0, 16, 2, [ (0x22222222, 0, 0x54, 0, 1, 0), (0x00000100, 0, 0x40, 0, 0, 4), ])] blob = make_container([(0xAAAA0002, struct.pack(" 16). fixed_schema = [(0xAAAA0003, 0, 16, 2, [ (0x33333333, 0, 0x50, 0, 1, 100), (0x00000100, 0, 0x40, 0, 0, 4), ])] blob2 = make_container([(0xAAAA0003, bytes(16))], fixed_schema, []) stats2 = __import__("collections").Counter() self.assertTrue(D.measure(blob2, stats2)) self.assertEqual(stats2["fixed array out of bounds"], 1) self.assertEqual(stats2["char arrays"], 0) def test_map_75_zero_groups_is_not_power_of_two(self): map_schema = [(0xAAAA0001, 0, 16, 2, [ (0x11111111, 0, 0x75, 0, 0, (2 << 16) | 1), (0x00000100, 0, 0x15, 0, 0, 0), (0x00000100, 0, 0x15, 0, 0, 0), ])] blob = make_container([(0xAAAA0001, struct.pack(" past 16 (joaat("arr"), 8, 0x5C, 0, 0, 0), # 16-byte header at +8 -> past 16 (joaat("smap"), 4, 0x71, 0, 0, 0 | (0 << 16)), # 20-byte header at +4 -> past 16 (joaat("inline"), 12, 0x54, 0, 0, 0), # 8-byte header at +12 -> past 16 ])] blob = make_container([(0xAAAA0014, bytes(16))], schema, []) stats = __import__("collections").Counter() self.assertTrue(D.measure(blob, stats)) self.assertEqual(stats["walk error"], 0) self.assertEqual(stats["member past block end"], 3) self.assertEqual(stats["inline array out of bounds"], 1) def test_short_string_length_mismatch_and_oob_slot(self): # Length byte claims 64 bytes in a 16-byte short-string slot: must return None, not read into LSCH. schema = [(0xAAAA0015, 1, 16, 2, [(joaat("short"), 0, 0x44, 0, 0, 0)])] payload = bytearray(b"A" * 15 + bytes([0x80 | 64])) blob = make_container([(0xAAAA0015, bytes(payload))], schema, []) stats = __import__("collections").Counter() tree = D.Walker(D.Container(blob), stats, keep=True).run() self.assertEqual(tree, {f"{joaat('short'):08x}": None}) self.assertEqual(stats["short string length mismatch"], 1) self.assertEqual(stats["short strings in place"], 0) # Short-string slot starting at +8 in a 16-byte block extends past the block end. oob_schema = [(0xAAAA0016, 1, 16, 2, [(joaat("short"), 8, 0x44, 0, 0, 0)])] blob2 = make_container([(0xAAAA0016, bytes(16))], oob_schema, []) stats2 = __import__("collections").Counter() tree2 = D.Walker(D.Container(blob2), stats2, keep=True).run() self.assertEqual(tree2, {f"{joaat('short'):08x}": None}) self.assertEqual(stats2["member past block end"], 1) def test_self_referential_array_and_map_cycles_terminate_and_dag_sharing_works(self): # Branching 0x5C array cycle: element 0 is a 0x5C pointing back to block 2 (count=2). arr_schema = [(0xAAAA0020, 1, 16, 3, [ (0x00000100, 0, 0x5C, 0, 0, 0), # element 0: recursive 0x5C array (joaat("loop"), 0, 0x5C, 0, 0, 0), ])] hdr = struct.pack("