#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Fetch NanoBoyAdvance at its pinned commits and build the family's two drivers for it. python3 -I build.py --machine arm7tdmi-sst # build/arm7tdmi-sst/nba_sst (NBA e8482c1) python3 -I build.py --machine gba # build/gba/nba_driver (NBA 8c3b159, v1.8.3) python3 -I build.py --version # nanoboyadvance-drivers 0.1.0 (...) JOBS=2 python3 -I build.py ... # parallel jobs for ninja (default 2) Part of the nanoboyadvance tool in emu-tools-gpl (README.md; GPL-3.0-or-later). The build steps were moved here on 2026-11-25 (decisions page T3) from two MIT emulator repositories, where alewman first wrote them: arm7tdmi-python's ``scripts/build_referees.py`` (``nba_sst``) and gba-python's ``scripts/build_referees.py --nba`` (``nba_driver``); that permission is kept for those parts (``../../notices/MIT-emulator-family.txt``). Each build keeps its consumer's compiler options and pin, so it is the program the consumer built before. - ``arm7tdmi-sst``: ``nba_sst/nba_sst.cc`` on the stand-in headers ``nba_sst/shim/`` against NBA's ARM core at ``e8482c1`` (one ``g++ -std=c++20 -O2`` compile), which runs SingleStepTests ARM7TDMI cases one at a time and reports state and bus agreement. - ``gba``: ``nba_driver/`` (CMake and Ninja, Release) against NBA's core library at ``8c3b159`` (v1.8.3): a headless driver that runs a ROM for a number of frames with a BIOS and writes the picture, registers and save memory. The source lands in ``upstream/NanoBoyAdvance-/`` (Codeberg's archive of the commit), the builds in ``build//``; both are git-ignored and NBA is never committed. ``build//build-info.json`` records the pin and the options. Exit status as the family's tool contract says: 0 built (or already built), 2 a usage error, 3 the source could not be fetched, anything else a failed build. Nothing is ever deleted: a half-fetched tree stops the script until it is moved aside. """ from __future__ import annotations import argparse import json import os import shutil import subprocess import sys import tarfile import tempfile import time from pathlib import Path from urllib.request import Request, urlopen TOOL, VERSION = "nanoboyadvance-drivers", "0.1.0" HERE = Path(__file__).resolve().parent UPSTREAM_DIR = HERE / "upstream" BUILD = HERE / "build" REPOSITORY = "https://codeberg.org/nba-emu/NanoBoyAdvance" EXIT_OK, EXIT_USAGE, EXIT_MISSING = 0, 2, 3 NICE = ["nice", "-n", "10"] MACHINES = { "arm7tdmi-sst": { "pin": "e8482c1efc6cde3f553e8170a51abea71cee426e", # 2026-07-26, master "program": "nba_sst", "was": "arm7tdmi-python scripts/build_referees.py", }, "gba": { "pin": "8c3b159c649b027ea8fc87df3290bad4cdcdcf4b", # 2026-10-19, v1.8.3 "program": "nba_driver", "was": "gba-python scripts/build_referees.py --nba", }, } def program(machine: str) -> Path: """The built program's documented path.""" return BUILD / machine / MACHINES[machine]["program"] def fetch(pin: str) -> Path: """NanoBoyAdvance at ``pin``, from Codeberg's archive of the commit.""" target = UPSTREAM_DIR / f"NanoBoyAdvance-{pin[:12]}" if (target / ".complete").exists(): return target if target.exists(): raise SystemExit(f"{target} is incomplete (an interrupted fetch?): move it aside first") UPSTREAM_DIR.mkdir(parents=True, exist_ok=True) url = f"{REPOSITORY}/archive/{pin}.tar.gz" print(f"downloading {url}", flush=True) with tempfile.TemporaryDirectory(dir=UPSTREAM_DIR) as temporary: archive = Path(temporary) / "source.tar.gz" try: request = Request(url, headers={"User-Agent": "emu-tools-gpl"}) with urlopen(request, timeout=300) as response, archive.open("wb") as out: shutil.copyfileobj(response, out, 1 << 20) except OSError as error: print(f"could not fetch {url}: {error}", file=sys.stderr) raise SystemExit(EXIT_MISSING) from error with tarfile.open(archive, "r:gz") as bundle: bundle.extractall(temporary, filter="data") (root,) = [p for p in Path(temporary).iterdir() if p.is_dir()] root.rename(target) (target / ".complete").write_text(pin + "\n") return target def run(command: list[str], cwd: Path) -> None: print("+", " ".join(command), flush=True) if subprocess.run(NICE + command, cwd=cwd).returncode: raise SystemExit(1) def build(machine: str) -> Path: spec = MACHINES[machine] out = program(machine) if out.exists(): print(f"already built: {out}") return out source = fetch(spec["pin"]) folder = BUILD / machine folder.mkdir(parents=True, exist_ok=True) jobs = os.environ.get("JOBS", "2") if machine == "arm7tdmi-sst": nba = source / "src" / "nba" driver = HERE / "nba_sst" options = ["-std=c++20", "-O2", f"-I{driver / 'shim'}", f"-I{nba / 'src'}", f"-I{nba / 'include'}"] # fmt: skip run(["g++", *options, str(driver / "nba_sst.cc"), "-o", str(out)], folder) else: options = ["-G", "Ninja", "-DCMAKE_BUILD_TYPE=Release"] run(["cmake", options[0], options[1], str(HERE / "nba_driver"), f"-DNBA_ROOT={source}", options[2]], folder) # fmt: skip run(["ninja", "-j", jobs, "nba_driver"], folder) info = { "tool": TOOL, "tool_version": VERSION, "machine": machine, "upstream": {"name": "NanoBoyAdvance", "url": REPOSITORY, "commit": spec["pin"]}, "options": options, "was": spec["was"], "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } (folder / "build-info.json").write_text(json.dumps(info, indent=1) + "\n") print(f"built {out}") return out def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--machine", choices=sorted(MACHINES)) parser.add_argument("--version", action="store_true") try: args = parser.parse_args(argv) except SystemExit as error: return EXIT_USAGE if error.code else EXIT_OK if args.version: pins = ", ".join(f"{m} {s['pin'][:7]}" for m, s in MACHINES.items()) print(f"{TOOL} {VERSION} (NanoBoyAdvance: {pins})") return EXIT_OK if not args.machine: parser.print_usage(sys.stderr) return EXIT_USAGE build(args.machine) return EXIT_OK if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))