#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census the No-Intro Nintendo DS and DSi sets by their cartridge headers. Reads, from each .zip under the named No-Intro folders, the first 16 KB + 8 bytes of the one ROM image inside (``.nds``, ``.srl``, ``.dsi`` or ``.bin``): the header (GBATEK "DS Cartridge Header") and the 8 bytes at 4000h, the Secure Area ID ("DS Cartridge Secure Area"). Nothing is extracted to disk, copied or kept; only counts are printed. python -I scripts/census_cartridges.py "Nintendo - Nintendo DS (Decrypted)" ... Folders are taken relative to $NO_INTRO_DIR. The output is the census table that docs/census.md quotes (kept under tests/detectors/ with its date). """ from __future__ import annotations import collections import os import struct import sys import zipfile from pathlib import Path EXTENSIONS = (".nds", ".srl", ".dsi", ".ids") def rom_members(infos: list[zipfile.ZipInfo]) -> list[zipfile.ZipInfo]: """The ROM images in a zip, by kind: cartridge images (``.nds``, ``.srl``, ``.dsi``, and ``.ids`` for the iQue DS set); else a DSiWare CDN title's content files (named by eight hex digits, beside ``tmd.N``), the largest first. Download Play zips also hold a ``.bin`` and a ``.bcn`` (the beacon) beside the ``.nds``: only the ``.nds`` is read.""" images = sorted((m for m in infos if m.filename.lower().endswith(EXTENSIONS)), key=lambda m: m.filename) if images: return images contents = [m for m in infos if len(m.filename) == 8 and all(c in "0123456789abcdefABCDEF" for c in m.filename)] return sorted(contents, key=lambda m: -m.file_size)[:1] def crc16(data: bytes) -> int: """CRC-16 as the DS BIOS computes it (GBATEK "BIOS Misc Functions": GetCRC16, initial FFFFh, reflected polynomial A001h).""" crc = 0xFFFF for byte in data: crc ^= byte for _ in range(8): crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1 return crc def secure_area_state(header: bytes, at_4000: bytes) -> str: arm9_offset = struct.unpack_from(" None: unit = header[0x12] counts["unitcode"][{0: "00h NDS", 2: "02h NDS+DSi", 3: "03h DSi"}.get(unit, f"{unit:02X}h")] += 1 counts["capacity"][f"{128 << header[0x14]} KB" if header[0x14] < 16 else f"code {header[0x14]}"] += 1 gamecode = header[0x0C:0x10] first = chr(gamecode[0]) if 0x20 < gamecode[0] < 0x7F else "(none)" counts["gamecode letter"][first] += 1 counts["seed select"][f"{header[0x13]:02X}h"] += 1 counts["region byte"][f"{header[0x1D]:02X}h"] += 1 counts["secure area"][secure_area_state(header, at_4000)] += 1 logo = struct.unpack_from("= 0x37F8000 else "main RAM"] += 1 counts["ROMCTRL normal (060h)"][f"{struct.unpack_from('= used" if size >= used else "file < used"] += 1 for limit in (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024): if size <= limit << 20: counts["file size (<=)"][f"{limit} MB"] += 1 break else: counts["file size (<=)"]["> 1 GB"] += 1 def main() -> int: root = os.environ.get("NO_INTRO_DIR") if not root: print("set NO_INTRO_DIR", file=sys.stderr) return 2 for folder in sys.argv[1:]: counts: dict[str, collections.Counter] = collections.defaultdict(collections.Counter) zips = sorted((Path(root) / folder).glob("*.zip")) problems = [] bios = 0 for path in zips: if path.name.startswith("[BIOS]"): bios += 1 continue try: with zipfile.ZipFile(path) as archive: members = rom_members(archive.infolist()) if not members: names = ", ".join(m.filename.rsplit(".", 1)[-1] for m in archive.infolist()) counts["not read (member kinds)"][names] += 1 continue if len(members) > 1: counts["zips holding several images"]["several (first by name read)"] += 1 with archive.open(members[0]) as handle: head = handle.read(0x4008) size = members[0].file_size except (OSError, zipfile.BadZipFile) as error: problems.append(f"{path.name}: {error}") continue if len(head) < 0x200: problems.append(f"{path.name}: shorter than a header") continue classify(head[:0x200], head[0x4000:0x4008], size, counts) print(f"## {folder}") print(f"zips {len(zips)}, [BIOS] entries {bios}, headers read {sum(counts['unitcode'].values())}, " f"problems {len(problems)}") for name, counter in counts.items(): if not sum(counter.values()): continue print(f"- {name}: " + ", ".join(f"{k} {v}" for k, v in counter.most_common(12))) for problem in problems[:20]: print(f" problem: {problem}") print() return 0 if __name__ == "__main__": sys.exit(main())