upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tools/rbf0_encode.py
diff options
context:
space:
mode:
authorgbezzuoli <guilhermebezzuoli@outlook.com>2026-11-22 18:46:57 -0300
committergbezzuoli <guilhermebezzuoli@outlook.com>2026-11-22 18:46:57 -0300
commita2f8aae55c22c3ba1d4cb8f8d39c5eb960543c1c (patch)
tree452b899f605e2774850f9c0e4a354f8df12808a3 /tools/rbf0_encode.py
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
rbf0_encode: --check fails on a refused resource; refuse attribute records the count does not cover (BUILD-1084)
Four findings by @HQasper on tools/rbf0_encode.py: - `--check` exited 0 when resources were refused, so a round trip that verified nothing read as success. It now exits 0 only when every resource is byte-identical, as rbf0_tree.py does for a resource that is not ok. - The element header count came from `attrs_declared` while every node of `attributes` was written, so an attribute appended by hand encoded as the element's first content value: a different tree with status ok. encode() now refuses more attribute records than the count (value), and an element short of its count that has a value in its content, which would decode as an attribute (order). A parsed element short of its count with no such value still round-trips exactly. - `blob[:doc["size"]]` in resources() could not trim anything. The slice is gone and check() compares the joined length with the recorded size; two carved streams of one name are refused instead of the last one silently winning. - docs/rbf0.md 9.6 lists the `value` refusals and says what `--check` exits with. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'tools/rbf0_encode.py')
-rw-r--r--tools/rbf0_encode.py33
1 files changed, 24 insertions, 9 deletions
diff --git a/tools/rbf0_encode.py b/tools/rbf0_encode.py
index eaf9d9c04..8e62240b6 100644
--- a/tools/rbf0_encode.py
+++ b/tools/rbf0_encode.py
@@ -11,16 +11,18 @@ instead of writing something else:
11 status the parse was not complete (bad, truncated, or bytes after the root closed) 11 status the parse was not complete (bad, truncated, or bytes after the root closed)
12 utf8 a descriptor name, string or text had invalid UTF-8, which the decoder replaced with U+FFFD 12 utf8 a descriptor name, string or text had invalid UTF-8, which the decoder replaced with U+FFFD
13 nan a float or vec3 component was NaN, whose bits the tree renders as text (infinities are exact) 13 nan a float or vec3 component was NaN, whose bits the tree renders as text (infinities are exact)
14 order a value counted as an attribute came after the element's content started 14 order a value counted as an attribute came after the element's content started, or an element short of
15 its attribute count has a value in its content, which would decode as an attribute
15 descriptor a descriptor index outside the table, or a first use out of order 16 descriptor a descriptor index outside the table, or a first use out of order
16 length a string or text no longer has its recorded byte length 17 length a string or text no longer has its recorded byte length
17 value a value the record cannot hold (an integer out of range, an unknown type) 18 value a value the record cannot hold (an integer out of range, a float that overflows the layout, an
19 unknown type, more attribute records than the element's attribute count)
18 20
19Usage: 21Usage:
20 python -I rbf0_encode.py --check <carve-dir | resource> [--limit N] 22 python -I rbf0_encode.py --check <carve-dir | resource> [--limit N]
21 Decode every RBF0 resource (joining 64 KiB continuations as rbf0_tree.py does), encode it, and compare the 23 Decode every RBF0 resource (joining 64 KiB continuations as rbf0_tree.py does), encode it, and compare the
22 result with the original bytes. Prints counts only: exact, different, and refused by reason. Exit 1 when a 24 result with the original bytes. Prints counts only: exact, different, and refused by reason. Exit 1 when a
23 resource encodes to different bytes. 25 resource encodes to different bytes or was refused: only a run where every resource is exact exits 0.
24 python -I rbf0_encode.py <rbf0_tree.json> <new_out_dir> 26 python -I rbf0_encode.py <rbf0_tree.json> <new_out_dir>
25 Write each resource of an rbf0_tree.py JSON report (possibly edited) as <offset>.rbf. The directory must be 27 Write each resource of an rbf0_tree.py JSON report (possibly edited) as <offset>.rbf. The directory must be
26 new or empty. 28 new or empty.
@@ -149,6 +151,14 @@ class _Writer:
149 attrs = node.get("attrs_declared", len(node.get("attributes", []))) 151 attrs = node.get("attrs_declared", len(node.get("attributes", [])))
150 if not isinstance(attrs, int) or isinstance(attrs, bool) or not 0 <= attrs <= 0xFFFF: 152 if not isinstance(attrs, int) or isinstance(attrs, bool) or not 0 <= attrs <= 0xFFFF:
151 raise EncodeError("value", f"attribute count {attrs!r}") 153 raise EncodeError("value", f"attribute count {attrs!r}")
154 # The header word says how many of the following value records are attributes. One record more would decode
155 # as the element's first content value; with fewer, the next content value would decode as an attribute.
156 listed = len(node.get("attributes", []))
157 if listed > attrs:
158 raise EncodeError("value", f"element {node.get('name')!r} has {listed} attribute records, count {attrs}")
159 if listed < attrs and any(c.get("kind") == "value" for c in node.get("content", [])):
160 raise EncodeError("order", f"element {node.get('name')!r} is short of its {attrs} attributes and has a "
161 "value in its content")
152 self.record(node, 0x00) 162 self.record(node, 0x00)
153 self.out += struct.pack("<HHH", 0, 0, attrs) 163 self.out += struct.pack("<HHH", 0, 0, attrs)
154 for child in node.get("attributes", []): 164 for child in node.get("attributes", []):
@@ -183,14 +193,19 @@ def encode(doc):
183 193
184 194
185def resources(source, limit=None): 195def resources(source, limit=None):
186 """Yield (doc, original bytes) for every RBF0 resource in a carve directory or a single file.""" 196 """Yield (doc, original bytes) for every RBF0 resource in a carve directory or a single file. The bytes are
197 the resource's chunks joined as rbf0_tree.decode_source joined them; check() compares their length with the
198 size the document records."""
187 docs, _summary = rbf0_tree.decode_source(source, limit=limit) 199 docs, _summary = rbf0_tree.decode_source(source, limit=limit)
188 rows, read = rbf0_tree._rows(source) 200 rows, read = rbf0_tree._rows(source)
189 by_name = {row["name"]: i for i, row in enumerate(rows)} 201 by_name = {}
202 for i, row in enumerate(rows):
203 if row["name"] in by_name: # a document names its first chunk; two rows of one name cannot be told apart
204 raise rbf0_tree.SelectionError(f"two carved streams are named {row['name']!r}")
205 by_name[row["name"]] = i
190 for doc in docs: 206 for doc in docs:
191 i = by_name[doc["source"]] 207 i = by_name[doc["source"]]
192 blob = b"".join(read(rows[j]) for j in range(i, i + doc["chunks"])) 208 yield doc, b"".join(read(rows[j]) for j in range(i, i + doc["chunks"]))
193 yield doc, blob[:doc["size"]]
194 209
195 210
196def check(source, limit=None): 211def check(source, limit=None):
@@ -208,7 +223,7 @@ def check(source, limit=None):
208 counts["refused"] += 1 223 counts["refused"] += 1
209 reasons[e.reason] += 1 224 reasons[e.reason] += 1
210 continue 225 continue
211 if encoded == blob: 226 if encoded == blob and doc.get("size") == len(blob):
212 counts["exact"] += 1 227 counts["exact"] += 1
213 layout["exact"] += 1 228 layout["exact"] += 1
214 else: 229 else:
@@ -279,7 +294,7 @@ def main(argv=None):
279 print(f" refused ({reason}): {n}") 294 print(f" refused ({reason}): {n}")
280 for layout, c in sorted(r["by_layout"].items()): 295 for layout, c in sorted(r["by_layout"].items()):
281 print(f" {layout}: {c['exact']} of {c['resources']} exact") 296 print(f" {layout}: {c['exact']} of {c['resources']} exact")
282 return 1 if r["different"] else 0 297 return 1 if r["different"] or r["refused"] else 0
283 if not a.report or not a.out: 298 if not a.report or not a.out:
284 ap.error("give --check SOURCE, or a report and an output directory") 299 ap.error("give --check SOURCE, or a report and an output directory")
285 if a.limit is not None: 300 if a.limit is not None: