upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tools/rbf0_tree.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/rbf0_tree.py')
-rw-r--r--tools/rbf0_tree.py554
1 files changed, 554 insertions, 0 deletions
diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py
new file mode 100644
index 000000000..bea6534f7
--- /dev/null
+++ b/tools/rbf0_tree.py
@@ -0,0 +1,554 @@
1"""Decode RBF0 resources into strict JSON trees, with an optional simple XML rendering.
2
3RBF0 is RAGE's binary form of an XML data file: one record stream with an inline descriptor table. This tool reads
4inflated RBF0 resources from a carve directory or a single resource file, joins the 64 KiB continuation streams of
5one logical resource, and builds the element tree. It reports unknown descriptors, unknown record types, truncated
6payloads and structural violations as errors instead of guessing a value.
7
8The output contains names and payloads taken from the archive, so treat it as game data: keep it out of git and do
9not attach it to an issue or a pull request. Format facts and aggregate counts are in docs/rbf0.md.
10
11Usage:
12 python -I tools/rbf0_tree.py <carve-dir> <out.json> [--xml DIR] [--root NAME]... [--offset 0x...] [--limit N]
13
14The input directory holds inflated zlib streams or complete RBF0 resources. A file name that starts with a
15hexadecimal archive offset is used to order and label the resource, as in the rbf0_index.py carve layout.
16"""
17import argparse
18import collections
19import json
20import math
21import os
22import re
23import struct
24import sys
25from xml.etree import ElementTree as ET
26
27sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
28
29import rbf0_index # noqa: E402
30
31MAGIC = rbf0_index.MAGIC
32PROLOGUE = rbf0_index.PROLOGUE
33MAX_CHUNK = rbf0_index.MAX_CHUNK
34MAX_CHUNKS = rbf0_index.MAX_CHUNKS
35MAX_BYTES = rbf0_index.MAX_BYTES
36RbfError = rbf0_index.RbfError
37TYPE_NAMES = {0x00: "open", 0x10: "int", 0x20: "true", 0x30: "false", 0x40: "float",
38 0x50: "vec3", 0x60: "string"}
39VALUE_TYPES = {0x10: "int", 0x20: "bool", 0x30: "bool", 0x40: "float", 0x50: "vec3", 0x60: "string"}
40XML_BAD = re.compile(r"[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]")
41
42
43def _utf8(raw):
44 """Return (text, valid). Invalid bytes become U+FFFD and are counted, never silently accepted."""
45 try:
46 return raw.decode("utf-8"), True
47 except UnicodeDecodeError:
48 return raw.decode("utf-8", "replace"), False
49
50
51def _render(value):
52 """A stable textual form for XML and for JSON consumers that want one scalar spelling."""
53 if isinstance(value, bool):
54 return "true" if value else "false"
55 if isinstance(value, float):
56 if math.isnan(value):
57 return "nan"
58 if math.isinf(value):
59 return "inf" if value > 0 else "-inf"
60 return repr(value)
61 if isinstance(value, (list, tuple)):
62 return "[" + ", ".join(_render(v) for v in value) + "]"
63 return str(value)
64
65
66class TreeError(RbfError):
67 """A malformed or truncated RBF0 record stream."""
68
69
70class Parser:
71 """One RBF0 resource. `parse()` always returns a document, with a partial tree on failure."""
72
73 def __init__(self, data, source="", offset=0, chunks=1):
74 self.data = data
75 self.source = source
76 self.offset = offset
77 self.chunks = chunks
78 self.wide = data[4:8] == PROLOGUE
79 self.p = 8 if self.wide else 4
80 self.scalar = 8 if self.wide else 4
81 self.descs = []
82 self.stack = []
83 self.root = None
84 self.status = "ok"
85 self.error = ""
86 self.error_offset = None
87 self.counts = collections.Counter()
88 self.descriptor_names = set()
89 self.attribute_mismatches = 0
90 self.attribute_order_violations = 0
91 self.text_after_child = 0
92 self.text_before_child = 0
93 self.value_after_child = 0
94 self.invalid_utf8 = 0
95 self.max_depth = 0
96
97 def take(self, n, what):
98 if self.p + n > len(self.data):
99 raise TreeError(f"{what} truncated", self.p, truncated=True)
100 start = self.p
101 self.p += n
102 return self.data[start:self.p]
103
104 def _descriptor(self, index, kind, at):
105 if index == len(self.descs):
106 n = struct.unpack("<H", self.take(2, "descriptor name length"))[0]
107 raw = self.take(n, "descriptor name")
108 name, valid = _utf8(raw)
109 if not valid:
110 self.invalid_utf8 += 1
111 self.descs.append({
112 "index": index,
113 "name": name,
114 "first_type": TYPE_NAMES.get(kind, f"0x{kind:02x}"),
115 "offset": at,
116 "name_offset": self.p - n,
117 "uses": 0,
118 "types": {},
119 "utf8_valid": valid,
120 })
121 self.descriptor_names.add(name)
122 elif index > len(self.descs):
123 raise TreeError(f"descriptor index {index} of {len(self.descs)}", at)
124 desc = self.descs[index]
125 desc["uses"] += 1
126 key = TYPE_NAMES.get(kind, f"0x{kind:02x}")
127 desc["types"][key] = desc["types"].get(key, 0) + 1
128 return desc
129
130 def _attach(self, frame, node):
131 node["depth"] = frame["depth"] + 1
132 if frame["node"]["kind"] != "element":
133 raise TreeError("record outside an element", node["offset"])
134 if node["kind"] == "value" and frame["attrs_seen"] < frame["attrs_declared"]:
135 if frame["content_started"]:
136 frame["node"]["attribute_order_violation"] = True
137 self.attribute_order_violations += 1
138 frame["node"]["attributes"].append(node)
139 frame["attrs_seen"] += 1
140 return
141 if node["kind"] in ("element", "text") and frame["attrs_seen"] < frame["attrs_declared"]:
142 frame["node"]["attribute_order_violation"] = True
143 self.attribute_order_violations += 1
144 frame["content_started"] = True
145 frame["node"]["content"].append(node)
146 if node["kind"] == "element":
147 if frame["text_seen"]:
148 frame["node"]["text_before_child"] = True
149 self.text_before_child += 1
150 frame["child_seen"] = True
151 elif node["kind"] == "value":
152 if frame["child_seen"]:
153 frame["node"]["value_after_child"] = True
154 self.value_after_child += 1
155 elif node["kind"] == "text":
156 if frame["child_seen"]:
157 frame["node"]["text_after_child"] = True
158 self.text_after_child += 1
159 if frame["text_seen"]:
160 frame["node"]["multiple_text"] = True
161 frame["text_seen"] = True
162
163 def parse(self):
164 data = self.data
165 if len(data) < 4 or data[:4] != MAGIC:
166 raise TreeError("not an RBF0 stream", 0)
167 try:
168 while self.p < len(data):
169 self.record_offset = self.p
170 at = self.p
171 index = self.take(1, "record index")[0]
172 kind = self.take(1, "record type")[0]
173 if index == 0xFF:
174 if kind != 0xFF:
175 raise TreeError("close tag is not FF FF", at)
176 if not self.stack:
177 raise TreeError("close without an open element", at)
178 frame = self.stack.pop()
179 frame["node"]["end"] = self.p
180 if frame["attrs_seen"] < frame["attrs_declared"]:
181 frame["node"]["attribute_mismatch"] = True
182 self.attribute_mismatches += 1
183 if not self.stack:
184 self.root = frame["node"]
185 break
186 continue
187 if index == 0xFD:
188 if kind != 0xFF:
189 raise TreeError("text tag is not FD FF", at)
190 n = struct.unpack("<I", self.take(4, "text length"))[0]
191 raw = self.take(n, "text")
192 payload_at = self.p - n
193 body = raw[:-1] if raw.endswith(b"\x00") else raw
194 text, valid = _utf8(body)
195 if not valid:
196 self.invalid_utf8 += 1
197 node = {
198 "kind": "text",
199 "offset": at,
200 "payload_offset": payload_at,
201 "length": n,
202 "nul_terminated": raw.endswith(b"\x00"),
203 "text": text,
204 "utf8_valid": valid,
205 }
206 if not self.stack:
207 raise TreeError("text outside an element", at)
208 self._attach(self.stack[-1], node)
209 self.counts["texts"] += 1
210 continue
211 desc = self._descriptor(index, kind, at)
212 name = desc["name"]
213 if kind == 0x00:
214 raw = self.take(6, "element header")
215 payload_at = self.p - 6
216 word0, word1, attrs = struct.unpack("<HHH", raw)
217 if word0 or word1:
218 raise TreeError(f"element header word is not zero ({word0}, {word1})", at)
219 node = {
220 "kind": "element",
221 "name": name,
222 "descriptor": index,
223 "offset": at,
224 "header_offset": payload_at,
225 "attrs_declared": attrs,
226 "depth": len(self.stack) + 1,
227 "attributes": [],
228 "content": [],
229 "end": None,
230 }
231 self.counts["elements"] += 1
232 self.max_depth = max(self.max_depth, len(self.stack) + 1)
233 if self.stack:
234 self._attach(self.stack[-1], node)
235 else:
236 if self.root is not None:
237 raise TreeError("second root element", at)
238 self.root = node
239 self.stack.append({
240 "node": node,
241 "attrs_declared": attrs,
242 "attrs_seen": 0,
243 "content_started": False,
244 "child_seen": False,
245 "text_seen": False,
246 "depth": len(self.stack) + 1,
247 })
248 continue
249 if kind not in VALUE_TYPES:
250 raise TreeError(f"unknown record type {kind:#04x}", at)
251 node = self._value(kind, name, index, at)
252 if not self.stack:
253 raise TreeError("value outside an element", at)
254 self._attach(self.stack[-1], node)
255 self.counts["values"] += 1
256 except TreeError as exc:
257 if not self.error:
258 self.status = "truncated" if exc.truncated else "bad"
259 self.error = str(exc)
260 self.error_offset = exc.offset
261 if self.status == "ok":
262 if self.stack:
263 self.status = "truncated"
264 self.error = f"{len(self.stack)} unclosed element(s) at 0x{self.p:x}"
265 self.error_offset = self.p
266 elif self.root is None:
267 self.status = "bad"
268 self.error = "no root element"
269 self.error_offset = self.p
270 elif self.root.get("end") != len(data):
271 self.status = "trailing"
272 self.error = f"{len(data) - self.root['end']} bytes after the root closed"
273 self.error_offset = self.root["end"]
274 return {
275 "source": self.source,
276 "offset": self.offset,
277 "size": len(data),
278 "chunks": self.chunks,
279 "layout": "wide-64" if self.wide else "narrow-32",
280 "prologue": PROLOGUE.hex() if self.wide else "",
281 "root_name": self.root["name"] if self.root else "",
282 "status": self.status,
283 "error": self.error,
284 "error_offset": self.error_offset,
285 "end": self.root["end"] if self.root and self.root.get("end") is not None else self.p,
286 "descriptors": self.descs,
287 "descriptor_count": len(self.descs),
288 "distinct_descriptor_names": len(self.descriptor_names),
289 "counts": dict(self.counts),
290 "attribute_mismatches": self.attribute_mismatches,
291 "attribute_order_violations": self.attribute_order_violations,
292 "text_after_child": self.text_after_child,
293 "text_before_child": self.text_before_child,
294 "value_after_child": self.value_after_child,
295 "invalid_utf8": self.invalid_utf8,
296 "max_depth": self.max_depth,
297 "tree": self.root,
298 }
299
300 def _value(self, kind, name, index, at):
301 payload_at = self.p
302 extra = {}
303 if kind == 0x10:
304 raw = self.take(self.scalar, "integer")
305 value = struct.unpack("<Q" if self.wide else "<I", raw)[0]
306 self.counts["ints"] += 1
307 elif kind == 0x20 or kind == 0x30:
308 value = kind == 0x20
309 self.counts["bools"] += 1
310 elif kind == 0x40:
311 raw = self.take(self.scalar, "float")
312 value = struct.unpack("<d" if self.wide else "<f", raw)[0]
313 self.counts["floats"] += 1
314 elif kind == 0x50:
315 raw = self.take(3 * self.scalar, "vector")
316 value = list(struct.unpack("<ddd" if self.wide else "<fff", raw))
317 if any(not math.isfinite(v) for v in value):
318 extra["float_special"] = [_render(v) for v in value]
319 value = [v if math.isfinite(v) else None for v in value]
320 self.counts["vec3"] += 1
321 else: # 0x60
322 n = struct.unpack("<H", self.take(2, "string length"))[0]
323 raw = self.take(n, "string")
324 payload_at = self.p - n
325 body = raw[:-1] if raw.endswith(b"\x00") else raw
326 value, valid = _utf8(body)
327 if not valid:
328 self.invalid_utf8 += 1
329 extra = {"byte_length": n, "nul_terminated": raw.endswith(b"\x00"), "utf8_valid": valid}
330 self.counts["strings"] += 1
331 if isinstance(value, float) and not math.isfinite(value):
332 extra["float_special"] = _render(value)
333 value = None
334 return {
335 "kind": "value",
336 "name": name,
337 "descriptor": index,
338 "type": VALUE_TYPES[kind],
339 "offset": at,
340 "payload_offset": payload_at,
341 "size": self.p - payload_at,
342 "value": value,
343 **extra,
344 }
345
346
347def parse_resource(data, source="", offset=0, chunks=1):
348 """Parse one complete RBF0 resource into a tree document. A non-RBF0 magic raises; a malformed stream
349 returns a partial document with status bad or truncated."""
350 return Parser(data, source, offset, chunks).parse()
351
352
353def _rows(source):
354 """Return (rows, read) for a single resource or a directory of inflated streams/resources."""
355 if os.path.isdir(source):
356 entries = []
357 unnamed = []
358 for name in sorted(os.listdir(source)):
359 full = os.path.join(source, name)
360 if not os.path.isfile(full):
361 continue
362 with open(full, "rb") as f:
363 head = f.read(8)
364 match = re.match(r"([0-9a-fA-F]{6,})", name)
365 if match:
366 entries.append((int(match.group(1), 16), name, full, head))
367 else:
368 unnamed.append((name, full, head))
369 next_offset = max((e[0] for e in entries), default=-1) + 1
370 for name, full, head in unnamed:
371 entries.append((next_offset, name, full, head))
372 next_offset += 1
373 entries.sort(key=lambda e: e[0])
374 rows = [{"offset": off, "stored": os.path.getsize(full), "size": os.path.getsize(full),
375 "head": head, "name": name} for off, name, full, head in entries]
376 by_offset = {row["offset"]: full for row, (_, _, full, _) in zip(rows, entries)}
377
378 def read(row):
379 with open(by_offset[row["offset"]], "rb") as f:
380 return f.read()
381 return rows, read
382 with open(source, "rb") as f:
383 data = f.read()
384 row = {"offset": 0, "stored": len(data), "size": len(data), "head": data[:8],
385 "name": os.path.basename(source)}
386 return [row], lambda _row: data
387
388
389def decode_source(source, roots=None, offset=None, limit=None, progress=None):
390 """Decode every RBF0 start in `source`, joining 64 KiB continuations. Returns (docs, summary)."""
391 rows, read = _rows(source)
392 starts = [i for i, row in enumerate(rows) if row["head"][:4] == MAGIC]
393 if offset is not None:
394 starts = [i for i in starts if rows[i]["offset"] == offset]
395 if not starts:
396 raise SystemExit(f"no RBF0 resource at offset 0x{offset:x}")
397 wanted = set(roots or ())
398 docs = []
399 for i in starts:
400 blob = read(rows[i])
401 chunks = 1
402 doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks)
403 while (doc["status"] == "truncated" and chunks < MAX_CHUNKS and len(blob) < MAX_BYTES
404 and rows[i + chunks - 1]["size"] == MAX_CHUNK and i + chunks < len(rows)):
405 nxt = rows[i + chunks]
406 if nxt["head"][:4] in (MAGIC, b"PSIN"):
407 break
408 blob += read(nxt)
409 chunks += 1
410 doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks)
411 if doc["status"] != "truncated":
412 break
413 if wanted and doc["root_name"] not in wanted:
414 continue
415 docs.append(doc)
416 if limit is not None and len(docs) >= limit:
417 break
418 if progress:
419 progress(len(docs), len(starts))
420 summary = _summary(docs)
421 summary["source"] = os.path.abspath(source)
422 return docs, summary
423
424
425def _summary(docs):
426 roots = collections.Counter(d["root_name"] for d in docs)
427 layouts = collections.Counter(d["layout"] for d in docs)
428 status = collections.Counter(d["status"] for d in docs)
429 counts = collections.Counter()
430 for d in docs:
431 counts.update(d["counts"])
432 return {
433 "resources": len(docs),
434 "ok": status.get("ok", 0),
435 "bad": status.get("bad", 0),
436 "truncated": status.get("truncated", 0),
437 "trailing": status.get("trailing", 0),
438 "layouts": dict(layouts),
439 "roots": dict(roots),
440 "descriptors": sum(d["descriptor_count"] for d in docs),
441 "distinct_descriptor_names": len({x["name"] for d in docs for x in d["descriptors"]}),
442 "elements": counts.get("elements", 0),
443 "values": counts.get("values", 0),
444 "texts": counts.get("texts", 0),
445 "strings": counts.get("strings", 0),
446 "ints": counts.get("ints", 0),
447 "floats": counts.get("floats", 0),
448 "bools": counts.get("bools", 0),
449 "vec3": counts.get("vec3", 0),
450 "max_depth": max((d["max_depth"] for d in docs), default=0),
451 "attribute_mismatches": sum(d["attribute_mismatches"] for d in docs),
452 "attribute_order_violations": sum(d["attribute_order_violations"] for d in docs),
453 "text_after_child": sum(d["text_after_child"] for d in docs),
454 "value_after_child": sum(d["value_after_child"] for d in docs),
455 "invalid_utf8": sum(d["invalid_utf8"] for d in docs),
456 "status": dict(status),
457 }
458
459
460def _xml_safe(text):
461 return XML_BAD.sub("\ufffd", text)
462
463
464def _xml_node(parent, node, tag=None):
465 if node["kind"] == "element":
466 attrs = {"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]),
467 "offset": f"0x{node['offset']:x}", "attrs": str(node["attrs_declared"])}
468 if node.get("end") is not None:
469 attrs["end"] = f"0x{node['end']:x}"
470 el = ET.SubElement(parent, "node", attrs)
471 for value in node["attributes"]:
472 _xml_node(el, value, "attr")
473 for child in node["content"]:
474 _xml_node(el, child)
475 return el
476 tag = tag or ("text" if node["kind"] == "text" else "value")
477 attrs = {"offset": f"0x{node['offset']:x}"}
478 if node["kind"] == "value":
479 attrs.update({"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]),
480 "type": node["type"]})
481 if node.get("float_special") is not None:
482 text = _render(node["float_special"])
483 else:
484 text = _render(node["value"])
485 else:
486 attrs["length"] = str(node["length"])
487 text = node["text"]
488 if node.get("utf8_valid") is False:
489 attrs["utf8"] = "invalid"
490 el = ET.SubElement(parent, tag, attrs)
491 el.text = _xml_safe(text)
492 return el
493
494
495def write_xml(directory, docs):
496 """Write one generic XML file per resource. Element names are fixed, so any descriptor name is safe."""
497 os.makedirs(directory, exist_ok=True)
498 paths = []
499 for i, doc in enumerate(docs):
500 root = ET.Element("rbf0", {
501 "root": _xml_safe(doc["root_name"]), "layout": doc["layout"],
502 "offset": f"0x{doc['offset']:x}",
503 "size": str(doc["size"]), "descriptors": str(doc["descriptor_count"]),
504 "status": doc["status"]})
505 if doc["tree"] is not None:
506 _xml_node(root, doc["tree"])
507 tree = ET.ElementTree(root)
508 ET.indent(tree, space=" ")
509 name = f"{doc['offset']:08x}.xml"
510 path = os.path.join(directory, name)
511 if os.path.exists(path):
512 path = os.path.join(directory, f"{doc['offset']:08x}-{i:04d}.xml")
513 tree.write(path, encoding="utf-8", xml_declaration=True)
514 paths.append(path)
515 return paths
516
517
518def write_json(path, docs, summary):
519 with open(path, "w", encoding="utf-8") as f:
520 json.dump({"tool": "rbf0_tree", "format": 1, "summary": summary, "resources": docs},
521 f, indent=1, ensure_ascii=False, allow_nan=False)
522
523
524def main(argv=None):
525 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
526 ap.add_argument("source", help="a carve directory, a complete resource, or a single RBF0 stream")
527 ap.add_argument("out", help="JSON output path")
528 ap.add_argument("--xml", metavar="DIR", help="also write one generic XML file per resource into DIR")
529 ap.add_argument("--root", action="append", metavar="NAME", help="keep only this root schema (repeatable)")
530 ap.add_argument("--offset", type=lambda s: int(s, 0), help="decode only the resource at this archive offset")
531 ap.add_argument("--limit", type=int, help="stop after this many selected resources")
532 ap.add_argument("--quiet", action="store_true")
533 args = ap.parse_args(argv)
534
535 def progress(n, total):
536 if not args.quiet and (n % 100 == 0 or n == total):
537 print(f"[{n}/{total}] resources", flush=True)
538
539 docs, summary = decode_source(args.source, roots=args.root, offset=args.offset,
540 limit=args.limit, progress=progress)
541 write_json(args.out, docs, summary)
542 paths = write_xml(args.xml, docs) if args.xml else []
543 if not args.quiet:
544 print(f"{summary['resources']} resources: {summary['ok']} ok, {summary['bad']} bad, "
545 f"{summary['truncated']} truncated, {summary['trailing']} trailing")
546 print(f"{summary['elements']} elements, {summary['texts']} texts, {summary['strings']} strings, "
547 f"{summary['descriptors']} descriptors -> {args.out}")
548 if paths:
549 print(f"{len(paths)} XML files -> {args.xml}")
550 return 0 if summary["ok"] == summary["resources"] else 1
551
552
553if __name__ == "__main__":
554 sys.exit(main())