# SPDX-License-Identifier: MIT """The boot ROM: bring your own, found by hash; no replacement ROM is shipped. docs/cartridge.md, "The boot path", and C16. The 512-byte ROM inside Mikey answers ``$FE00-$FFFF`` (bit 2 of MAPCTL replaces ``$FE00-$FFF7`` with RAM, bit 3 the vectors ``$FFFA-$FFFF``; ``$FFF8`` is RAM and ``$FFF9`` is MAPCTL itself). Two images circulate, differing only in the byte at ``$FFF9``, which a running machine cannot read back as ROM: MAME's ``lynxa.bin`` (everyone else's ``lynxboot.img``) and MAME's ``lynx.bin``. Both behave identically; the first is the reference. """ from __future__ import annotations import hashlib import os import zipfile from pathlib import Path from lynx_python import romsets REFERENCE_SHA1 = "e4ed47fae31693e016b081c6bda48da5b70d7ccb" # lynxboot.img, MAME lynxa.bin MAME_LYNX_BIN_SHA1 = "de60f2263851bbe10e5801ef8f6c357a4bc077e6" # MAME lynx.bin: byte $FFF9 differs BOOT_ROM_SHA1S = frozenset({REFERENCE_SHA1, MAME_LYNX_BIN_SHA1}) BOOT_ROM_SIZE = 512 # The user's own copy, then MAME's lynx.zip under $MAME_ROMPATH (by hash); read in place. SEARCH_PATHS = ("~/.local/share/lynx-python/lynxboot.img",) class BootRomError(ValueError): pass def check(data: bytes) -> bytes: """Return the image if it is a known Lynx boot ROM, else raise.""" if len(data) != BOOT_ROM_SIZE: raise BootRomError(f"a Lynx boot ROM is {BOOT_ROM_SIZE} bytes, not {len(data)}") digest = hashlib.sha1(data).hexdigest() if digest not in BOOT_ROM_SHA1S: raise BootRomError(f"unknown boot ROM (SHA-1 {digest})") return bytes(data) def find(path: str | os.PathLike[str] | None = None) -> bytes | None: """The boot ROM from ``path``, ``$LYNX_BOOT_ROM``, the search paths or ``$MAME_ROMPATH/lynx.zip`` (the reference image preferred); None if absent.""" candidates = [path] if path else [] if os.environ.get("LYNX_BOOT_ROM"): candidates.append(os.environ["LYNX_BOOT_ROM"]) candidates.extend(SEARCH_PATHS) for candidate in candidates: p = Path(os.path.expanduser(str(candidate))) if p.is_file(): return check(p.read_bytes()) for directory in romsets.mame_rompaths(): archive = directory / "lynx.zip" if not archive.is_file(): continue with zipfile.ZipFile(archive) as z: found = {} for name in z.namelist(): data = z.read(name) if len(data) == BOOT_ROM_SIZE: found[hashlib.sha1(data).hexdigest()] = data for digest in (REFERENCE_SHA1, MAME_LYNX_BIN_SHA1): if digest in found: return found[digest] return None