upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tests/test_imhex_patterns.py
diff options
context:
space:
mode:
authorLeonardo Guimaraes <leozinhoszg@gmail.com>2026-11-22 11:14:51 -0300
committerLeonardo Guimaraes <leozinhoszg@gmail.com>2026-11-22 11:14:51 -0300
commit52dc48074dafb4eed77857bde941a5cb73ca3263 (patch)
tree75797edf7d5b2f9581eeddfe10c7d6a0b43f8183 /tests/test_imhex_patterns.py
parent60c624ec9b37a7a0b3612200970827c33dd0c90a (diff)
tools/imhex: ImHex pattern for PSIN containers
psin.hexpat lays out a container as docs/psin.md describes it: the big-endian first-section offset, the instance-data block table (rows, the pppppppp end) and its blocks as raw bytes, the section chain, LSCH struct headers and members and LENM enums and values (header count by the fill-exact rule psin_index.py uses), the LSNS block table with opaque 16-byte records, the LRSC 0DRP version and root block, and the CHKS file size. A section past the end of a truncated stream is shown as raw bytes. tests/test_imhex_patterns.py builds a synthetic container from the invented schema in test_psin_index.py, checks it with psin_index.parse and psin_data.block_table, and when ImHex is installed compares the pattern's output with both, plus a container cut inside LENM.
Diffstat (limited to 'tests/test_imhex_patterns.py')
-rw-r--r--tests/test_imhex_patterns.py88
1 files changed, 87 insertions, 1 deletions
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py
index 9e0cc1cca..751de8b90 100644
--- a/tests/test_imhex_patterns.py
+++ b/tests/test_imhex_patterns.py
@@ -3,7 +3,9 @@
3 python -I tests/test_imhex_patterns.py 3 python -I tests/test_imhex_patterns.py
4 4
5Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with 5Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with
6tools/rbf0_index.py, the repository's own parser. When ImHex is installed, each pattern then runs on the same bytes 6tools/rbf0_index.py and the PSIN inputs with tools/psin_index.py and tools/psin_data.py, the repository's own
7parsers (the PSIN schema reuses the invented names of tests/test_psin_index.py). When ImHex is installed, each pattern
8then runs on the same bytes
7through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the 9through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the
8parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it 10parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it
9the ImHex half is skipped and the rest still runs. 11the ImHex half is skipped and the rest still runs.
@@ -20,8 +22,12 @@ import unittest
20ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 22ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21PATTERNS = os.path.join(ROOT, "tools", "imhex") 23PATTERNS = os.path.join(ROOT, "tools", "imhex")
22sys.path.insert(0, os.path.join(ROOT, "tools")) 24sys.path.insert(0, os.path.join(ROOT, "tools"))
25sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23 26
27import psin_data # noqa: E402
28import psin_index # noqa: E402
24import rbf0_index # noqa: E402 29import rbf0_index # noqa: E402
30from test_psin_index import SCHEMA as PSIN_SCHEMA, joaat, make_lenm, make_lsch, make_section # noqa: E402
25 31
26 32
27def find_imhex(): 33def find_imhex():
@@ -69,6 +75,27 @@ def rpf9_archive(data_offset=0x100, size=0x140):
69 return head + toc + body 75 return head + toc + body
70 76
71 77
78PSIN_BLOCKS = [(PSIN_SCHEMA[0][0], bytes(range(0x20))), (0x10, b"probe\x00"), (0x16, struct.pack("<3Q", 1, 2, 3))]
79PSIN_ENUMS = [(joaat("ProbeEnum"), 0x33333333, [(0, joaat("PROBE_A")), (-1, joaat("PROBE_B"))])]
80LSNS_BLOCKS = [(0x101, 32), (0x207, 16)]
81
82
83def psin_container(lsns=True):
84 """A complete container (docs/psin.md): block table, blocks, LSCH, LENM, LSNS, LGID, LRSC (root 1), CHKS."""
85 rows = b"".join(struct.pack("<II", t, len(d)) + b"\xaa" * 8 for t, d in PSIN_BLOCKS) + b"\x70" * 8
86 data = b"".join(d + bytes(-len(d) % 16) for _t, d in PSIN_BLOCKS)
87 first = 8 + len(rows) + len(data)
88 lsns_payload = struct.pack("<I", len(LSNS_BLOCKS)) + b"".join(struct.pack("<II", k, n) for k, n in LSNS_BLOCKS)
89 lsns_payload += bytes((i * 29) & 0xFF for i in range(sum(n for _k, n in LSNS_BLOCKS)))
90 lrsc = b"0DRP" + struct.pack("<I", 122) + bytes(8) + struct.pack("<I", 1) + bytes(12)
91 sections = make_section("LSCH", make_lsch(PSIN_SCHEMA)) + make_section("LENM", make_lenm(PSIN_ENUMS))
92 if lsns:
93 sections += make_section("LSNS", lsns_payload)
94 sections += make_section("LGID") + make_section("LRSC", lrsc)
95 sections += make_section("CHKS", struct.pack(">I", first + len(sections) + 16) + b"\x12\x34\x56\x78")
96 return b"PSIN" + struct.pack(">I", first) + rows + data + sections
97
98
72def pragma_magic(pattern): 99def pragma_magic(pattern):
73 """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file.""" 100 """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file."""
74 with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f: 101 with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f:
@@ -92,9 +119,20 @@ class InputsAndMagic(unittest.TestCase):
92 self.assertEqual(r["elements"], 2) 119 self.assertEqual(r["elements"], 2)
93 self.assertEqual(r["descriptors"], 7) 120 self.assertEqual(r["descriptors"], 7)
94 121
122 def test_synthetic_psin_parses(self):
123 blob = psin_container()
124 r = psin_index.parse(blob, schema=True)
125 self.assertTrue(r["complete"], r["error"])
126 self.assertEqual(r["schema"]["reason"], "")
127 self.assertEqual(r["lsns_blocks"], len(LSNS_BLOCKS))
128 blocks, exact = psin_data.block_table(blob, r["first_section"])
129 self.assertTrue(exact)
130 self.assertEqual([(t, n) for t, _at, n in blocks], [(t, len(d)) for t, d in PSIN_BLOCKS])
131
95 def test_pattern_magics(self): 132 def test_pattern_magics(self):
96 self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC) 133 self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC)
97 self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md) 134 self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md)
135 self.assertEqual(pragma_magic("psin.hexpat"), psin_index.MAGIC)
98 136
99 137
100@unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)") 138@unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)")
@@ -160,6 +198,54 @@ class PatternsInImHex(unittest.TestCase):
160 self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22)) 198 self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22))
161 self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10) 199 self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10)
162 200
201 def test_psin_matches_psin_index_and_psin_data(self):
202 blob = psin_container()
203 ref = psin_index.parse(blob, schema=True)
204 table, _exact = psin_data.block_table(blob, ref["first_section"])
205 got, log = self.run_pattern("psin.hexpat", blob)
206 self.assertIsNotNone(got, log)
207 self.assertEqual(got["header"]["first_section"], ref["first_section"])
208
209 # Block table: rows, the "pppppppp" end, and each block's data where psin_data places it.
210 self.assertEqual([(r["type"], r["size"]) for r in got["rows"]], [(t, n) for t, _at, n in table])
211 self.assertEqual(got["table_end"], "pppppppp")
212 self.assertEqual([bytes(b["data"]) for b in got["blocks"]], [blob[at:at + n] for _t, at, n in table])
213
214 sections = {s["tag"]: s for s in got["sections"]}
215 self.assertEqual([(s["tag"], s["size"]) for s in got["sections"]],
216 [(s["tag"], s["size"]) for s in ref["sections"]])
217 schema = ref["schema"]
218 self.assertEqual([s["name_hash"] for s in sections["LSCH"]["structs"]],
219 [int(s["hash"], 16) for s in schema["structs"]])
220 self.assertEqual([(m["name_hash"], m["offset"], m["type"], m["index"], m["ref_hash"])
221 for m in sections["LSCH"]["members"]],
222 [(int(m["hash"], 16), m["offset"], m["type"], m["index"], int(m["ref"], 16))
223 for s in schema["structs"] for m in s["members"]])
224 self.assertEqual([e["value_count"] for e in sections["LENM"]["enums"]],
225 [len(e["values"]) for e in schema["enums"]])
226 self.assertEqual([v["value"] for v in sections["LENM"]["values"]],
227 [v["value"] for e in schema["enums"] for v in e["values"]])
228 lsns = next(s for s in ref["sections"] if s["tag"] == "LSNS")
229 self.assertEqual([(d["kind"], d["bytes"]) for d in sections["LSNS"]["descs"]],
230 [(int(b["kind"], 16), b["bytes"]) for b in lsns["blocks"]])
231 self.assertEqual([len(b["records"]) for b in sections["LSNS"]["lsns_blocks"]], [n // 16 for _k, n in LSNS_BLOCKS])
232 self.assertEqual(sections["LRSC"]["rsc_version"], ref["rsc_version"])
233 self.assertEqual(sections["LRSC"]["root_block"], 1)
234 self.assertEqual(sections["CHKS"]["checksum_size"], ref["checksum_size"])
235
236 def test_psin_truncated_keeps_the_whole_sections(self):
237 blob = psin_container(lsns=False)
238 first = struct.unpack_from(">I", blob, 4)[0]
239 lsch_size = struct.unpack_from(">I", blob, first + 4)[0]
240 cut = blob[:first + lsch_size + 20] # inside LENM
241 self.assertFalse(psin_index.parse(cut)["complete"])
242 got, log = self.run_pattern("psin.hexpat", cut)
243 self.assertIsNotNone(got, log)
244 tags = [s["tag"] for s in got["sections"]]
245 self.assertEqual(tags, ["LSCH", "LENM"])
246 self.assertIn("structs", got["sections"][0])
247 self.assertEqual(len(got["sections"][1]["truncated"]), 12) # what is left after LENM's 8-byte header
248
163 def test_rpf9_rejects_a_data_offset_past_the_end(self): 249 def test_rpf9_rejects_a_data_offset_past_the_end(self):
164 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20]) 250 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20])
165 self.assertIsNone(got) 251 self.assertIsNone(got)