From e35cf21baeba76af503cf967e6f1614755ecd265 Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 29 Nov 2026 03:08:27 -0500 Subject: [PATCH 1/2] feat(freeusc): add --compare-arch CXTP vs DXT bit-diff report mode (#8) --- tests/test_volcanic_compare_arch.py | 226 +++++++++++++ tools/freeusc/volcanic_bitdiff.py | 478 +++++++++++++++++++++++++++- 2 files changed, 703 insertions(+), 1 deletion(-) create mode 100644 tests/test_volcanic_compare_arch.py diff --git a/tests/test_volcanic_compare_arch.py b/tests/test_volcanic_compare_arch.py new file mode 100644 index 0000000..749f1b6 --- /dev/null +++ b/tests/test_volcanic_compare_arch.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 FreePVR Contributors +""" +Clean-room tests for `volcanic_bitdiff.py --compare-arch / compare-arch`. + +Covers DXT-48-1536 vs CXTP-48-1536 JSON capture-manifest pairing, framing-delta +summarization, text/markdown/JSON rendering, and graceful error handling. + +Runs cleanly on any laptop without a phone or vendor binaries: + python3 -m unittest tests.test_volcanic_compare_arch -v + python3 -m unittest discover -s tests -v +""" + +from __future__ import annotations + +import json +import struct +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT / "tools" / "freeusc")) + +import volcanic_bitdiff as vbd # noqa: E402 + +# Minimal clean-room framing vectors (valid Volcanic USC words, no vendor blobs). +USC_BASE = struct.pack("<3I", 0x0414A76B, 0x80408808, 0x8000031C) # FOP + CTRL.END +USC_OP_FLIPPED = struct.pack("<3I", 0x0414A76B ^ 0x00FC0000, 0x80408808, 0x8000031C) # opcode bits [23:18] flipped +USC_INT = struct.pack("<2I", 0x091023F0, 0x81854008) # INT +USC_LONG = USC_BASE + USC_INT # length + instruction delta vs USC_BASE +USC_DMA = struct.pack("<4I", 0x0005834E, 0x5808021E, 0x01000380, 0x83000004) + + +def _write_manifest(path: Path, device: str, probes: list) -> None: + path.write_text(json.dumps({"device_name": device, "probes": probes})) + + +class TestCompareArchPairing(unittest.TestCase): + def test_pairs_by_name_and_reports_only_in(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "dxt.json", Path(td) / "cxtp.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "a", "usc_hex": USC_BASE.hex()}, {"name": "only_a", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "a", "usc_hex": USC_BASE.hex()}, {"name": "only_b", "usc_hex": USC_BASE.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + self.assertEqual(rep["pairing"]["matched"], ["a"]) + self.assertEqual(rep["pairing"]["only_in_a"], ["only_a"]) + self.assertEqual(rep["pairing"]["only_in_b"], ["only_b"]) + self.assertEqual(rep["pairing"]["matched_count"], 1) + + def test_identical_vs_differing_and_bit_range(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "dxt.json", Path(td) / "cxtp.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "same", "usc_hex": USC_BASE.hex()}, {"name": "op", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "same", "usc_hex": USC_BASE.hex()}, {"name": "op", "usc_hex": USC_OP_FLIPPED.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + self.assertEqual(rep["aggregate"]["identical_probes"], 1) + self.assertEqual(rep["aggregate"]["differing_probes"], 1) + by = {p["probe"]: p for p in rep["per_probe"]} + self.assertTrue(by["same"]["identical"]) + self.assertFalse(by["op"]["identical"]) + self.assertEqual(by["op"]["diff"]["diff_word_count"], 1) + self.assertEqual(by["op"]["diff"]["word_diffs"][0]["bit_ranges"], ["[23:18]"]) + + def test_length_and_instruction_deltas(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "dxt.json", Path(td) / "cxtp.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "grow", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "grow", "usc_hex": USC_LONG.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + p = rep["per_probe"][0] + self.assertTrue(p["mismatched_byte_length"]) + self.assertGreater(p["len_delta_bytes"], 0) + self.assertGreater(p["instruction_delta"], 0) + self.assertEqual(rep["aggregate"]["probes_with_length_mismatch"], 1) + self.assertEqual(rep["aggregate"]["total_len_delta_bytes"], p["len_delta_bytes"]) + + def test_family_histogram_and_opcode_shifts(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "dxt.json", Path(td) / "cxtp.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "p", "usc_hex": USC_INT.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + p = rep["per_probe"][0] + self.assertIn("family_histogram_a", p) + self.assertIn("family_histogram_b", p) + self.assertIn("family_delta", p) + self.assertIn("opcode_cluster_shifts", rep["aggregate"]) + self.assertIn("INT", rep["aggregate"]["opcode_cluster_shifts"]) + + def test_aggregate_union_mask_and_report_forms(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "dxt.json", Path(td) / "cxtp.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "p", "usc_hex": USC_OP_FLIPPED.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + self.assertEqual(rep["aggregate"]["union_xor_mask"], "0x00fc0000") + self.assertEqual(rep["aggregate"]["union_bit_ranges"], ["[23:18]"]) + txt = vbd.compare_report_to_text(rep) + md = vbd.compare_report_to_markdown(rep) + js = json.dumps(rep) + for s in (txt, md, js): + self.assertIn("p", s) + self.assertIn("Volcanic CXTP vs DXT", txt) + self.assertIn("# Volcanic CXTP vs DXT", md) + + +class TestCompareArchManifestForms(unittest.TestCase): + def test_words_payload_forms(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + words_a = [0x0414A76B, 0x80408808, 0x8000031C] + # hex-string, words, words_hex all encode the same bytes + for idx, probes in enumerate([ + [{"name": "p", "usc_hex": USC_BASE.hex()}], + [{"name": "p", "words": words_a}], + [{"name": "p", "words_hex": ["0x0414A76B", "0x80408808", "0x8000031C"]}], + ]): + _write_manifest(pa, "DXT-48-1536", probes) + _write_manifest(pb, "CXTP-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + self.assertTrue(rep["per_probe"][0]["identical"], f"form {idx}") + + def test_file_based_manifest_strips_vulkan_header(self) -> None: + with tempfile.TemporaryDirectory() as td: + d = Path(td) + # raw USC file + full Vulkan cache blob side by side + (d / "p.usc").write_bytes(USC_BASE) + hdr = vbd.VK_CACHE_HEADER_V1.pack(32, 1, vbd.IMG_VENDOR_ID, 0x71022448, bytes(range(16))) + struct.pack(" None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + _write_manifest(pa, "DXT-48-1536", []) + _write_manifest(pb, "CXTP-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + self.assertEqual(rep["pairing"]["matched"], []) + self.assertEqual(rep["pairing"]["only_in_b"], ["p"]) + self.assertEqual(rep["aggregate"]["identical_probes"], 0) + self.assertIn("no matched probes", vbd.compare_report_to_text(rep).lower()) + + +class TestCompareArchErrors(unittest.TestCase): + def test_missing_manifest_raises(self) -> None: + with self.assertRaises(FileNotFoundError): + vbd.compare_arch_manifests(Path("/tmp/does-not-exist-dxt.json"), Path("/tmp/does-not-exist-cxtp.json")) + + def test_malformed_json_raises(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + pa.write_text("{not json") + pb.write_text("{}") + with self.assertRaises(ValueError): + vbd.compare_arch_manifests(pa, pb) + + def test_missing_probes_key_raises(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + pa.write_text(json.dumps({"no_list_here": 1})) + pb.write_text(json.dumps({"no_list_here": 2})) + with self.assertRaises(ValueError): + vbd.compare_arch_manifests(pa, pb) + + def test_mismatched_lengths_do_not_raise(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "p", "usc_hex": USC_DMA.hex()}]) + rep = vbd.compare_arch_manifests(pa, pb) + self.assertEqual(len(rep["per_probe"]), 1) + + def test_cli_missing_manifest_nonzero_exit(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa = Path(td) / "exists.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + proc = subprocess.run( + [sys.executable, str(REPO_ROOT / "tools" / "freeusc" / "volcanic_bitdiff.py"), + "compare-arch", str(pa), str(Path(td) / "missing.json")], + capture_output=True, text=True, timeout=30, + ) + self.assertNotEqual(proc.returncode, 0) + self.assertIn("error", proc.stderr.lower()) + + def test_cli_json_and_text_formats(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + _write_manifest(pa, "DXT-48-1536", [{"name": "p", "usc_hex": USC_BASE.hex()}]) + _write_manifest(pb, "CXTP-48-1536", [{"name": "p", "usc_hex": USC_OP_FLIPPED.hex()}]) + cli = [sys.executable, str(REPO_ROOT / "tools" / "freeusc" / "volcanic_bitdiff.py")] + for args, marker in [ + (["compare-arch", str(pa), str(pb)], "union_xor_mask"), + (["compare-arch", str(pa), str(pb), "--format", "text"], "Volcanic CXTP"), + (["compare-arch", str(pa), str(pb), "--format", "markdown"], "# Volcanic CXTP"), + (["--compare-arch", str(pa), str(pb), "--format", "json"], "matched_count"), + (["--compare-arch", str(pa), str(pb), "--json"], "matched_count"), + ]: + proc = subprocess.run(cli + args, capture_output=True, text=True, timeout=30) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn(marker, proc.stdout) + + def test_cli_empty_manifest_graceful_exit_zero(self) -> None: + with tempfile.TemporaryDirectory() as td: + pa, pb = Path(td) / "a.json", Path(td) / "b.json" + _write_manifest(pa, "DXT-48-1536", []) + _write_manifest(pb, "CXTP-48-1536", []) + proc = subprocess.run( + [sys.executable, str(REPO_ROOT / "tools" / "freeusc" / "volcanic_bitdiff.py"), + "compare-arch", str(pa), str(pb), "--format", "text"], + capture_output=True, text=True, timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("Matched probes: 0", proc.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/freeusc/volcanic_bitdiff.py b/tools/freeusc/volcanic_bitdiff.py index fabe3c7..4514805 100755 --- a/tools/freeusc/volcanic_bitdiff.py +++ b/tools/freeusc/volcanic_bitdiff.py @@ -18,6 +18,10 @@ length-delta insertions/deletions via prefix/suffix + LCS anchor alignment). - `diff-dir`: Batch paired-twin differential sweep across a on-device capture directory keyed by `corpus_manifest.json`, clustering bitfield masks per probe group. + - `compare-arch` / `--compare-arch`: Compare two clean-room JSON capture manifests + (e.g., DXT-48-1536 vs CXTP-48-1536) — pair probes by name, summarize + instruction-word framing deltas, header/prefix/opcode-cluster shifts, and + bit-diff summaries as text, markdown, or JSON. - `analyze-rgx-sh`: Structural + near-twin bit-diff analysis across extracted `rgx.sh` USC chunks. - `--self-test`: Deterministic offline verification of synthetic pipeline cache parsing, twin bit-diffing, opcode-field clustering, and `rgx.sh` chunk analysis. @@ -615,6 +619,389 @@ def analyze_rgx_sh_chunks(manifest_path: Path, max_near_twins: int = 12) -> Dict } +def _hex_to_bytes(s: str) -> bytes: + """Decode a hex string (with optional 0x/0X prefix, whitespace) to bytes.""" + t = "".join(s.split()) + if t.lower().startswith("0x"): + t = t[2:] + if len(t) % 2 != 0: + # left-pad to even length for LSB-first clean-room vectors given as int hex + t = "0" + t + return bytes.fromhex(t) + + +def _probe_id(entry: Dict[str, Any]) -> Optional[str]: + for key in ("name", "id", "probe", "probe_name", "chunk_name", "primary_file"): + v = entry.get(key) + if isinstance(v, str) and v.strip(): + base = v.strip() + # strip common binary suffixes for file-based ids + for suf in (".pipeline_binary_0.bin", ".pipeline_cache.bin", ".bin", ".usc", ".blob"): + if base.endswith(suf): + base = base[: -len(suf)] + break + return base + return None + + +def _probe_payload_bytes(entry: Dict[str, Any], manifest_dir: Path) -> bytes: + """Extract raw USC byte payload from a capture-manifest probe entry. + + Accepted inline forms (checked in order): + - "usc_hex" / "code_hex" / "bytes_hex" / "hex" / "data_hex": hex string (LE words) + - "words": list of ints (u32 LE); "words_hex": list of hex strings + - file fields: "file", "blob_file", "path", "primary_file", + "pipeline_binary_file", "pipeline_cache_file", "usc_file" + Returns b"" when no payload is present (graceful empty-probe handling). + Raises FileNotFoundError when a referenced file is missing and ValueError on malformed hex. + """ + for key in ("usc_hex", "code_hex", "bytes_hex", "hex", "data_hex"): + v = entry.get(key) + if isinstance(v, str) and v.strip(): + try: + return _hex_to_bytes(v) + except ValueError as e: + raise ValueError(f"malformed hex in field {key!r}: {e}") from e + words = entry.get("words") + if isinstance(words, list) and words: + try: + packed = b"".join(struct.pack(" Tuple[Dict[str, bytes], Dict[str, Any]]: + """Load a clean-room JSON capture manifest into an ordered name->bytes map.""" + if not manifest_path.exists(): + raise FileNotFoundError(f"manifest not found: {manifest_path}") + try: + raw_obj = json.loads(manifest_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as e: + raise ValueError(f"malformed JSON in manifest {manifest_path}: {e}") from e + manifest_dir = manifest_path.parent + entries: Any = None + if isinstance(raw_obj, list): + entries = raw_obj + elif isinstance(raw_obj, dict): + for key in ("probes", "chunks", "captures", "entries", "files"): + if isinstance(raw_obj.get(key), list): + entries = raw_obj[key] + break + if entries is None and raw_obj: + # Tolerate {"": {"file": ...}} shapes. If the object + # has no probe-like dict values, it is not a manifest dict-map either. + candidates = [] + for k, v in raw_obj.items(): + if isinstance(v, dict): + entry = dict(v) + entry.setdefault("name", k) + candidates.append(entry) + if not candidates: + raise ValueError( + f"manifest {manifest_path} must contain a JSON array under 'probes' " + f"(or 'chunks'/'captures') or be a top-level array" + ) + entries = candidates + if not isinstance(entries, list): + raise ValueError( + f"manifest {manifest_path} must contain a JSON array under 'probes' " + f"(or 'chunks'/'captures') or be a top-level array" + ) + probes: Dict[str, bytes] = {} + for idx, entry in enumerate(entries): + if not isinstance(entry, dict): + raise ValueError(f"probe entry #{idx} in {manifest_path} is not a JSON object") + pid = _probe_id(entry) + if not pid: + raise ValueError(f"probe entry #{idx} in {manifest_path} lacks a probe name/id") + if pid in probes: + raise ValueError(f"duplicate probe id {pid!r} in manifest {manifest_path}") + try: + probes[pid] = _probe_payload_bytes(entry, manifest_dir) + except FileNotFoundError: + raise + except ValueError: + raise + meta: Dict[str, Any] = {} + if isinstance(raw_obj, dict): + for key in ("device", "device_name", "deviceName", "device_id", "deviceId", + "arch", "silicon", "target", "source", "capture"): + if key in raw_obj: + meta[key] = raw_obj[key] + return probes, meta + + +def compare_arch_manifests(manifest_a: Path, manifest_b: Path) -> Dict[str, Any]: + """Compare two clean-room capture manifests (e.g. DXT vs CXTP) and summarize framing deltas.""" + a_map, meta_a = _load_compare_probes(manifest_a) + b_map, meta_b = _load_compare_probes(manifest_b) + names_a = set(a_map.keys()) + names_b = set(b_map.keys()) + matched = sorted(names_a & names_b) + only_a = sorted(names_a - names_b) + only_b = sorted(names_b - names_a) + + per_probe: List[Dict[str, Any]] = [] + total_fam_a: Counter = Counter() + total_fam_b: Counter = Counter() + total_union_mask = 0 + agg_diff_words = 0 + agg_ins_words = 0 + agg_del_words = 0 + agg_identical = 0 + + for name in matched: + buf_a = a_map[name] + buf_b = b_map[name] + fr_a = frame_volcanic_instructions(buf_a) + fr_b = frame_volcanic_instructions(buf_b) + diff = diff_twin_bytes(buf_a, buf_b) + fam_a = dict(fr_a.get("family_histogram", {})) + fam_b = dict(fr_b.get("family_histogram", {})) + for k, v in fam_a.items(): + total_fam_a[k] += v + for k, v in fam_b.items(): + total_fam_b[k] += v + identical = bool(diff.get("identical")) + if identical: + agg_identical += 1 + agg_diff_words += int(diff.get("diff_word_count", diff.get("word_diffs", []).__len__() if isinstance(diff.get("word_diffs"), list) else 0)) + for ins in diff.get("insertions", []): + agg_ins_words += int(ins.get("word_count", 0)) + for dele in diff.get("deletions", []): + agg_del_words += int(dele.get("word_count", 0)) + try: + total_union_mask |= int(str(diff.get("union_xor_mask", "0x0")), 16) if diff.get("union_xor_mask") else 0 + except (ValueError, TypeError): + pass + # family delta for this probe + fam_delta: Dict[str, int] = {} + for fam in sorted(set(fam_a) | set(fam_b)): + d = int(fam_b.get(fam, 0)) - int(fam_a.get(fam, 0)) + if d != 0: + fam_delta[fam] = d + per_probe.append({ + "probe": name, + "identical": identical, + "size_a_bytes": len(buf_a), + "size_b_bytes": len(buf_b), + "len_delta_bytes": len(buf_b) - len(buf_a), + "len_delta_words": (len(buf_b) // 4) - (len(buf_a) // 4), + "instruction_count_a": int(fr_a.get("instruction_count", 0)), + "instruction_count_b": int(fr_b.get("instruction_count", 0)), + "instruction_delta": int(fr_b.get("instruction_count", 0)) - int(fr_a.get("instruction_count", 0)), + "word_count_a": int(fr_a.get("word_count_u32", len(buf_a) // 4)), + "word_count_b": int(fr_b.get("word_count_u32", len(buf_b) // 4)), + "framing_a_valid": bool(fr_a.get("valid")), + "framing_b_valid": bool(fr_b.get("valid")), + "ends_with_ctrl_end_a": bool(fr_a.get("ends_with_ctrl_end")), + "ends_with_ctrl_end_b": bool(fr_b.get("ends_with_ctrl_end")), + "family_histogram_a": fam_a, + "family_histogram_b": fam_b, + "family_delta": fam_delta, + "mismatched_byte_length": len(buf_a) != len(buf_b), + "diff": diff, + }) + + opcode_shifts: Dict[str, Any] = {} + for fam in sorted(set(total_fam_a) | set(total_fam_b)): + ca = total_fam_a.get(fam, 0) + cb = total_fam_b.get(fam, 0) + opcode_shifts[fam] = {"count_a": ca, "count_b": cb, "delta": cb - ca} + total_len_delta = sum(p["len_delta_bytes"] for p in per_probe) + total_inst_delta = sum(p["instruction_delta"] for p in per_probe) + + report: Dict[str, Any] = { + "schema_version": 1, + "arch_a": { + "manifest": str(manifest_a), + "label": str(meta_a.get("device_name") or meta_a.get("deviceName") or meta_a.get("device") or meta_a.get("arch") or meta_a.get("silicon") or ""), + "device_meta": meta_a, + "probe_count": len(a_map), + "total_bytes": sum(len(v) for v in a_map.values()), + }, + "arch_b": { + "manifest": str(manifest_b), + "label": str(meta_b.get("device_name") or meta_b.get("deviceName") or meta_b.get("device") or meta_b.get("arch") or meta_b.get("silicon") or ""), + "device_meta": meta_b, + "probe_count": len(b_map), + "total_bytes": sum(len(v) for v in b_map.values()), + }, + "pairing": { + "matched": matched, + "matched_count": len(matched), + "only_in_a": only_a, + "only_in_b": only_b, + "only_in_a_count": len(only_a), + "only_in_b_count": len(only_b), + }, + "per_probe": per_probe, + "aggregate": { + "identical_probes": agg_identical, + "differing_probes": len(per_probe) - agg_identical, + "total_len_delta_bytes": total_len_delta, + "total_len_delta_words": sum(p["len_delta_words"] for p in per_probe), + "total_instruction_delta": total_inst_delta, + "total_diff_words": agg_diff_words, + "total_inserted_words": agg_ins_words, + "total_deleted_words": agg_del_words, + "union_xor_mask": f"0x{total_union_mask:08x}", + "union_bit_ranges": bit_ranges_from_mask(total_union_mask), + "opcode_cluster_shifts": opcode_shifts, + "probes_with_length_mismatch": sum(1 for p in per_probe if p["mismatched_byte_length"]), + "probes_with_framing_error": sum(1 for p in per_probe if not (p["framing_a_valid"] and p["framing_b_valid"])), + }, + } + return report + + +def compare_report_to_text(report: Dict[str, Any]) -> str: + """Render a compare-arch report as human-readable plain text.""" + a = report.get("arch_a", {}) + b = report.get("arch_b", {}) + pairing = report.get("pairing", {}) + agg = report.get("aggregate", {}) + lines: List[str] = [] + lines.append("Volcanic CXTP vs DXT Bit-Diff Report") + lines.append("=" * 40) + lines.append(f"Arch A: {a.get('label') or 'A'} ({a.get('manifest')}) - {a.get('probe_count')} probes, {a.get('total_bytes')} bytes") + lines.append(f"Arch B: {b.get('label') or 'B'} ({b.get('manifest')}) - {b.get('probe_count')} probes, {b.get('total_bytes')} bytes") + lines.append("") + lines.append("Pairing") + lines.append("-------") + lines.append(f"Matched probes: {pairing.get('matched_count', 0)}") + if pairing.get("matched"): + lines.append(" matched: " + ", ".join(pairing["matched"])) + lines.append(f"Only in A: {pairing.get('only_in_a_count', 0)}" + (": " + ", ".join(pairing["only_in_a"]) if pairing.get("only_in_a") else "")) + lines.append(f"Only in B: {pairing.get('only_in_b_count', 0)}" + (": " + ", ".join(pairing["only_in_b"]) if pairing.get("only_in_b") else "")) + lines.append("") + lines.append("Aggregate summary") + lines.append("-----------------") + lines.append(f"Identical probes: {agg.get('identical_probes', 0)}") + lines.append(f"Differing probes: {agg.get('differing_probes', 0)}") + lines.append(f"Total length delta: {agg.get('total_len_delta_bytes', 0)} bytes ({agg.get('total_len_delta_words', 0)} words)") + lines.append(f"Total instruction delta: {agg.get('total_instruction_delta', 0)}") + lines.append(f"Total differing words: {agg.get('total_diff_words', 0)} (inserted {agg.get('total_inserted_words', 0)}, deleted {agg.get('total_deleted_words', 0)})") + lines.append(f"Union XOR mask: {agg.get('union_xor_mask', '0x00000000')} ranges {agg.get('union_bit_ranges', [])}") + lines.append(f"Probes with length mismatch: {agg.get('probes_with_length_mismatch', 0)}") + lines.append(f"Probes with framing error: {agg.get('probes_with_framing_error', 0)}") + lines.append("") + lines.append("Opcode cluster shifts (family: A -> B, delta)") + lines.append("---------------------------------------------") + shifts = agg.get("opcode_cluster_shifts", {}) + if shifts: + for fam, v in sorted(shifts.items()): + lines.append(f" {fam}: {v['count_a']} -> {v['count_b']} (delta {v['delta']:+d})") + else: + lines.append(" (no matched probes)") + lines.append("") + lines.append("Per-probe breakdown") + lines.append("-------------------") + per = report.get("per_probe", []) + if not per: + lines.append(" (empty - no matched probes)") + for p in per: + status = "IDENTICAL" if p["identical"] else "DIFFERS" + lines.append(f" {p['probe']}: status={status} size {p['size_a_bytes']}->{p['size_b_bytes']} bytes " + f"(delta {p['len_delta_bytes']:+d}) insts {p['instruction_count_a']}->{p['instruction_count_b']} " + f"(delta {p['instruction_delta']:+d})") + if not p["identical"]: + d = p["diff"] + lines.append(f" diff_words={d.get('diff_word_count', 0)} insert={len(d.get('insertions', []))} " + f"delete={len(d.get('deletions', []))} mask={d.get('union_xor_mask', '0x00000000')} " + f"ranges={d.get('union_bit_ranges', [])}") + return "\n".join(lines) + "\n" + + +def compare_report_to_markdown(report: Dict[str, Any]) -> str: + """Render a compare-arch report as human-readable Markdown.""" + a = report.get("arch_a", {}) + b = report.get("arch_b", {}) + pairing = report.get("pairing", {}) + agg = report.get("aggregate", {}) + lines: List[str] = [] + lines.append("# Volcanic CXTP vs DXT Bit-Diff Report") + lines.append("") + lines.append(f"- **Arch A:** {a.get('label') or 'A'} (`{a.get('manifest')}`) — {a.get('probe_count')} probes, {a.get('total_bytes')} bytes") + lines.append(f"- **Arch B:** {b.get('label') or 'B'} (`{b.get('manifest')}`) — {b.get('probe_count')} probes, {b.get('total_bytes')} bytes") + lines.append("") + lines.append("## Pairing") + lines.append("") + lines.append(f"- Matched probes: **{pairing.get('matched_count', 0)}**") + lines.append(f"- Only in A: **{pairing.get('only_in_a_count', 0)}**" + (": " + ", ".join(f"`{x}`" for x in pairing["only_in_a"]) if pairing.get("only_in_a") else "")) + lines.append(f"- Only in B: **{pairing.get('only_in_b_count', 0)}**" + (": " + ", ".join(f"`{x}`" for x in pairing["only_in_b"]) if pairing.get("only_in_b") else "")) + lines.append("") + lines.append("## Aggregate summary") + lines.append("") + lines.append(f"- Identical probes: `{agg.get('identical_probes', 0)}`") + lines.append(f"- Differing probes: `{agg.get('differing_probes', 0)}`") + lines.append(f"- Total length delta: `{agg.get('total_len_delta_bytes', 0)}` bytes (`{agg.get('total_len_delta_words', 0)}` words)") + lines.append(f"- Total instruction delta: `{agg.get('total_instruction_delta', 0)}`") + lines.append(f"- Total differing words: `{agg.get('total_diff_words', 0)}` (inserted `{agg.get('total_inserted_words', 0)}`, deleted `{agg.get('total_deleted_words', 0)}`)") + lines.append(f"- Union XOR mask: `{agg.get('union_xor_mask', '0x00000000')}` — ranges `{agg.get('union_bit_ranges', [])}`") + lines.append(f"- Probes with length mismatch: `{agg.get('probes_with_length_mismatch', 0)}`") + lines.append(f"- Probes with framing error: `{agg.get('probes_with_framing_error', 0)}`") + lines.append("") + lines.append("## Opcode cluster shifts") + lines.append("") + shifts = agg.get("opcode_cluster_shifts", {}) + if shifts: + lines.append("| Family | A | B | Delta |") + lines.append("| --- | ---: | ---: | ---: |") + for fam, v in sorted(shifts.items()): + lines.append(f"| `{fam}` | {v['count_a']} | {v['count_b']} | {v['delta']:+d} |") + else: + lines.append("(no matched probes)") + lines.append("") + lines.append("## Per-probe breakdown") + lines.append("") + per = report.get("per_probe", []) + if not per: + lines.append("(empty — no matched probes)") + else: + lines.append("| Probe | Status | Len A→B (bytes) | Inst A→B | Diff words | Insert/Delete |") + lines.append("| --- | --- | --- | --- | ---: | --- |") + for p in per: + status = "identical" if p["identical"] else "differs" + d = p["diff"] + iw = sum(int(x.get("word_count", 0)) for x in d.get("insertions", [])) + dw = sum(int(x.get("word_count", 0)) for x in d.get("deletions", [])) + lines.append(f"| `{p['probe']}` | {status} | {p['size_a_bytes']}→{p['size_b_bytes']} ({p['len_delta_bytes']:+d}) | " + f"{p['instruction_count_a']}→{p['instruction_count_b']} ({p['instruction_delta']:+d}) | " + f"{d.get('diff_word_count', 0)} | {iw}/{dw} |") + return "\n".join(lines) + "\n" + + def run_self_test(rgx_manifest: Optional[Path] = None) -> int: """Run deterministic offline self-tests covering all core analyzer features.""" # 1. Synthetic PowerVR Vulkan pipeline cache blob (36B header + zero pad + high-entropy USC chunk) @@ -685,7 +1072,36 @@ def run_self_test(rgx_manifest: Optional[Path] = None) -> int: assert framed["family_histogram"]["BIT_NO_P0_LUT"] == 1, framed assert framed["family_histogram"]["CTRL_LONG"] == 1, framed - # 7. Optional local `rgx.sh` chunk analysis check (when --rgx-manifest is provided) + # 7. Compare-arch synthetic DXT vs CXTP manifests (clean-room, inline hex) + import tempfile + from pathlib import Path as _P + _usc_a = struct.pack("<3I", 0x0414A76B, 0x80408808, 0x8000031C) + _usc_b = struct.pack("<3I", 0x0414A76B, 0x80408808, 0x8000031C) + _usc_b_op = struct.pack("<3I", 0x0414A76B ^ 0x00FC0000, 0x80408808, 0x8000031C) + _usc_long = struct.pack("<3I", 0x0414A76B, 0x80408808, 0x8000031C) + struct.pack("<2I", 0x091023F0, 0x81854008) + with tempfile.TemporaryDirectory(prefix="freepvr_compare_") as _td: + _p = _P(_td) + _ma = {"device_name": "DXT-48-1536", "probes": [{"name": "00_empty_nop", "usc_hex": _usc_a.hex()}, {"name": "04_iadd32", "usc_hex": _usc_a.hex()}, {"name": "only_dxt", "usc_hex": _usc_a.hex()}]} + _mb = {"device_name": "CXTP-48-1536", "probes": [{"name": "00_empty_nop", "usc_hex": _usc_b.hex()}, {"name": "04_iadd32", "usc_hex": _usc_b_op.hex()}, {"name": "only_cxtp", "usc_hex": _usc_a.hex()}]} + _pa = _p / "dxt.json" + _pb = _p / "cxtp.json" + _pa.write_text(json.dumps(_ma)) + _pb.write_text(json.dumps(_mb)) + _rep = compare_arch_manifests(_pa, _pb) + assert _rep["pairing"]["matched"] == ["00_empty_nop", "04_iadd32"], _rep["pairing"] + assert _rep["pairing"]["only_in_a"] == ["only_dxt"], _rep["pairing"] + assert _rep["pairing"]["only_in_b"] == ["only_cxtp"], _rep["pairing"] + assert _rep["aggregate"]["identical_probes"] == 1, _rep["aggregate"] + assert _rep["aggregate"]["differing_probes"] == 1, _rep["aggregate"] + _by = {p["probe"]: p for p in _rep["per_probe"]} + assert _by["00_empty_nop"]["identical"] is True + assert _by["04_iadd32"]["identical"] is False + assert "[23:18]" in str(_by["04_iadd32"]["diff"]), _by["04_iadd32"] + assert "Volcanic CXTP vs DXT" in compare_report_to_text(_rep) + assert "# Volcanic CXTP vs DXT" in compare_report_to_markdown(_rep) + print("[self-test] PASS: compare-arch manifest pairing, framing-delta, and report rendering") + + # 8. Optional local `rgx.sh` chunk analysis check (when --rgx-manifest is provided) if rgx_manifest is not None and rgx_manifest.exists(): res = analyze_rgx_sh_chunks(rgx_manifest, max_near_twins=5) @@ -754,6 +1170,11 @@ def main() -> int: ) ap.add_argument("--self-test", action="store_true", help="Run built-in offline verification suite") ap.add_argument("--rgx-manifest", type=Path, default=None, help="Optional rgx.sh chunks manifest.json for --self-test") + ap.add_argument("--compare-arch", nargs=2, metavar=("MANIFEST_A", "MANIFEST_B"), default=None, + help="Compare two clean-room JSON capture manifests (DXT vs CXTP) — shorthand for 'compare-arch'") + ap.add_argument("--format", choices=["text", "markdown", "json"], default=None, + help="Output format for --compare-arch / compare-arch (default: json; use text/markdown for human report)") + ap.add_argument("--json", action="store_true", help="Force JSON output for --compare-arch / compare-arch") sub = ap.add_subparsers(dest="cmd") @@ -777,11 +1198,66 @@ def main() -> int: p_frame = sub.add_parser("frame", help="Frame & validate a raw Volcanic USC shader binary") p_frame.add_argument("usc_bin", type=Path) + p_cmp = sub.add_parser("compare-arch", help="Compare two clean-room JSON capture manifests (DXT vs CXTP)") + p_cmp.add_argument("manifest_a", type=Path) + p_cmp.add_argument("manifest_b", type=Path) + p_cmp.add_argument("--format", choices=["text", "markdown", "json"], default=None, + help="Output format (default: json; use text/markdown for human report)") + p_cmp.add_argument("--json", action="store_true", help="Force JSON output") + p_cmp.add_argument("--output", type=Path, default=None, help="Write report to file instead of stdout") + args = ap.parse_args() if args.self_test: return run_self_test(args.rgx_manifest) + # --compare-arch top-level shorthand and 'compare-arch' subcommand share one path. + cmp_a: Optional[Path] = None + cmp_b: Optional[Path] = None + cmp_format: str = "json" + cmp_output: Optional[Path] = None + if getattr(args, "compare_arch", None): + cmp_a = Path(args.compare_arch[0]) + cmp_b = Path(args.compare_arch[1]) + if getattr(args, "format", None): + cmp_format = str(args.format) + if getattr(args, "json", False): + cmp_format = "json" + cmp_output = None + elif getattr(args, "cmd", None) == "compare-arch": + cmp_a = args.manifest_a + cmp_b = args.manifest_b + if args.format: + cmp_format = str(args.format) + if args.json: + cmp_format = "json" + cmp_output = args.output + if cmp_a is not None and cmp_b is not None: + try: + report = compare_arch_manifests(cmp_a, cmp_b) + except FileNotFoundError as e: + print(f"error: {e}", file=sys.stderr) + return 2 + except ValueError as e: + print(f"error: {e}", file=sys.stderr) + return 2 + except Exception as e: # graceful fallback for unexpected manifest shapes + print(f"error: failed to compare manifests: {e}", file=sys.stderr) + return 2 + if cmp_format == "json": + out_text = json.dumps(report, indent=2) + elif cmp_format == "text": + out_text = compare_report_to_text(report) + elif cmp_format == "markdown": + out_text = compare_report_to_markdown(report) + else: + out_text = json.dumps(report, indent=2) + if cmp_output is not None: + cmp_output.write_text(out_text, encoding="utf-8") + else: + print(out_text, end="" if out_text.endswith("\n") else "\n") + return 0 + if args.cmd == "parse-cache": raw = args.blob.read_bytes() hdr = parse_pipeline_blob_header(raw) From ed247ff462c12d3c646469a61e12d2117f1144c7 Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 29 Nov 2026 08:50:48 -0500 Subject: [PATCH 2/2] security(compare-arch): harden bit-diff against DoS, path traversal, report injection --- tests/test_volcanic_compare_arch_fuzz.py | 264 +++++++++++++++++++++++ tools/freeusc/volcanic_bitdiff.py | 104 +++++++-- 2 files changed, 354 insertions(+), 14 deletions(-) create mode 100644 tests/test_volcanic_compare_arch_fuzz.py diff --git a/tests/test_volcanic_compare_arch_fuzz.py b/tests/test_volcanic_compare_arch_fuzz.py new file mode 100644 index 0000000..277cbcf --- /dev/null +++ b/tests/test_volcanic_compare_arch_fuzz.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 FreePVR Contributors +""" +Adversarial fuzz / property tests for `volcanic_bitdiff.py --compare-arch` (PR #13 hardening). + +Throws thousands of malformed, truncated, mismatched-length, all-0x00, all-0xFF, +and randomized CXTP/DXT instruction streams at the framing parser, twin bit-diff, +header parser, candidate scanner, and compare-arch manifest loader. Every path +must be fail-closed: no unhandled exceptions, no crashes, no tracebacks, and +report renderers must never let manifest-controlled text inject lines or break +Markdown tables. + +Runs cleanly on any laptop without a phone or vendor binaries: + python3 -m unittest tests.test_volcanic_compare_arch_fuzz -v +""" + +from __future__ import annotations + +import json +import random +import struct +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT / "tools" / "freeusc")) + +import volcanic_bitdiff as vbd # noqa: E402 + +SEED = 20261129 +RNG = random.Random(SEED) +USC_BASE = struct.pack("<3I", 0x0414A76B, 0x80408808, 0x8000031C) + + +def _rand_bytes(max_len: int = 4096) -> bytes: + style = RNG.randrange(6) + if style == 0: + return b"" + if style == 1: + return bytes(RNG.randrange(256) for _ in range(RNG.randrange(0, max_len))) + if style == 2: + return b"\x00" * RNG.randrange(0, max_len) + if style == 3: + return b"\xff" * RNG.randrange(0, max_len) + if style == 4: + # truncated valid stream + return USC_BASE[: RNG.randrange(0, len(USC_BASE))] + # odd length + n = RNG.randrange(0, max_len) + if n % 2 == 0: + n += 1 + return bytes(RNG.randrange(256) for _ in range(n)) + + +def _rand_words(max_words: int = 512) -> bytes: + n = RNG.randrange(0, max_words) + return struct.pack(f"<{n}I", *[RNG.getrandbits(32) for _ in range(n)]) + + +class TestFuzzParsers(unittest.TestCase): + def test_frame_never_raises(self) -> None: + for _ in range(1500): + data = _rand_bytes() if RNG.random() < 0.5 else _rand_words() + try: + res = vbd.frame_volcanic_instructions(data) + except Exception as exc: # noqa: BLE001 - fuzz: any raise is a crash + self.fail(f"frame_volcanic_instructions raised {type(exc).__name__}: {exc} for len {len(data)}") + self.assertIsInstance(res, dict) + self.assertIn("valid", res) + self.assertIn("instruction_count", res) + # valid streams must round-trip word counts + if res["valid"]: + total = sum(i["word_count"] for i in res["instructions"]) + self.assertEqual(total, len(data) // 4) + + def test_diff_never_raises_and_masks_sane(self) -> None: + for _ in range(1000): + a = _rand_bytes(1024) if RNG.random() < 0.5 else _rand_words(256) + b = _rand_bytes(1024) if RNG.random() < 0.5 else _rand_words(256) + try: + d = vbd.diff_twin_bytes(a, b) + except Exception as exc: # noqa: BLE001 + self.fail(f"diff_twin_bytes raised {type(exc).__name__}: {exc}") + self.assertEqual(d["len_a"], len(a)) + self.assertEqual(d["len_b"], len(b)) + for wd in d.get("word_diffs", []): + self.assertEqual(wd["xor_mask"], wd["val_a"] ^ wd["val_b"]) + self.assertLessEqual(wd["xor_mask"], 0xFFFFFFFF) + self.assertEqual(wd["hamming_weight"], bin(wd["xor_mask"]).count("1")) + # bit ranges must exactly describe the mask + rebuilt = 0 + for r in wd["bit_ranges"]: + hi_s, lo_s = r.strip("[]").split(":") + hi, lo = int(hi_s), int(lo_s) + for bit in range(lo, hi + 1): + rebuilt |= 1 << bit + self.assertEqual(rebuilt, wd["xor_mask"]) + + def test_parsers_never_raise(self) -> None: + for _ in range(800): + data = _rand_bytes() + for fn in ( + lambda: vbd.parse_pipeline_blob_header(data), + lambda: vbd.locate_candidate_usc_chunks(data, 0), + lambda: vbd.locate_candidate_usc_chunks(data, RNG.randrange(0, 40)), + lambda: vbd.bit_ranges_from_mask(RNG.getrandbits(32)), + lambda: vbd.cluster_group_diffs({"g": [vbd.diff_twin_bytes(data, _rand_words(16))]}), + ): + try: + fn() + except Exception as exc: # noqa: BLE001 + self.fail(f"parser raised {type(exc).__name__}: {exc}") + + def test_frame_extreme_lengths(self) -> None: + for data in ( + b"", b"\x00", b"\x00" * 3, b"\x00" * 4, b"\xff" * 4, + b"\x00" * 65536, b"\xff" * 65536, b"\x00" * 65537, + ): + res = vbd.frame_volcanic_instructions(data) + self.assertIsInstance(res["valid"], bool) + + def test_large_shifted_diff_completes_linear(self) -> None: + n = 100_000 + a_words = list(range(n)) + b_words = list(range(n // 2, n)) + list(range(n // 2)) + ba = struct.pack(f"<{n}I", *a_words) + bb = struct.pack(f"<{n}I", *b_words) + start = time.time() + d = vbd.diff_twin_bytes(ba, bb) + elapsed = time.time() - start + self.assertLess(elapsed, 10.0, f"large shifted diff took {elapsed:.2f}s (quadratic DoS?)") + self.assertFalse(d["identical"]) + + def test_bit_ranges_roundtrip(self) -> None: + for _ in range(500): + mask = RNG.getrandbits(32) + rebuilt = 0 + for r in vbd.bit_ranges_from_mask(mask): + hi_s, lo_s = r.strip("[]").split(":") + for bit in range(int(lo_s), int(hi_s) + 1): + rebuilt |= 1 << bit + self.assertEqual(rebuilt, mask) + self.assertEqual(vbd.bit_ranges_from_mask(0), []) + self.assertEqual(vbd.bit_ranges_from_mask(0xFFFFFFFF), ["[31:0]"]) + + +class TestFuzzCompareArch(unittest.TestCase): + def test_compare_never_raises_on_evil_payloads(self) -> None: + with tempfile.TemporaryDirectory() as td: + d = Path(td) + for trial in range(250): + probes_a, probes_b = [], [] + for i in range(RNG.randrange(0, 4)): + name = f"p{i}" + ka = RNG.randrange(4) + if ka == 0: + probes_a.append({"name": name, "usc_hex": _rand_bytes(512).hex()}) + elif ka == 1: + probes_a.append({"name": name, "words": [RNG.getrandbits(32) for _ in range(RNG.randrange(0, 64))]}) + elif ka == 2: + probes_a.append({"name": name, "words_hex": [f"0x{RNG.getrandbits(32):08x}" for _ in range(RNG.randrange(0, 16))]}) + else: + probes_a.append({"name": name, "usc_hex": ""}) + probes_b.append({"name": name, "usc_hex": _rand_bytes(512).hex()}) + pa, pb = d / "a.json", d / "b.json" + pa.write_text(json.dumps({"device_name": "DXT-48-1536", "probes": probes_a})) + pb.write_text(json.dumps({"device_name": "CXTP-48-1536", "probes": probes_b})) + try: + rep = vbd.compare_arch_manifests(pa, pb) + txt = vbd.compare_report_to_text(rep) + md = vbd.compare_report_to_markdown(rep) + js = json.dumps(rep) + except Exception as exc: # noqa: BLE001 + self.fail(f"trial {trial}: compare raised {type(exc).__name__}: {exc}") + self.assertIn("Volcanic", txt) + self.assertIn("Volcanic", md) + self.assertEqual(json.loads(js)["schema_version"], 1) + # every markdown table row must remain a single well-formed row + for line in md.splitlines(): + if line.startswith("| `"): + self.assertTrue(line.endswith("|"), line) + self.assertGreaterEqual(line.count("|"), 5, line) + + def test_report_escaping(self) -> None: + evil = "p|ipe`tick`\nFAKE LINE: injected\r\nsecond" + with tempfile.TemporaryDirectory() as td: + d = Path(td) + blob = {"device_name": "DXT\nINJECTED", "probes": [{"name": evil, "usc_hex": USC_BASE.hex()}]} + pa, pb = d / "a.json", d / "b.json" + pa.write_text(json.dumps(blob)) + pb.write_text(json.dumps({"device_name": "CXTP", "probes": [{"name": evil, "usc_hex": USC_BASE.hex()}]})) + rep = vbd.compare_arch_manifests(pa, pb) + txt = vbd.compare_report_to_text(rep) + md = vbd.compare_report_to_markdown(rep) + self.assertNotIn("\nFAKE LINE", txt) + self.assertNotIn("\nFAKE LINE", md) + self.assertNotIn("`tick`", md) + self.assertNotIn("INJECTED\n", txt.split("Arch A:")[1].splitlines()[0] + "\n") + + def test_file_refs_contained(self) -> None: + with tempfile.TemporaryDirectory() as td: + d = Path(td) + (d / "sub").mkdir() + (d / "outside.usc").write_bytes(USC_BASE) + good = {"device_name": "CXTP-48-1536", "probes": [{"name": "p", "file": "outside.usc"}]} + bad = {"device_name": "DXT-48-1536", "probes": [{"name": "p", "file": "../outside.usc"}]} + pa = d / "sub" / "a.json" + pb = d / "b.json" + pa.write_text(json.dumps(bad)) + pb.write_text(json.dumps(good)) + with self.assertRaises(ValueError): + vbd.compare_arch_manifests(pa, pb) + # absolute path outside also blocked + pa.write_text(json.dumps({"device_name": "X", "probes": [{"name": "p", "file": str(d / "outside.usc")}]})) + with self.assertRaises(ValueError): + vbd.compare_arch_manifests(pa, pb) + + def test_cli_fail_closed_no_traceback(self) -> None: + with tempfile.TemporaryDirectory() as td: + d = Path(td) + cli = [sys.executable, str(REPO_ROOT / "tools" / "freeusc" / "volcanic_bitdiff.py")] + cases = [ + "{not json", + json.dumps({"probes": [{"name": "p", "usc_hex": "zz"}]}), + json.dumps({"no_list": 1}), + json.dumps({"probes": [{"name": "p", "file": "../escape.bin"}]}), + json.dumps({"probes": [{"useless": 1}]}), + "[]", + ] + for i, body in enumerate(cases): + m1, m2 = d / f"m1_{i}.json", d / f"m2_{i}.json" + m1.write_text(body) + m2.write_text(json.dumps({"device_name": "DXT-48-1536", "probes": [{"name": "p", "usc_hex": USC_BASE.hex()}]})) + proc = subprocess.run( + cli + ["compare-arch", str(m2), str(m1)], + capture_output=True, text=True, timeout=60, + ) + self.assertIn(proc.returncode, (0, 2), f"case {i} rc={proc.returncode} stderr={proc.stderr}") + self.assertNotIn("Traceback", proc.stderr) + + def test_hex_and_word_forms_reject_garbage(self) -> None: + with tempfile.TemporaryDirectory() as td: + d = Path(td) + pa, pb = d / "a.json", d / "b.json" + pb.write_text(json.dumps({"device_name": "B", "probes": [{"name": "p", "usc_hex": USC_BASE.hex()}]})) + for probe in ( + {"name": "p", "usc_hex": "zz"}, + {"name": "p", "usc_hex": "0xzz"}, + {"name": "p", "words": ["a"]}, + {"name": "p", "words_hex": [None]}, + {"name": "p", "words": [0] * (vbd._MAX_WORDS_PER_PROBE + 1)}, + ): + pa.write_text(json.dumps({"device_name": "A", "probes": [probe]})) + with self.assertRaises(ValueError): + vbd.compare_arch_manifests(pa, pb) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/freeusc/volcanic_bitdiff.py b/tools/freeusc/volcanic_bitdiff.py index 4514805..95dd1ad 100755 --- a/tools/freeusc/volcanic_bitdiff.py +++ b/tools/freeusc/volcanic_bitdiff.py @@ -45,6 +45,14 @@ VK_CACHE_HEADER_V1 = struct.Struct(" Dict[str, Any]: hamming_weight=bin(xm).count("1"), ) ) + elif len(words_a) * len(words_b) > _SEQMATCH_MAX_PRODUCT: + # Linear index-aligned fallback: difflib.SequenceMatcher is super-quadratic + # on adversarial large word sequences. Pair the overlapping inner prefix + # word-for-word and report the scaled tails as bulk del/ins. + paired = min(len(words_a), len(words_b)) + for k in range(paired): + wa = words_a[k] + wb = words_b[k] + if wa != wb: + xm = wa ^ wb + union_mask |= xm + word_diffs.append( + WordBitDiff( + word_index=prefix_words + k, + byte_offset_a=(prefix_words + k) * 4, + byte_offset_b=(prefix_words + k) * 4, + val_a=wa, + val_b=wb, + xor_mask=xm, + bit_ranges=bit_ranges_from_mask(xm), + hamming_weight=bin(xm).count("1"), + ) + ) + if len(words_a) > paired: + deletions.append( + { + "byte_offset_a": (prefix_words + paired) * 4, + "word_count": len(words_a) - paired, + "words_hex": [f"0x{w:08x}" for w in words_a[paired:]], + } + ) + if len(words_b) > paired: + insertions.append( + { + "byte_offset_b": (prefix_words + paired) * 4, + "word_count": len(words_b) - paired, + "words_hex": [f"0x{w:08x}" for w in words_b[paired:]], + } + ) else: sm = difflib.SequenceMatcher(None, words_a, words_b, autojunk=False) for tag, i1, i2, j1, j2 in sm.get_opcodes(): @@ -658,12 +705,16 @@ def _probe_payload_bytes(entry: Dict[str, Any], manifest_dir: Path) -> bytes: for key in ("usc_hex", "code_hex", "bytes_hex", "hex", "data_hex"): v = entry.get(key) if isinstance(v, str) and v.strip(): + if len(v) > _MAX_PROBE_PAYLOAD_BYTES * 2: + raise ValueError(f"hex payload in field {key!r} exceeds {_MAX_PROBE_PAYLOAD_BYTES} bytes (fail-closed)") try: return _hex_to_bytes(v) except ValueError as e: raise ValueError(f"malformed hex in field {key!r}: {e}") from e words = entry.get("words") if isinstance(words, list) and words: + if len(words) > _MAX_WORDS_PER_PROBE: + raise ValueError(f"words array exceeds {_MAX_WORDS_PER_PROBE} words (fail-closed)") try: packed = b"".join(struct.pack(" bytes: raise ValueError(f"malformed words array: {e}") from e wh = entry.get("words_hex") if isinstance(wh, list) and wh: + if len(wh) > _MAX_WORDS_PER_PROBE: + raise ValueError(f"words_hex array exceeds {_MAX_WORDS_PER_PROBE} words (fail-closed)") try: vals = [] for w in wh: @@ -690,9 +743,17 @@ def _probe_payload_bytes(entry: Dict[str, Any], manifest_dir: Path) -> bytes: p = Path(v.strip()) if not p.is_absolute(): p = manifest_dir / p + # Fail-closed containment: file references must resolve inside the + # manifest's own directory (no ../ or absolute-path escapes). + base = manifest_dir.resolve() + target = p.resolve() + if not target.is_relative_to(base): + raise ValueError(f"file reference {v.strip()!r} in field {key!r} escapes manifest directory (fail-closed)") + if target.stat().st_size > _MAX_PROBE_PAYLOAD_BYTES: + raise ValueError(f"referenced file {v.strip()!r} exceeds {_MAX_PROBE_PAYLOAD_BYTES} bytes (fail-closed)") # Stripped Vulkan header variants: if file is a full cache/binary blob, # peel the header so framing compares payload USC bytes directly. - raw = p.read_bytes() + raw = target.read_bytes() hdr = parse_pipeline_blob_header(raw) if hdr.format_kind in ("vk_pipeline_cache", "vk_pipeline_binary"): return raw[hdr.payload_offset :] @@ -885,6 +946,21 @@ def compare_arch_manifests(manifest_a: Path, manifest_b: Path) -> Dict[str, Any] return report +def _plain(value: Any) -> str: + """Flatten arbitrary manifest-controlled text for single-line plain reports.""" + return str(value).replace("\r", " ").replace("\n", " ") + + +def _md_cell(value: Any) -> str: + """Escape table/markdown-unsafe characters in cells and inline code.""" + return ( + _plain(value) + .replace("\\", "\\\\") + .replace("|", "\\|") + .replace("`", "'") + ) + + def compare_report_to_text(report: Dict[str, Any]) -> str: """Render a compare-arch report as human-readable plain text.""" a = report.get("arch_a", {}) @@ -894,16 +970,16 @@ def compare_report_to_text(report: Dict[str, Any]) -> str: lines: List[str] = [] lines.append("Volcanic CXTP vs DXT Bit-Diff Report") lines.append("=" * 40) - lines.append(f"Arch A: {a.get('label') or 'A'} ({a.get('manifest')}) - {a.get('probe_count')} probes, {a.get('total_bytes')} bytes") - lines.append(f"Arch B: {b.get('label') or 'B'} ({b.get('manifest')}) - {b.get('probe_count')} probes, {b.get('total_bytes')} bytes") + lines.append(f"Arch A: {_plain(a.get('label') or 'A')} ({_plain(a.get('manifest'))}) - {a.get('probe_count')} probes, {a.get('total_bytes')} bytes") + lines.append(f"Arch B: {_plain(b.get('label') or 'B')} ({_plain(b.get('manifest'))}) - {b.get('probe_count')} probes, {b.get('total_bytes')} bytes") lines.append("") lines.append("Pairing") lines.append("-------") lines.append(f"Matched probes: {pairing.get('matched_count', 0)}") if pairing.get("matched"): - lines.append(" matched: " + ", ".join(pairing["matched"])) - lines.append(f"Only in A: {pairing.get('only_in_a_count', 0)}" + (": " + ", ".join(pairing["only_in_a"]) if pairing.get("only_in_a") else "")) - lines.append(f"Only in B: {pairing.get('only_in_b_count', 0)}" + (": " + ", ".join(pairing["only_in_b"]) if pairing.get("only_in_b") else "")) + lines.append(" matched: " + ", ".join(_plain(x) for x in pairing["matched"])) + lines.append(f"Only in A: {pairing.get('only_in_a_count', 0)}" + (": " + ", ".join(_plain(x) for x in pairing["only_in_a"]) if pairing.get("only_in_a") else "")) + lines.append(f"Only in B: {pairing.get('only_in_b_count', 0)}" + (": " + ", ".join(_plain(x) for x in pairing["only_in_b"]) if pairing.get("only_in_b") else "")) lines.append("") lines.append("Aggregate summary") lines.append("-----------------") @@ -921,7 +997,7 @@ def compare_report_to_text(report: Dict[str, Any]) -> str: shifts = agg.get("opcode_cluster_shifts", {}) if shifts: for fam, v in sorted(shifts.items()): - lines.append(f" {fam}: {v['count_a']} -> {v['count_b']} (delta {v['delta']:+d})") + lines.append(f" {_plain(fam)}: {v['count_a']} -> {v['count_b']} (delta {v['delta']:+d})") else: lines.append(" (no matched probes)") lines.append("") @@ -932,7 +1008,7 @@ def compare_report_to_text(report: Dict[str, Any]) -> str: lines.append(" (empty - no matched probes)") for p in per: status = "IDENTICAL" if p["identical"] else "DIFFERS" - lines.append(f" {p['probe']}: status={status} size {p['size_a_bytes']}->{p['size_b_bytes']} bytes " + lines.append(f" {_plain(p['probe'])}: status={status} size {p['size_a_bytes']}->{p['size_b_bytes']} bytes " f"(delta {p['len_delta_bytes']:+d}) insts {p['instruction_count_a']}->{p['instruction_count_b']} " f"(delta {p['instruction_delta']:+d})") if not p["identical"]: @@ -952,14 +1028,14 @@ def compare_report_to_markdown(report: Dict[str, Any]) -> str: lines: List[str] = [] lines.append("# Volcanic CXTP vs DXT Bit-Diff Report") lines.append("") - lines.append(f"- **Arch A:** {a.get('label') or 'A'} (`{a.get('manifest')}`) — {a.get('probe_count')} probes, {a.get('total_bytes')} bytes") - lines.append(f"- **Arch B:** {b.get('label') or 'B'} (`{b.get('manifest')}`) — {b.get('probe_count')} probes, {b.get('total_bytes')} bytes") + lines.append(f"- **Arch A:** {_md_cell(a.get('label') or 'A')} (`{_md_cell(a.get('manifest'))}`) — {a.get('probe_count')} probes, {a.get('total_bytes')} bytes") + lines.append(f"- **Arch B:** {_md_cell(b.get('label') or 'B')} (`{_md_cell(b.get('manifest'))}`) — {b.get('probe_count')} probes, {b.get('total_bytes')} bytes") lines.append("") lines.append("## Pairing") lines.append("") lines.append(f"- Matched probes: **{pairing.get('matched_count', 0)}**") - lines.append(f"- Only in A: **{pairing.get('only_in_a_count', 0)}**" + (": " + ", ".join(f"`{x}`" for x in pairing["only_in_a"]) if pairing.get("only_in_a") else "")) - lines.append(f"- Only in B: **{pairing.get('only_in_b_count', 0)}**" + (": " + ", ".join(f"`{x}`" for x in pairing["only_in_b"]) if pairing.get("only_in_b") else "")) + lines.append(f"- Only in A: **{pairing.get('only_in_a_count', 0)}**" + (": " + ", ".join(f"`{_md_cell(x)}`" for x in pairing["only_in_a"]) if pairing.get("only_in_a") else "")) + lines.append(f"- Only in B: **{pairing.get('only_in_b_count', 0)}**" + (": " + ", ".join(f"`{_md_cell(x)}`" for x in pairing["only_in_b"]) if pairing.get("only_in_b") else "")) lines.append("") lines.append("## Aggregate summary") lines.append("") @@ -979,7 +1055,7 @@ def compare_report_to_markdown(report: Dict[str, Any]) -> str: lines.append("| Family | A | B | Delta |") lines.append("| --- | ---: | ---: | ---: |") for fam, v in sorted(shifts.items()): - lines.append(f"| `{fam}` | {v['count_a']} | {v['count_b']} | {v['delta']:+d} |") + lines.append(f"| `{_md_cell(fam)}` | {v['count_a']} | {v['count_b']} | {v['delta']:+d} |") else: lines.append("(no matched probes)") lines.append("") @@ -996,7 +1072,7 @@ def compare_report_to_markdown(report: Dict[str, Any]) -> str: d = p["diff"] iw = sum(int(x.get("word_count", 0)) for x in d.get("insertions", [])) dw = sum(int(x.get("word_count", 0)) for x in d.get("deletions", [])) - lines.append(f"| `{p['probe']}` | {status} | {p['size_a_bytes']}→{p['size_b_bytes']} ({p['len_delta_bytes']:+d}) | " + lines.append(f"| `{_md_cell(p['probe'])}` | {status} | {p['size_a_bytes']}→{p['size_b_bytes']} ({p['len_delta_bytes']:+d}) | " f"{p['instruction_count_a']}→{p['instruction_count_b']} ({p['instruction_delta']:+d}) | " f"{d.get('diff_word_count', 0)} | {iw}/{dw} |") return "\n".join(lines) + "\n"