#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 0's judge run: every local Lynx image through the one front door, read in place. python -I scripts/m0_formats.py # the exit numbers (docs/validation.md, M0) python -I scripts/m0_formats.py --list # one line per image Checks, as the brief's M0 exit words them: 1. every image loads without error (the boot ROM is refused as a cart and accepted as a boot ROM by hash: counted separately); 2. every .lnx and its .lyx resolve to the same SHA-1 and the same description; 3. the census numbers reproduce over distinct headerless payloads: block size from a table, from the size rule only, from neither; 4. the block-size conflicts (C14) are reported; 5. LNX -> LYX -> LNX is byte-identical for every header that agrees with the table. Nothing is written anywhere; the LYX and LNX of step 5 exist only in memory. """ from __future__ import annotations import argparse import collections import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "src")) import hashlib import lynx_python.cart.formats as formats_module import lynx_python.cart.loader as loader_module from lynx_python import romsets from lynx_python.cart import NotACart, describe from lynx_python.cart.convert import ConvertError, to_lnx, to_lyx from lynx_python.cart.formats import ( _sevenzip_members, _zip_members, decode_eeprom, sniff, ) from lynx_python.cart.table import default_table # Romsets by environment variable only (NO_INTRO_DIR, LYNX_EXTRA_SETS). SETS = romsets.all_sets() COMPARED = ("sha1", "bank0_block", "bank1_block", "audin", "rotation", "eeprom", "boot", "name") def images(): """(set, archive path, member, bytes, container) for every cart member, in place.""" for source, folder in SETS.items(): for path in sorted(folder.iterdir()): if not path.is_file(): continue suffix = path.suffix.lower() if suffix == ".zip": members, container = _zip_members(path.read_bytes()), "zip" elif suffix == ".7z": members, container = _sevenzip_members(path), "7z" elif suffix in (".lnx", ".lyx", ".o", ".bll", ".com"): members, container = [(path.name, path.read_bytes())], "loose" else: continue for name, data in members: yield source, path, name, data, container def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--list", action="store_true") parser.add_argument( "--seed-fault", choices=["size-rule", "header-version"], help="break one rule in this process only, to show the gate can fail", ) args = parser.parse_args() if args.seed_fault == "size-rule": # no payload size matches the rule any more loader_module.SIZE_RULE.clear() loader_module.SIZE_RULE.update({256 * b + 1: b for b in loader_module.BLOCK_SIZES}) elif args.seed_fault == "header-version": # the converter writes version 0 original = formats_module.LnxHeader.to_bytes def to_bytes(self): data = bytearray(original(self)) data[8:10] = b"\0\0" return bytes(data) formats_module.LnxHeader.to_bytes = to_bytes loaded, errors, bootroms = [], [], [] by_format = collections.Counter() for source, path, member, data, container in images(): try: d = describe(data, member=member, container=container) except NotACart: bootroms.append((source, member, hashlib.sha1(data).hexdigest())) by_format[("bootrom", container)] += 1 continue except Exception as exc: # noqa: BLE001 - the judge counts every failure errors.append((source, member, repr(exc))) continue loaded.append((source, path, member, d, data)) by_format[(d.kind, container)] += 1 if args.list: print( f"{source}: {member}: {d.kind} {d.sha1[:12]} b0={d.bank0_block}" f"({d.provenance['bank0_block']}) rot={d.rotation}({d.provenance['rotation']})" ) carts = [x for x in loaded if x[3].kind != "bll"] print("## 1. Loading") print( f"images: {len(loaded) + len(errors) + len(bootroms)}; loaded {len(loaded)} " f"({len(carts)} carts, {len(loaded) - len(carts)} BLL); boot ROM recognised " f"by hash {len(bootroms)}; errors {len(errors)}" ) for e in errors: print(" ERROR", *e) print( "by format and container: " + ", ".join(f"{k} in {c}: {n}" for (k, c), n in sorted(by_format.items())) ) print("\n## 2. .lnx against .lyx") lyx = collections.defaultdict(list) for x in carts: if x[3].kind == "raw": lyx[x[3].sha1].append(x[3]) lnx = [x for x in carts if x[3].kind == "lnx"] same_sha = same_desc = 0 for _, _, member, d, _ in lnx: partners = lyx.get(d.sha1, []) if partners: same_sha += 1 if all(all(getattr(p, k) == getattr(d, k) for k in COMPARED) for p in partners): same_desc += 1 else: for p in partners: diff = [k for k in COMPARED if getattr(p, k) != getattr(d, k)] if diff: print(f" differs: {member} vs {p.member}: {diff}") print( f"{len(lnx)} .lnx images; same SHA-1 as a local .lyx: {same_sha}; " f"same description as every such .lyx: {same_desc}" ) print("\n## 3. Census over distinct headerless payloads (block size provenance)") distinct = {} for x in carts: if x[3].kind == "raw": distinct.setdefault(x[3].sha1, x[3]) for sha1 in {b[2] for b in bootroms}: # the census counted the BIOS among the 421 distinct.setdefault(sha1, None) counts = collections.Counter() for d in distinct.values(): if d is None: counts["neither"] += 1 elif d.provenance["bank0_block"].startswith("table:"): counts["table"] += 1 elif d.provenance["bank0_block"] == "size-rule": counts["size-rule"] += 1 else: counts["neither"] += 1 print( f"distinct headerless payloads: {len(distinct)} (the boot ROM included, as the census " f"did); fully tabled {counts['table']}, size rule only {counts['size-rule']}, " f"neither {counts['neither']}" ) for d in distinct.values(): if d is not None and d.provenance["bank0_block"] == "default": print(f" neither: {d.member} ({len(d.payload)} bytes, default block {d.bank0_block})") print("\n## 4. Conflicts the table records, and warnings on load") seen = set() for _, _, member, d, _ in carts: for c in d.conflicts: key = (d.sha1, c["field"]) if key not in seen: seen.add(key) print(f" {d.name}: {c}") for _, _, member, d, _ in lnx: for w in d.warnings: print(f" warning, {member}: {w}") if d.bank0_alternatives: print( f" {member}: boot tries block {d.bank0_block} " f"({d.provenance['bank0_block']}), then {d.bank0_alternatives}" ) print("\n## 5. Round trip LNX -> LYX -> LNX") agree = identical = 0 for _, _, member, d, data in lnx: entry = default_table().get(d.sha1) claims = { "bank0_block": d.header.bank0_block, "bank1_block": d.header.bank1_block, "audin": bool(d.header.audin & 1), "rotation": d.header.rotation_name, "eeprom": decode_eeprom(d.header.eeprom), } if entry is None or any(claims[k] != v for k, (v, _) in entry.fields.items()): continue # the header disagrees with the table: not part of the exit agree += 1 raw = to_lyx(data) back = describe(raw, member=member.rsplit(".", 1)[0] + ".lyx") try: rebuilt = to_lnx(back) except ConvertError as exc: print(f" refused: {member}: {exc}") continue if rebuilt == data and sniff(rebuilt) == "lnx": identical += 1 else: print(f" differs: {member}") print( f"headers agreeing with the table: {agree}; byte-identical after the round trip: " f"{identical}" ) return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())