"""Read probe saves: a save file, or a work RAM dump, which holds a full copy at $4000. python tools/decode.py FILE [--run N] [--boots] python tools/decode.py A=FILE B=FILE ... side by side, differences marked A save may hold every other byte, as the bus does, so both layouts are tried. """ import struct import sys from pathlib import Path MAGIC = b"MDPB" FORMAT = 4 FORMATS = (4, 5, 6) # 5: run slots of a fixed size, then the long run (header 48-55); 6: MAX_TESTS at 56 BOOT_LOGS = 32 RESET_LOGS = 32 RESET_ENTRY = 40 RESETS = 64 + BOOT_LOGS * 32 RUNS = RESETS + RESET_LOGS * RESET_ENTRY RUN_SLOTS = 3 MAX_TESTS = 64 STATUS = 32 DIR = STATUS + MAX_TESTS DIR_ENTRY = 10 STATE = {0: "not run", 1: "started", 2: "done", 3: "hung"} def crc16(b): c = 0xFFFF for x in b: c ^= x << 8 for _ in range(8): c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF return c def find(raw): """Anywhere in a save, a RAM dump or a save state: RAM may be held byte-swapped.""" swapped = bytearray(raw[:len(raw) & ~1]) swapped[0::2], swapped[1::2] = swapped[1::2], swapped[0::2] spare = None for b in (raw, raw[1::2], raw[::2], bytes(swapped)): at = b.find(MAGIC) while at >= 0: if struct.unpack_from(">H", b, at + 4)[0] in FORMATS and crc16(b[at:at + 62]) == struct.unpack_from(">H", b, at + 62)[0]: whole = b[at:at + struct.unpack_from(">H", b, at + 6)[0]] if b"RUN3" in whole: # a state can hold a stray copy of the header alone return whole spare = spare or whole at = b.find(MAGIC, at + 1) return spare def layout(s): """(run slots, bytes a run) for this save's format.""" if struct.unpack_from(">H", s, 4)[0] >= 5: return s[48], struct.unpack_from(">H", s, 50)[0] return RUN_SLOTS, (len(s) - RUNS) // RUN_SLOTS def soak_area(s): """(offset, length) of the long run's area, or None.""" if struct.unpack_from(">H", s, 4)[0] < 5: return None return struct.unpack_from(">HH", s, 52) def parse(path): s = find(Path(path).read_bytes()) if s is None: raise SystemExit(f"{path}: no good report (format {FORMATS})") boots, runs = struct.unpack_from(">II", s, 8) cur = s[16] slots, rb = layout(s) dir_at = STATUS + (s[56] if struct.unpack_from(">H", s, 4)[0] >= 6 else MAX_TESTS) out = {"boots": boots, "runs": runs, "log": [], "run": [], "resets": [], "raw": s} for i in range(RESET_LOGS): e = s[RESETS + i * RESET_ENTRY:RESETS + (i + 1) * RESET_ENTRY] n = struct.unpack(">I", e[:4])[0] if n: out["resets"].append((n, struct.unpack(">18H", e[4:]))) out["resets"].sort() for i in range(BOOT_LOGS): e = s[64 + i * 32:96 + i * 32] n = struct.unpack(">I", e[:4])[0] if n: hv, st = struct.unpack(">HH", e[4:8]) nz, total = struct.unpack(">II", e[12:20]) vram, cram, vsram, zram = struct.unpack(">HHHH", e[20:28]) out["log"].append(dict(boot=n, hv=hv, status=st, warm=e[8], version=e[9], sram=e[10], source=e[11], ram_nonzero=nz, ram_sum=total, vram=vram, cram=cram, vsram=vsram, zram=zram, zram_sum=struct.unpack(">I", e[28:32])[0])) for k in range(slots): r = s[RUNS + k * rb:RUNS + (k + 1) * rb] if r[:4] != b"RUN3": continue run, boot = struct.unpack_from(">II", r, 4) tests = [] for i in range(r[21]): e = r[dir_at + i * DIR_ENTRY:dir_at + (i + 1) * DIR_ENTRY] off, length, crc = struct.unpack(">HHH", e[4:10]) data = r[off:off + length] recs = [struct.unpack_from(">HHI", data, j) for j in range(0, length, 8)] tests.append(dict(index=i, tag=e[:4].decode("ascii", "replace").strip("\0"), status=STATE.get(r[STATUS + i], "?"), crc_ok=not length or crc16(data) == crc, records=recs)) out["run"].append(dict(run=run, boot=boot, build=r[12:20].decode("ascii", "replace").strip(), version=r[20], tests=tests, current=k == cur)) out["run"].sort(key=lambda x: x["run"]) return out def latest(r): return r["run"][-1] if r["run"] else {"tests": [], "run": 0, "build": "", "version": 0, "boot": 0} def show(path, want=None, boots=False): r = parse(path) print(f"boots {r['boots']} runs {r['runs']} kept {[x['run'] for x in r['run']]}") if boots: for e in r["log"]: print(e) x = next((q for q in r["run"] if q["run"] == want), None) if want else latest(r) print(f"run {x['run']} began boot {x['boot']} build {x['build']} version {x['version']:02X}") for t in x["tests"]: v = " ".join(f"{a[2]:X}" for a in t["records"][:6]) more = f" +{len(t['records']) - 6}" if len(t["records"]) > 6 else "" print(f"{t['tag']:5} {t['status']:8} {'crc ok' if t['crc_ok'] else 'CRC BAD':7} {v}{more}") def side(pairs): R = {n: latest(parse(p)) for n, p in pairs} tags = list(dict.fromkeys(t["tag"] for r in R.values() for t in r["tests"] if t["tag"])) print(f"{'':10}" + "".join(f"{n:>24}" for n in R)) for tag in tags: ids = sorted({a[0] for r in R.values() for t in r["tests"] if t["tag"] == tag for a in t["records"]}) for i in ids: cells = [] for r in R.values(): t = next((t for t in r["tests"] if t["tag"] == tag), None) v = sorted(a[2] for a in t["records"] if a[0] == i) if t else [] cells.append(("-" if not v else str(v[0]) if v[0] == v[-1] else f"{v[0]}-{v[-1]}", v)) mark = "" if len({c[0] for c in cells}) < 2 else " *" print(f"{tag:5} {i:<4}" + "".join(f"{c[0]:>24}" for c in cells) + mark) if __name__ == "__main__": a = [x for x in sys.argv[1:] if not x.startswith("--")] if any("=" in x for x in a): side([x.split("=", 1) for x in a]) else: run = int(sys.argv[sys.argv.index("--run") + 1]) if "--run" in sys.argv else None show([x for x in a if not x.isdigit()][0], run, "--boots" in sys.argv)