upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tools/script_qtable.py
diff options
context:
space:
mode:
authorAlpaca-exe <20233126@etud.univ-evry.fr>2026-11-23 02:35:53 +0100
committerAlpaca-exe <20233126@etud.univ-evry.fr>2026-11-23 02:35:53 +0100
commit45cbda2549c7d1b104b500065f8f0e365f6bc8ee (patch)
tree188f58a703b2fecbfd2aff85ae36d4b443529104 /tools/script_qtable.py
parent03b09a086592a197db64d91655c6e65c30764d96 (diff)
script_qtable: decode 0x71717171 object-tree container in script.rpf
Diffstat (limited to 'tools/script_qtable.py')
-rw-r--r--tools/script_qtable.py540
1 files changed, 540 insertions, 0 deletions
diff --git a/tools/script_qtable.py b/tools/script_qtable.py
new file mode 100644
index 000000000..e1b884762
--- /dev/null
+++ b/tools/script_qtable.py
@@ -0,0 +1,540 @@
1"""Decode the 0x71717171-tagged ('qqqq') object-tree container in script.rpf.
2
3`rpf9_carve.py` extracts 1,012 PSIN containers from `script.rpf` plus one
442-stream binary container at offset `0x53000` (2,702,384 bytes inflated). It
5begins with a 40-byte header holding `u32 record_count` at `+0x14`, followed by
6`record_count` ascending `u64` byte offsets and `record_count` 16-byte-aligned
7records. Internal 8-byte pointers carry `0x71717171` (`'qqqq'`) in the high
832 bits and `offsets[target] + 8` in the low 32 bits.
9
10Usage:
11 python -I tools/script_qtable.py <carve_dir_or_rpf_or_bin> [--root-hash HEX] [--type-hash HEX] [--json FILE]
12
13Default output and `--json` reports emit aggregate structure counts, size and
14stride histograms, invariant checks and optional local query counts only; no
15payload bytes or string tables are exported. Standard library only.
16"""
17from __future__ import annotations
18
19import argparse
20from collections import Counter
21import json
22import os
23import struct
24import sys
25
26# -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers.
27TOOLS = os.path.dirname(os.path.abspath(__file__))
28if TOOLS not in sys.path:
29 sys.path.insert(0, TOOLS)
30
31import gamedata_index as gi # noqa: E402
32import gamedata_maps as gm # noqa: E402
33from report_paths import same_report_path # noqa: E402
34
35HEADER_BYTES = 40
36Q_TAG = 0x71717171
37ARRAY_MARKER = 0x14
38ARRAY_HEADER_BYTES = 48
39ARRAY_FLAG_POINTERS = 0x10000
40MAX_RECORDS = 1_000_000
41
42
43def _align16(value: int) -> int:
44 return (value + 15) & ~15
45
46
47def is_qtable_prefix(blob: bytes) -> bool:
48 """True when `blob` begins with a valid 40-byte qtable header and offset[0]."""
49 if len(blob) < HEADER_BYTES + 8:
50 return False
51 words = struct.unpack_from("<10I", blob, 0)
52 record_count = words[5]
53 if not (1 <= record_count <= MAX_RECORDS):
54 return False
55 if any(words[i] != 0 for i in range(10) if i != 5):
56 return False
57 first_off = struct.unpack_from("<Q", blob, HEADER_BYTES)[0]
58 table_end = HEADER_BYTES + record_count * 8
59 return first_off in (table_end, _align16(table_end)) and first_off % 16 == 0
60
61
62def _parse_hex_u32(text: str) -> int:
63 value = int(text, 16)
64 if not (0 <= value <= 0xFFFFFFFF):
65 raise ValueError(f"hash out of u32 range: {text}")
66 return value
67
68
69def _classify_record(idx: int, rec: bytes, ptrs: list[tuple[int, int, int | None]]) -> dict:
70 w2, w3 = struct.unpack_from("<2I", rec, 8)
71 if len(rec) >= ARRAY_HEADER_BYTES and w2 == ARRAY_MARKER and w3 == 0:
72 cnt, cap, stride, aflags, w8, w9, elem_hash, w11 = struct.unpack_from("<8I", rec, 16)
73 if cnt == cap:
74 expected_len = _align16(ARRAY_HEADER_BYTES + cnt * stride)
75 return {
76 "index": idx,
77 "kind": "array",
78 "bytes": len(rec),
79 "count": cnt,
80 "stride": stride,
81 "array_flags": aflags,
82 "element_type_hash": elem_hash,
83 "size_exact": expected_len == len(rec),
84 "extra_words_zero": (w8 == 0 and w9 == 0 and w11 == 0),
85 "zero_element_hash": elem_hash == 0,
86 }
87
88 is_wrapper = (
89 len(rec) == 32
90 and w3 == 0
91 and len(ptrs) == 1
92 and ptrs[0][0] == 16
93 and ptrs[0][2] == idx + 1
94 and struct.unpack_from("<Q", rec, 24)[0] == 0
95 )
96 return {
97 "index": idx,
98 "kind": "struct",
99 "bytes": len(rec),
100 "struct_type_hash": w2,
101 "w3_zero": w3 == 0,
102 "is_wrapper": is_wrapper,
103 }
104
105
106def _collect_subtree(root_idx: int, adj: list[list[int]], records: list[dict],
107 offsets: list[int], end_off: int, limit_hi: int) -> dict:
108 """Walk one tree from `root_idx` to measure node count, depth, bytes and type composition."""
109 stack = [(root_idx, 0)]
110 seen: set[int] = set()
111 arrays = structs = max_depth = total_bytes = cross_edges = 0
112 stride_counts: Counter[int] = Counter()
113 struct_sizes: Counter[int] = Counter()
114
115 while stack:
116 node, depth = stack.pop()
117 if node in seen:
118 continue
119 seen.add(node)
120 if not (root_idx <= node < limit_hi):
121 cross_edges += 1
122 if depth > max_depth:
123 max_depth = depth
124 rec_end = offsets[node + 1] if node + 1 < len(offsets) else end_off
125 total_bytes += rec_end - offsets[node]
126 info = records[node]
127 if info["kind"] == "array":
128 arrays += 1
129 stride_counts[info["stride"]] += 1
130 else:
131 structs += 1
132 struct_sizes[info["bytes"]] += 1
133 for child in adj[node]:
134 stack.append((child, depth + 1))
135
136 return {
137 "nodes": len(seen),
138 "max_depth": max_depth,
139 "bytes": total_bytes,
140 "arrays": arrays,
141 "structs": structs,
142 "cross_tree_edges": cross_edges,
143 "array_strides": {str(k): stride_counts[k] for k in sorted(stride_counts)},
144 "struct_sizes": {str(k): struct_sizes[k] for k in sorted(struct_sizes)},
145 }
146
147
148def parse_qtable(blob: bytes, *, root_hash: int | None = None, type_hash: int | None = None) -> dict:
149 """Validate and summarize a 0x71717171-tagged object-tree payload."""
150 if not is_qtable_prefix(blob):
151 raise ValueError("payload does not begin with a valid 40-byte qtable header")
152 if len(blob) % 16 != 0:
153 raise ValueError(f"payload length {len(blob)} is not 16-byte aligned")
154
155 n = struct.unpack_from("<I", blob, 0x14)[0]
156 table_end = HEADER_BYTES + n * 8
157 offsets = list(struct.unpack_from(f"<{n}Q", blob, HEADER_BYTES))
158
159 for i, off in enumerate(offsets):
160 if off % 16 != 0:
161 raise ValueError(f"record {i} offset {off:#x} is not 16-byte aligned")
162 if off < table_end or off >= len(blob):
163 raise ValueError(f"record {i} offset {off:#x} is out of bounds for {len(blob):#x} bytes")
164 if i > 0 and off <= offsets[i - 1]:
165 raise ValueError(f"record {i} offset {off:#x} <= previous {offsets[i - 1]:#x}")
166
167 bounds = offsets + [len(blob)]
168 if any((bounds[i + 1] - bounds[i]) < 16 for i in range(n)):
169 raise ValueError("record shorter than 16 bytes")
170
171 body_to_index = {offsets[i] + 8: i for i in range(n)}
172 in_degree = [0] * n
173 adj: list[list[int]] = [[] for _ in range(n)]
174 records: list[dict] = []
175
176 root_indices: list[int] = []
177 root_hashes_by_idx: dict[int, int] = {}
178 root_flags_hist: Counter[int] = Counter()
179 nonroot_flags_nonzero = 0
180
181 total_pointers = resolved_pointers = unresolved_pointers = forward_edges = 0
182 size_hist: Counter[int] = Counter()
183 array_stride_hist: Counter[int] = Counter()
184 array_flags_hist: Counter[int] = Counter()
185 struct_size_hist: Counter[int] = Counter()
186 element_hashes: set[int] = set()
187 struct_hashes: set[int] = set()
188 wrapper_count = struct_w3_nonzero = 0
189 array_exact = array_extra_zero = array_zero_elem_hash = 0
190 array_ptr_stride8 = array_ptr_count = 0
191
192 for i in range(n):
193 rec = blob[bounds[i]:bounds[i + 1]]
194 size_hist[len(rec)] += 1
195 rkey, pflags = struct.unpack_from("<2I", rec, 0)
196 if rkey != 0:
197 root_indices.append(i)
198 root_hashes_by_idx[i] = rkey
199 root_flags_hist[pflags] += 1
200 elif pflags != 0:
201 nonroot_flags_nonzero += 1
202
203 rec_ptrs: list[tuple[int, int, int | None]] = []
204 for rel in range(8, len(rec), 8):
205 word = struct.unpack_from("<Q", rec, rel)[0]
206 if (word >> 32) == Q_TAG:
207 total_pointers += 1
208 target_off = word & 0xFFFFFFFF
209 tgt = body_to_index.get(target_off)
210 rec_ptrs.append((rel, target_off, tgt))
211 if tgt is None:
212 unresolved_pointers += 1
213 else:
214 resolved_pointers += 1
215 in_degree[tgt] += 1
216 adj[i].append(tgt)
217 if tgt > i:
218 forward_edges += 1
219
220 info = _classify_record(i, rec, rec_ptrs)
221 info["root_key_hash"] = rkey
222 info["prefix_flags"] = pflags
223 records.append(info)
224
225 if info["kind"] == "array":
226 array_stride_hist[info["stride"]] += 1
227 array_flags_hist[info["array_flags"]] += 1
228 element_hashes.add(info["element_type_hash"])
229 if info["size_exact"]:
230 array_exact += 1
231 if info["extra_words_zero"]:
232 array_extra_zero += 1
233 if info["zero_element_hash"]:
234 array_zero_elem_hash += 1
235 if info["array_flags"] == ARRAY_FLAG_POINTERS:
236 array_ptr_count += 1
237 if info["stride"] == 8:
238 array_ptr_stride8 += 1
239 else:
240 struct_size_hist[info["bytes"]] += 1
241 struct_hashes.add(info["struct_type_hash"])
242 if not info["w3_zero"]:
243 struct_w3_nonzero += 1
244 if info["is_wrapper"]:
245 wrapper_count += 1
246
247 root_set = set(root_indices)
248 in_deg_zero = sum(1 for d in in_degree if d == 0)
249 nonroot_in_deg_one = all(in_degree[i] == 1 for i in range(n) if i not in root_set)
250 root_bijection_holds = (
251 all((i in root_set) == (in_degree[i] == 0) for i in range(n))
252 and nonroot_in_deg_one
253 )
254
255 tree_sizes: list[int] = []
256 tree_depths: list[int] = []
257 cross_tree_edges = 0
258 tree_owner: list[int] = [-1] * n
259 for pos, r_idx in enumerate(root_indices):
260 hi = root_indices[pos + 1] if pos + 1 < len(root_indices) else n
261 for member in range(r_idx, hi):
262 tree_owner[member] = r_idx
263 stats = _collect_subtree(r_idx, adj, records, offsets, len(blob), hi)
264 tree_sizes.append(stats["nodes"])
265 tree_depths.append(stats["max_depth"])
266 cross_tree_edges += stats["cross_tree_edges"]
267
268 trees_partition_records = sum(tree_sizes) == n and cross_tree_edges == 0
269 contiguous_preorder = trees_partition_records and forward_edges == resolved_pointers
270
271 array_count = sum(1 for r in records if r["kind"] == "array")
272 struct_count = n - array_count
273
274 valid = (
275 unresolved_pointers == 0
276 and root_bijection_holds
277 and contiguous_preorder
278 and array_exact == array_count
279 )
280
281 result: dict = {
282 "valid": valid,
283 "payload_bytes": len(blob),
284 "header_bytes": HEADER_BYTES,
285 "offset_table_bytes": n * 8,
286 "record_pool_offset": offsets[0],
287 "record_pool_bytes": len(blob) - offsets[0],
288 "record_count": n,
289 "root_count": len(root_indices),
290 "distinct_root_hashes": len(set(root_hashes_by_idx.values())),
291 "in_deg_zero_count": in_deg_zero,
292 "nonroot_in_deg_one": nonroot_in_deg_one,
293 "root_bijection_holds": root_bijection_holds,
294 "total_pointers": total_pointers,
295 "resolved_pointers": resolved_pointers,
296 "unresolved_pointers": unresolved_pointers,
297 "forward_edges": forward_edges,
298 "cross_tree_edges": cross_tree_edges,
299 "trees_partition_records": trees_partition_records,
300 "contiguous_preorder": contiguous_preorder,
301 "nonroot_prefix_flags_nonzero": nonroot_flags_nonzero,
302 "root_prefix_flags": {f"{k:#x}": root_flags_hist[k] for k in sorted(root_flags_hist)},
303 "array_records": array_count,
304 "array_size_exact": array_exact,
305 "array_extra_words_zero": array_extra_zero,
306 "array_zero_element_hashes": array_zero_elem_hash,
307 "array_value_records": array_flags_hist.get(0, 0),
308 "array_pointer_records": array_ptr_count,
309 "array_pointer_stride8": array_ptr_stride8,
310 "array_flags": {f"{k:#x}": array_flags_hist[k] for k in sorted(array_flags_hist)},
311 "array_strides": {str(k): array_stride_hist[k] for k in sorted(array_stride_hist)},
312 "distinct_element_type_hashes": len(element_hashes),
313 "struct_records": struct_count,
314 "struct_wrappers": wrapper_count,
315 "struct_w3_nonzero": struct_w3_nonzero,
316 "distinct_struct_type_hashes": len(struct_hashes),
317 "struct_sizes": {str(k): struct_size_hist[k] for k in sorted(struct_size_hist)},
318 "record_sizes": {str(k): size_hist[k] for k in sorted(size_hist)},
319 "tree_nodes_min": min(tree_sizes) if tree_sizes else 0,
320 "tree_nodes_median": sorted(tree_sizes)[len(tree_sizes) // 2] if tree_sizes else 0,
321 "tree_nodes_max": max(tree_sizes) if tree_sizes else 0,
322 "tree_depth_min": min(tree_depths) if tree_depths else 0,
323 "tree_depth_max": max(tree_depths) if tree_depths else 0,
324 }
325
326 if root_hash is not None:
327 matches = []
328 for pos, r_idx in enumerate(root_indices):
329 if root_hashes_by_idx[r_idx] == root_hash:
330 hi = root_indices[pos + 1] if pos + 1 < len(root_indices) else n
331 sub = _collect_subtree(r_idx, adj, records, offsets, len(blob), hi)
332 sub["root_index"] = r_idx
333 sub["root_offset_hex"] = f"{offsets[r_idx]:#x}"
334 sub["root_type_hash"] = f"{records[r_idx].get('struct_type_hash', ARRAY_MARKER):#010x}"
335 matches.append(sub)
336 result["root_query"] = {
337 "hash": f"{root_hash:#010x}",
338 "matches": len(matches),
339 "trees": matches,
340 }
341
342 if type_hash is not None:
343 matching_arrays = [r for r in records if r["kind"] == "array" and r["element_type_hash"] == type_hash]
344 matching_structs = [r for r in records if r["kind"] == "struct" and r["struct_type_hash"] == type_hash]
345 owner_roots = {tree_owner[r["index"]] for r in matching_arrays + matching_structs if tree_owner[r["index"]] >= 0}
346 result["type_query"] = {
347 "hash": f"{type_hash:#010x}",
348 "array_matches": len(matching_arrays),
349 "struct_matches": len(matching_structs),
350 "distinct_trees": len(owner_roots),
351 "array_strides": dict(sorted(Counter(str(r["stride"]) for r in matching_arrays).items())),
352 "struct_sizes": dict(sorted(Counter(str(r["bytes"]) for r in matching_structs).items())),
353 }
354
355 return result
356
357
358def _join_qtable_from_source(source) -> tuple[bytes, dict]:
359 rows = source.rows
360 n = len(rows)
361 for i in range(n):
362 data = source.read(rows[i])
363 if not is_qtable_prefix(data):
364 continue
365 parts = [data]
366 stored = rows[i].get("stored", len(data))
367 j = i + 1
368 prev_len = len(data)
369 while j < n and prev_len > 0 and prev_len % 65536 == 0:
370 nxt = source.read(rows[j])
371 nk = gi.stream_kind(nxt, rows[j])
372 if nk in ("decl", "bink2", "rbf0", "psin", "other") or gi.standalone_xml(nxt):
373 break
374 parts.append(nxt)
375 stored += rows[j].get("stored", len(nxt))
376 prev_len = len(nxt)
377 j += 1
378 blob = b"".join(parts)
379 meta = {
380 "source_type": "directory" if isinstance(source, gi.DirectorySource) else "archive",
381 "offset": rows[i]["off"],
382 "offset_hex": f"{rows[i]['off']:#x}",
383 "chunks": j - i,
384 "stored": stored,
385 "inflated": len(blob),
386 }
387 return blob, meta
388 raise ValueError("no 0x71717171 object-tree container found")
389
390
391class _BinFolderSource:
392 """Minimal sorted *.bin reader when a test/carve directory has no index.json."""
393
394 def __init__(self, directory: str):
395 names = sorted(n for n in os.listdir(directory) if n.lower().endswith(".bin"))
396 self.directory = directory
397 self.rows = []
398 for idx, name in enumerate(names):
399 full = os.path.join(directory, name)
400 sz = os.path.getsize(full)
401 try:
402 off = int(os.path.splitext(name)[0], 16)
403 except ValueError:
404 off = idx * 0x10000
405 self.rows.append({"off": off, "stored": sz, "size": sz, "_name": name})
406
407 def read(self, row: dict) -> bytes:
408 with open(os.path.join(self.directory, row["_name"]), "rb") as f:
409 return f.read()
410
411
412def load_qtable_payload(target: str) -> tuple[bytes, dict]:
413 """Load the object-tree container from a carve directory, .rpf archive or raw .bin."""
414 if os.path.isdir(target):
415 index_path = os.path.join(target, "index.json")
416 source = gi.DirectorySource(target) if os.path.isfile(index_path) else _BinFolderSource(target)
417 return _join_qtable_from_source(source)
418
419 if not os.path.isfile(target):
420 raise FileNotFoundError(target)
421
422 with open(target, "rb") as f:
423 head = f.read(64)
424
425 if head[:4] == b"9FPR":
426 source = gi.ArchiveSource(target)
427 try:
428 return _join_qtable_from_source(source)
429 finally:
430 source.close()
431
432 with open(target, "rb") as f:
433 blob = f.read()
434 if not is_qtable_prefix(blob):
435 raise ValueError(f"{target}: not an RPF9 archive or 0x71717171 object-tree payload")
436 return blob, {
437 "source_type": "file",
438 "offset": 0,
439 "offset_hex": "0x0",
440 "chunks": 1,
441 "stored": len(blob),
442 "inflated": len(blob),
443 }
444
445
446def check_report_path(out_path: str, target: str, rows: list[dict] | None = None) -> None:
447 """Refuse a --json destination that is a directory or collides with any input."""
448 if os.path.isdir(out_path):
449 raise ValueError(f"--json is a directory: {out_path}")
450 if os.path.isdir(target):
451 if os.path.isfile(os.path.join(target, "index.json")):
452 gm.check_report_path(out_path, target, rows=rows)
453 elif same_report_path(out_path, target):
454 raise ValueError(f"--json would overwrite the input {target}")
455 else:
456 for name in os.listdir(target):
457 if name.lower().endswith(".bin") and same_report_path(out_path, os.path.join(target, name)):
458 raise ValueError(f"--json would overwrite the input {name}")
459 elif same_report_path(out_path, target):
460 raise ValueError(f"--json would overwrite the input {target}")
461
462
463def _print_summary(report: dict) -> None:
464 loc = report["location"]
465 print(
466 f'qtable {loc["offset_hex"]}: {loc["chunks"]} streams, '
467 f'{loc["stored"]:,} stored, {report["payload_bytes"]:,} inflated '
468 f'(valid={report["valid"]})'
469 )
470 print(
471 f' records: {report["record_count"]:,} '
472 f'(arrays={report["array_records"]:,} exact={report["array_size_exact"]:,}, '
473 f'structs={report["struct_records"]:,} wrappers={report["struct_wrappers"]:,})'
474 )
475 print(
476 f' trees: {report["root_count"]:,} roots ({report["distinct_root_hashes"]:,} distinct hashes), '
477 f'bijection={report["root_bijection_holds"]}, '
478 f'preorder={report["contiguous_preorder"]}, '
479 f'nodes min/med/max={report["tree_nodes_min"]}/{report["tree_nodes_median"]}/{report["tree_nodes_max"]}, '
480 f'depth {report["tree_depth_min"]}..{report["tree_depth_max"]}'
481 )
482 print(
483 f' pointers: {report["resolved_pointers"]:,}/{report["total_pointers"]:,} resolved '
484 f'(forward={report["forward_edges"]:,}, unresolved={report["unresolved_pointers"]})'
485 )
486 print(f' array strides: {report["array_strides"]} ({report["distinct_element_type_hashes"]} element hashes)')
487 print(f' struct sizes: {report["struct_sizes"]} ({report["distinct_struct_type_hashes"]} struct hashes)')
488 if "root_query" in report:
489 rq = report["root_query"]
490 print(f' --root-hash {rq["hash"]}: {rq["matches"]} match(es) {rq["trees"]}')
491 if "type_query" in report:
492 tq = report["type_query"]
493 print(
494 f' --type-hash {tq["hash"]}: arrays={tq["array_matches"]}, '
495 f'structs={tq["struct_matches"]}, distinct_trees={tq["distinct_trees"]}'
496 )
497
498
499def main(argv=None) -> int:
500 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
501 ap.add_argument("target", help="carved script directory, script.rpf archive, or joined .bin file")
502 ap.add_argument("--root-hash", help="inspect subtrees for this u32 root hash (hex)")
503 ap.add_argument("--type-hash", help="summarize array/struct records matching this u32 type hash (hex)")
504 ap.add_argument("--json", help="write aggregate statistics JSON to this file")
505 a = ap.parse_args(argv)
506
507 try:
508 root_h = _parse_hex_u32(a.root_hash) if a.root_hash is not None else None
509 type_h = _parse_hex_u32(a.type_hash) if a.type_hash is not None else None
510 if a.json:
511 rows = gm._read_index_rows(a.target) if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) else None
512 check_report_path(a.json, a.target, rows=rows)
513 blob, meta = load_qtable_payload(a.target)
514 report = parse_qtable(blob, root_hash=root_h, type_hash=type_h)
515 except (OSError, ValueError, KeyError, TypeError, struct.error, RuntimeError) as e:
516 print("error:", e, file=sys.stderr)
517 return 2 if isinstance(e, ValueError) and "--json" in str(e) else 1
518
519 out = {"location": meta, **report}
520 _print_summary(out)
521
522 if a.json:
523 try:
524 gm._make_parent(a.json)
525 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
526 json.dump(out, f, indent=1)
527 except OSError as e:
528 print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
529 return 1
530 print("wrote", a.json)
531
532 return 0 if report["valid"] else 1
533
534
535if __name__ == "__main__":
536 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
537 sys.stdout.reconfigure(errors="replace")
538 except (AttributeError, ValueError, OSError):
539 pass
540 sys.exit(main())