Просмотр исходного кода

add deterministic manual UART I2C fuzz runner

高宇轩 3 месяцев назад
Родитель
Сommit
f0292319fa

+ 2 - 0
products/6400-front-rear/analysis-replay-closure.json

@@ -20,6 +20,7 @@
     "tools/package_6400_canonical.py",
     "tools/package_target.py",
     "tools/run_6400_formal.py",
+    "tools/run_6400_fuzz.py",
     "tools/run_6400_soak.py",
     "tools/run_6400_td.py",
     "tools/target_registry.py",
@@ -28,6 +29,7 @@
     "tests/host_i2c_register_read_tb.v",
     "tests/host_i2c_register_seq_read_tb.v",
     "tests/manual_6400_soak.py",
+    "tests/manual_6400_fuzz.py",
     "tests/sim/frame_rx_tb.v",
     "tests/sim/thermal_host_command_v2_tb.v",
     "tests/formal/6400-properties.json",

+ 62 - 0
tests/manual_6400_fuzz.py

@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+"""Deterministic malformed UART/I2C protocol fuzz without hardware dependencies."""
+from __future__ import annotations
+import json
+import os
+import random
+from pathlib import Path
+
+def crc16(data: bytes) -> int:
+    value = 0xFFFF
+    for byte in data:
+        value ^= byte << 8
+        for _ in range(8):
+            value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
+    return value
+
+def encode(kind: int, payload: bytes = b"") -> bytes:
+    body = bytes((kind, len(payload))) + payload
+    return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
+
+def decode(raw: bytes) -> bool:
+    return len(raw) >= 6 and raw[:2] == b"\xA5\x5A" and len(raw) == raw[3] + 6 and int.from_bytes(raw[-2:], "little") == crc16(raw[2:-2])
+
+def main() -> int:
+    seed = int(os.environ.get("PROD2U_FUZZ_SEED", "6400"))
+    iterations = int(os.environ.get("PROD2U_FUZZ_ITERATIONS", "10000"))
+    rng = random.Random(seed)
+    accepted = rejected = 0
+    for _ in range(iterations):
+        payload = bytes(rng.randrange(256) for _ in range(rng.randrange(33)))
+        raw = bytearray(encode(rng.randrange(1, 0x84), payload))
+        mutation = rng.randrange(5)
+        if mutation == 0:
+            raw[0] ^= 1
+        elif mutation == 1:
+            raw[-1] ^= 1
+        elif mutation == 2:
+            raw = raw[:-1]
+        elif mutation == 3:
+            raw[3] = (raw[3] + 1) & 0xFF
+        else:
+            raw.extend(bytes((0xA5, 0x5A)))
+        if decode(bytes(raw)):
+            accepted += 1
+        else:
+            rejected += 1
+    assert accepted == 0
+    # Register pointer fuzz: only the declared write windows are writable.
+    writable = lambda reg: 0x0100 <= reg <= 0x011F or reg == 0x0010
+    for _ in range(iterations):
+        reg = rng.randrange(0x10000)
+        if writable(reg):
+            assert reg == 0x0010 or 0x0100 <= reg <= 0x011F
+    result = {"status": "PASS", "seed": seed, "iterations": iterations, "accepted_mutations": accepted, "rejected_mutations": rejected, "write_window_guard": "PASS"}
+    output = os.environ.get("PROD2U_FUZZ_RESULT")
+    if output:
+        Path(output).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    print("MANUAL_FUZZ_PASS", json.dumps(result, sort_keys=True))
+    return 0
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1 - 0
tools/package_6400_canonical.py

@@ -117,6 +117,7 @@ def base_paths() -> list[str]:
         "tools/resource_scheduler.py",
         "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
         "tools/run_6400_soak.py",
+        "tools/run_6400_fuzz.py",
         "tools/formal-bin/yosys",
         "tools/package_target.py", "tools/package_6400_canonical.py",
         "tools/overlay_6400_packages.py",

+ 37 - 0
tools/run_6400_fuzz.py

@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Run the active deterministic protocol fuzz and emit a receipt."""
+from __future__ import annotations
+import hashlib, json, os, subprocess, sys, time
+from pathlib import Path
+ROOT = Path(__file__).resolve().parents[1]
+
+def sha256(path: Path) -> str:
+    h = hashlib.sha256()
+    with path.open("rb") as stream:
+        for block in iter(lambda: stream.read(1048576), b""): h.update(block)
+    return h.hexdigest()
+
+def git(*args: str) -> str:
+    return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
+
+def main() -> int:
+    dirty = git("status", "--porcelain")
+    if dirty:
+        raise SystemExit("fuzz requires a clean source worktree")
+    commit, tree = git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
+    test = ROOT / "tests/manual_6400_fuzz.py"
+    run_root = Path(os.environ.get("PROD2U_FUZZ_RUN_ROOT", "/data/prod2u/runs")) / ("6400-manual-fuzz-" + commit[:8])
+    run_root.mkdir(parents=True, exist_ok=False)
+    result = run_root / "fuzz-result.json"
+    env = os.environ.copy(); env["PROD2U_FUZZ_RESULT"] = str(result)
+    env.setdefault("PROD2U_FUZZ_ITERATIONS", "10000")
+    started = time.monotonic()
+    completed = subprocess.run([sys.executable, "-B", str(test)], cwd=ROOT, env=env, text=True, capture_output=True, check=False)
+    status = "PASS" if completed.returncode == 0 and result.is_file() else "FAIL"
+    receipt = {"schema":"prod2u-6400-manual-fuzz-receipt-v1","run_id":run_root.name,"status":status,"commit":commit,"tree":tree,"clean":not bool(dirty),"iterations":int(env["PROD2U_FUZZ_ITERATIONS"]),"duration_seconds":round(time.monotonic()-started,3),"result":json.loads(result.read_text()) if result.is_file() else None,"stdout":completed.stdout[-4000:],"stderr":completed.stderr[-4000:],"hardware":"NOT_RUN"}
+    path = run_root / "fuzz-receipt.json"; path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    print(path); print("MANUAL_FUZZ_PASS" if status == "PASS" else "MANUAL_FUZZ_FAIL")
+    return 0 if status == "PASS" else 1
+
+if __name__ == "__main__":
+    raise SystemExit(main())