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:
Diffstat (limited to 'tests/test_imhex_patterns.py')
-rw-r--r--tests/test_imhex_patterns.py256
1 files changed, 256 insertions, 0 deletions
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py
new file mode 100644
index 000000000..751de8b90
--- /dev/null
+++ b/tests/test_imhex_patterns.py
@@ -0,0 +1,256 @@
1"""Tests for the ImHex patterns in tools/imhex.
2
3 python -I tests/test_imhex_patterns.py
4
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 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
9through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the
10parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it
11the ImHex half is skipped and the rest still runs.
12"""
13import json
14import os
15import shutil
16import struct
17import subprocess
18import sys
19import tempfile
20import unittest
21
22ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23PATTERNS = os.path.join(ROOT, "tools", "imhex")
24sys.path.insert(0, os.path.join(ROOT, "tools"))
25sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
27import psin_data # noqa: E402
28import psin_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
31
32
33def find_imhex():
34 candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")]
35 if os.name == "nt":
36 candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe"))
37 for c in candidates:
38 if c and os.path.isfile(c):
39 return c
40 return None
41
42
43IMHEX = find_imhex()
44
45
46# ---- synthetic inputs ------------------------------------------------------------------------------------------
47
48def _name(name):
49 return struct.pack("<H", len(name)) + name
50
51
52def rbf0_stream(wide):
53 """One resource with every record type of docs/rbf0.md section 3, then bytes past the root close."""
54 q, d = ("Q", "d") if wide else ("I", "f")
55 q, d, d3 = "<" + q, "<" + d, "<" + d * 3
56 out = b"RBF0" + (rbf0_index.PROLOGUE if wide else b"")
57 out += bytes([0, 0x00]) + _name(b"root") + struct.pack("<HHH", 0, 0, 1)
58 out += bytes([1, 0x10]) + _name(b"count") + struct.pack(q, 7) # the root's one attribute
59 out += bytes([2, 0x00]) + _name(b"item") + struct.pack("<HHH", 0, 0, 0)
60 out += bytes([3, 0x40]) + _name(b"scale") + struct.pack(d, 1.5)
61 out += bytes([4, 0x50]) + _name(b"pos") + struct.pack(d3, 1.0, -2.0, 0.25)
62 out += bytes([5, 0x60]) + _name(b"label") + struct.pack("<H", 5) + b"probe"
63 out += bytes([6, 0x20]) + _name(b"flag") + bytes([6, 0x30]) # new, then reused
64 out += bytes([3, 0x10]) + struct.pack(q, 9) # reused with another type
65 out += bytes([0xFD, 0xFF]) + struct.pack("<I", 5) + b"text\x00"
66 out += b"\xff\xff" # close item
67 out += b"\xff\xff" # close root: the end
68 return out + b"\x00\x11\x22\x33" # not part of the resource
69
70
71def rpf9_archive(data_offset=0x100, size=0x140):
72 head = b"9FPR" + struct.pack("<III", data_offset, 0x11, 0x22)
73 toc = bytes((i * 37) & 0xFF for i in range(data_offset - len(head)))
74 body = b"\x78\x9c" + bytes(size - data_offset - 2)
75 return head + toc + body
76
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
99def pragma_magic(pattern):
100 """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file."""
101 with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f:
102 for line in f:
103 if line.startswith("#pragma magic"):
104 inside = line[line.index("[") + 1:line.index("]")]
105 return bytes(int(b, 16) for b in inside.split())
106 return None
107
108
109# ---- tests -----------------------------------------------------------------------------------------------------
110
111class InputsAndMagic(unittest.TestCase):
112 """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree."""
113
114 def test_synthetic_streams_parse(self):
115 for wide in (True, False):
116 r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4])
117 self.assertEqual(r["status"], "ok", r["error"])
118 self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32")
119 self.assertEqual(r["elements"], 2)
120 self.assertEqual(r["descriptors"], 7)
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
132 def test_pattern_magics(self):
133 self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC)
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)
136
137
138@unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)")
139class PatternsInImHex(unittest.TestCase):
140 def setUp(self):
141 self.tmp = tempfile.TemporaryDirectory()
142 self.addCleanup(self.tmp.cleanup)
143
144 def run_pattern(self, pattern, data):
145 """Returns (decoded JSON or None, combined output)."""
146 src = os.path.join(self.tmp.name, "input.bin")
147 out = os.path.join(self.tmp.name, "out.json")
148 if os.path.exists(out):
149 os.remove(out)
150 with open(src, "wb") as f:
151 f.write(data)
152 cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"]
153 includes = os.path.join(os.path.dirname(IMHEX), "includes")
154 if os.path.isdir(includes):
155 cmd += ["-I", includes]
156 p = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
157 log = p.stdout + p.stderr
158 if not os.path.exists(out):
159 return None, log
160 with open(out, encoding="utf-8") as f:
161 return json.load(f), log
162
163 def check_rbf0(self, wide):
164 data = rbf0_stream(wide)
165 ref = rbf0_index.parse_rbf0(data[:-4])
166 got, log = self.run_pattern("rbf0.hexpat", data)
167 self.assertIsNotNone(got, log)
168 self.assertEqual("prologue" in got["header"], wide)
169 records = got["records"]
170
171 names = [r["name"] for r in records if "name" in r]
172 self.assertEqual(names, ref["descriptor_names"])
173 self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"])
174 ints = [r["value_int"] for r in records if "value_int" in r]
175 self.assertEqual(ints, ref["ints"])
176 floats = []
177 for r in records:
178 floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", [])
179 self.assertEqual(floats, ref["floats"])
180 strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r]
181 self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"])
182 self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0])
183 # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records.
184 self.assertEqual(records[-1]["index"], 0xFF)
185 self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2)
186
187 def test_rbf0_wide(self):
188 self.check_rbf0(wide=True)
189
190 def test_rbf0_narrow(self):
191 self.check_rbf0(wide=False)
192
193 def test_rpf9_header_and_opaque_toc(self):
194 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100))
195 self.assertIsNotNone(got, log)
196 self.assertEqual(got["header"]["magic"], "9FPR")
197 self.assertEqual(got["header"]["data_offset"], 0x100)
198 self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22))
199 self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10)
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
249 def test_rpf9_rejects_a_data_offset_past_the_end(self):
250 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20])
251 self.assertIsNone(got)
252 self.assertIn("data offset is outside the file", log)
253
254
255if __name__ == "__main__":
256 unittest.main()