# SPDX-License-Identifier: MIT """The file formats a Lynx cart or program arrives in, read from the bytes, never the extension. docs/cartridge.md, "Formats". Three kinds, each loose or inside a ``.zip`` or ``.7z``: - ``lnx``: bytes 0-3 are ``LYNX``; a 64-byte header (Handy's layout, K. Wilkins, zlib licence, ``libretro-handy/lynx/cart.h``; bytes 59 and 60 a later community extension, cc65 ``exehdr.s``) followed by the payload. - ``bll``: bytes 0-1 are ``$80 $08`` and bytes 6-9 ``BS93``: a RAM image with a big-endian load address (2-3) and a length that includes the 10-byte header (4-5) (42Bastian's BLL; MAME calls it "Quickload"). - ``raw`` (``.lyx``): none of the others; the payload alone, which is what No-Intro hashes. Every function here is pure: bytes in, values out. Unwrapping a ``.7z`` runs the system ``7z`` program (``7z e -so``) and reads its output in memory; nothing is extracted to disk. """ from __future__ import annotations import io import shutil import subprocess import zipfile from dataclasses import dataclass from pathlib import Path LNX_MAGIC = b"LYNX" LNX_HEADER_SIZE = 64 BLL_HEADER_SIZE = 10 ROTATIONS = ("none", "left", "right") # header byte 58: 0, 1, 2 EEPROM_TYPES = ("none", "93C46", "93C56", "93C66", "93C76", "93C86") # header byte 60, bits 0-2 # Member names inside an archive that are never the cart (text that ships with dumps). _NOT_CARTS = (".txt", ".nfo", ".diz", ".xml", ".jpg", ".png", ".pdf", ".md") class FormatError(ValueError): """The bytes are not a Lynx cart, program or archive holding one.""" @dataclass(frozen=True) class LnxHeader: """The 64-byte LNX header as written, before any judgement of its claims.""" bank0_block: int bank1_block: int version: int name: str maker: str rotation: int # raw byte 58 audin: int # raw byte 59 eeprom: int # raw byte 60 spare: bytes # bytes 61-63 @property def rotation_name(self) -> str | None: """'none', 'left' or 'right'; None when the byte holds anything else.""" return ROTATIONS[self.rotation] if self.rotation < len(ROTATIONS) else None def to_bytes(self) -> bytes: """The header bytes; the inverse of :func:`parse_lnx_header`.""" name = self.name.encode("latin-1")[:32].ljust(32, b"\0") maker = self.maker.encode("latin-1")[:16].ljust(16, b"\0") return ( LNX_MAGIC + self.bank0_block.to_bytes(2, "little") + self.bank1_block.to_bytes(2, "little") + self.version.to_bytes(2, "little") + name + maker + bytes((self.rotation, self.audin, self.eeprom)) + self.spare[:3].ljust(3, b"\0") ) @dataclass(frozen=True) class BllHeader: """The 10-byte BLL (``BS93``) header.""" load: int length: int # includes the 10 header bytes def decode_eeprom(byte: int) -> tuple[str, int] | None: """Header byte 60 as (type, organisation in bits), or None for no EEPROM. Bits 0-2 select 93C46..93C86 (1..5); bit 6 set means the 8-bit organisation, clear the 16-bit one; bit 7 asks for the save on an SD card (a flash-cart matter, ignored here). cc65's header source computes the size with a "please recheck" note (C13). A type of 6 or 7 is not defined: None. """ kind = byte & 7 if kind == 0 or kind >= len(EEPROM_TYPES): return None return EEPROM_TYPES[kind], 8 if byte & 0x40 else 16 def encode_eeprom(eeprom: tuple[str, int] | None) -> int: """The inverse of :func:`decode_eeprom` (the SD-card bit is never set).""" if eeprom is None: return 0 kind, organisation = eeprom return EEPROM_TYPES.index(kind) | (0x40 if organisation == 8 else 0) def sniff(data: bytes) -> str: """'lnx', 'bll' or 'raw', from the content alone.""" if data[:4] == LNX_MAGIC and len(data) >= LNX_HEADER_SIZE: return "lnx" if len(data) >= BLL_HEADER_SIZE and data[:2] == b"\x80\x08" and data[6:10] == b"BS93": return "bll" return "raw" def parse_lnx_header(data: bytes) -> LnxHeader: """Read the claims of an LNX header; raises FormatError if there is none.""" if sniff(data) != "lnx": raise FormatError("no LYNX header") def text(raw: bytes) -> str: return raw.split(b"\0")[0].decode("latin-1") return LnxHeader( bank0_block=int.from_bytes(data[4:6], "little"), bank1_block=int.from_bytes(data[6:8], "little"), version=int.from_bytes(data[8:10], "little"), name=text(data[10:42]), maker=text(data[42:58]), rotation=data[58], audin=data[59], eeprom=data[60], spare=bytes(data[61:64]), ) def parse_bll_header(data: bytes) -> BllHeader: if sniff(data) != "bll": raise FormatError("no BS93 header") return BllHeader(load=int.from_bytes(data[2:4], "big"), length=int.from_bytes(data[4:6], "big")) def split(data: bytes) -> tuple[str, LnxHeader | BllHeader | None, bytes]: """(kind, header claims, payload). A BLL image is its own payload, header included.""" kind = sniff(data) if kind == "lnx": return kind, parse_lnx_header(data), bytes(data[LNX_HEADER_SIZE:]) if kind == "bll": return kind, parse_bll_header(data), bytes(data) return kind, None, bytes(data) # -- containers -------------------------------------------------------------- def _container(data: bytes) -> str | None: if data[:4] == b"PK\x03\x04" or data[:4] == b"PK\x05\x06": return "zip" if data[:6] == b"7z\xbc\xaf\x27\x1c": return "7z" return None def _pick(members: list[tuple[str, bytes]], origin: str) -> tuple[str, bytes]: """The one cart member: text and pictures ignored; a LYNX/BS93 member preferred.""" carts = [(n, d) for n, d in members if not n.lower().endswith(_NOT_CARTS) and d] if not carts: raise FormatError(f"{origin}: no cart inside the archive") sniffed = [(n, d) for n, d in carts if sniff(d) != "raw"] if len(carts) > 1 and len(sniffed) == 1: return sniffed[0] if len(carts) > 1: raise FormatError( f"{origin}: {len(carts)} possible carts inside the archive: " + ", ".join(n for n, _ in carts) ) return carts[0] def _zip_members(data: bytes) -> list[tuple[str, bytes]]: with zipfile.ZipFile(io.BytesIO(data)) as archive: return [(i.filename, archive.read(i)) for i in archive.infolist() if not i.is_dir()] def _sevenzip_members(path: Path) -> list[tuple[str, bytes]]: tool = shutil.which("7z") or shutil.which("7za") or shutil.which("7zr") if tool is None: raise FormatError(f"{path}: reading .7z needs the 7z program on PATH") listing = subprocess.run( [tool, "l", "-ba", "-slt", str(path)], capture_output=True, text=True, check=True ).stdout names, is_dir = [], {} current = None for line in listing.splitlines(): if line.startswith("Path = "): current = line[7:] names.append(current) elif line.startswith("Attributes = ") and current is not None: is_dir[current] = line[13:].startswith("D") out = [] for name in names: if is_dir.get(name): continue data = subprocess.run( [tool, "e", "-so", str(path), name], capture_output=True, check=True ).stdout out.append((name, data)) return out def unwrap(source: str | Path | bytes, name: str | None = None) -> tuple[str, bytes, str]: """Return (member name, bytes, container) for a path or bytes; container is 'zip', '7z' or 'loose'. Archives are read in memory, in place.""" path = None if isinstance(source, bytes | bytearray | memoryview): data = bytes(source) origin = name or "" else: path = Path(source) data = path.read_bytes() origin = str(path) name = name or path.name kind = _container(data) if kind == "zip": member, inner = _pick(_zip_members(data), origin) return member, inner, "zip" if kind == "7z": if path is None: raise FormatError("a .7z must be given as a path (it is read with the 7z program)") member, inner = _pick(_sevenzip_members(path), origin) return member, inner, "7z" return name or "", data, "loose"