#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Fetch mGBA (and Lua) at their pins and build the family's two mGBA tools. python3 -I build.py --machine gba # build/gba/mgba_driver (and mgba-headless) python3 -I build.py --machine arm-disasm # build/arm-disasm/mgba_disasm python3 -I build.py --version # mgba-tools 0.1.0 (mGBA fd9dc5c, Lua 5.4.7) JOBS=2 python3 -I build.py ... # parallel jobs for make and ninja (default 2) Part of the mgba tool in emu-tools-gpl (README.md). The build steps and the two drivers were moved here on 2026-11-25 (decisions page T3) from two MIT emulator repositories, where alewman first wrote them: gba-python's ``scripts/build_referees.py`` and ``scripts/mgba_driver.c`` (``gba``) and arm7tdmi-python's ``scripts/build_referees.py`` and ``referees/mgba/`` (MPL-2.0; ``arm-disasm``); that permission is kept for those parts (``../../notices/MIT-emulator-family.txt``). Each build keeps its consumer's options, so it is the program the consumer built before. - ``gba``: Lua 5.4.7 as a static library (the host has no Lua headers), mGBA's core as ``libmgba.a`` with ``mgba-headless`` (headless, static, Lua scripting, PNG and zlib; no Qt, SDL, OpenGL or FFmpeg), then ``mgba_driver`` (``mgba_driver/mgba_driver.c``, MIT) compiled with the defines mGBA was compiled with and linked against both. - ``arm-disasm``: ``mgba_disasm/mgba_disasm.c`` (MPL-2.0) on its stand-in header ``mgba_disasm/shim/`` with mGBA's ARM and Thumb decoder (``src/arm/decoder*.c``). Sources land in ``upstream/`` (mGBA from GitHub's archive of the commit, Lua's release tarball checked against its SHA-256), builds in ``build//``; both are git-ignored and neither upstream is committed. ``build//build-info.json`` records the pins and the options. Exit status as the family's tool contract says: 0 built (or already built), 2 a usage error, 3 a source could not be fetched or does not match its SHA-256, 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 hashlib 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 = "mgba-tools", "0.1.0" HERE = Path(__file__).resolve().parent UPSTREAM_DIR = HERE / "upstream" BUILD = HERE / "build" EXIT_OK, EXIT_USAGE, EXIT_MISSING = 0, 2, 3 NICE = ["nice", "-n", "10"] MGBA = { "name": "mGBA", "url": "https://github.com/mgba-emu/mgba", "commit": "fd9dc5c2cbf234365068855851107e762fc6211b", # 2026-10-18 "licence": "MPL-2.0", } LUA = { "name": "Lua", "url": "https://www.lua.org/ftp/lua-5.4.7.tar.gz", "sha256": "9fbf5e28ef86c69858f6d3d34eccc32e911c1a28b4120ff3e84aaa70cfbf1e30", "licence": "MIT", } #: mGBA's CMake switches for the gba build, as gba-python's build_referees.py set them. MGBA_OFF = ( "BUILD_QT", "BUILD_SDL", "BUILD_GL", "BUILD_GLES2", "BUILD_GLES3", "USE_FFMPEG", "USE_EDITLINE", "USE_MINIZIP", "USE_LIBZIP", "USE_SQLITE3", "USE_ELF", "USE_JSON_C", "USE_FREETYPE", "USE_LZMA", "USE_DISCORD_RPC", "USE_EPOXY", "ENABLE_GDB_STUB", "BUILD_SHARED", ) # fmt: skip MGBA_ON = ("BUILD_HEADLESS", "BUILD_STATIC", "ENABLE_SCRIPTING", "USE_PNG", "USE_ZLIB") MACHINES = { "gba": {"program": "mgba_driver", "was": "gba-python scripts/build_referees.py"}, "arm-disasm": {"program": "mgba_disasm", "was": "arm7tdmi-python scripts/build_referees.py"}, } def program(machine: str) -> Path: """The built program's documented path.""" return BUILD / machine / MACHINES[machine]["program"] def download(url: str, target: Path) -> None: print(f"downloading {url}", flush=True) try: request = Request(url, headers={"User-Agent": "emu-tools-gpl"}) with urlopen(request, timeout=300) as response, target.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 def unpack(archive: Path, target: Path, stamp: str) -> Path: if (target / ".complete").exists(): return target if target.exists(): raise SystemExit(f"{target} is incomplete (an interrupted fetch?): move it aside first") with tempfile.TemporaryDirectory(dir=UPSTREAM_DIR) as temporary: 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(stamp + "\n") return target def fetch_mgba() -> Path: target = UPSTREAM_DIR / f"mgba-{MGBA['commit'][:12]}" if (target / ".complete").exists(): return target UPSTREAM_DIR.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=UPSTREAM_DIR) as temporary: archive = Path(temporary) / "mgba.tar.gz" download(f"{MGBA['url']}/archive/{MGBA['commit']}.tar.gz", archive) return unpack(archive, target, MGBA["commit"]) def fetch_lua() -> Path: UPSTREAM_DIR.mkdir(parents=True, exist_ok=True) archive = UPSTREAM_DIR / "lua-5.4.7.tar.gz" if not archive.exists(): partial = archive.with_suffix(".partial") download(LUA["url"], partial) partial.rename(archive) digest = hashlib.sha256(archive.read_bytes()).hexdigest() if digest != LUA["sha256"]: print(f"{archive}: SHA-256 {digest} is not the pinned {LUA['sha256']}; move it aside", file=sys.stderr) # fmt: skip raise SystemExit(EXIT_MISSING) return unpack(archive, UPSTREAM_DIR / "lua-5.4.7", LUA["sha256"]) 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_lua(jobs: str) -> Path: prefix = BUILD / "lua" if (prefix / "lib" / "liblua.a").exists(): return prefix source = fetch_lua() run(["make", "-j", jobs, "linux", "MYCFLAGS=-fPIC"], source / "src") run(["make", "install", f"INSTALL_TOP={prefix}"], source) return prefix def build_gba(jobs: str) -> list[str]: lua = build_lua(jobs) mgba = fetch_mgba() out = BUILD / "gba" out.mkdir(parents=True, exist_ok=True) flags = [f"-D{name}=OFF" for name in MGBA_OFF] + [f"-D{name}=ON" for name in MGBA_ON] flags += ["-DCMAKE_BUILD_TYPE=Release", f"-DLUA_INCLUDE_DIR={lua / 'include'}", f"-DLUA_LIBRARY={lua / 'lib' / 'liblua.a'}", "-DUSE_LUA=5.4"] # fmt: skip if not (out / "mgba-headless").exists(): run(["cmake", "-G", "Ninja", str(mgba), *flags], out) run(["ninja", "-j", jobs, "mgba-headless"], out) # The struct layouts depend on the defines mGBA compiled with (ENABLE_SCRIPTING, ...). ninja = (out / "build.ninja").read_text(encoding="utf-8") block = ninja.split("src/core/core.c.o:", 1)[1] defines = block.split("DEFINES = ", 1)[1].split("\n", 1)[0].split() run(["cc", "-O2", "-flto=auto", *defines, "-o", str(out / "mgba_driver"), str(HERE / "mgba_driver" / "mgba_driver.c"), "-I", str(mgba / "include"), "-I", str(out / "include"), str(out / "libmgba.a"), str(lua / "lib" / "liblua.a"), "-lpng", "-lz", "-lm", "-lpthread", "-ldl"], out) # fmt: skip return flags def build_disasm() -> list[str]: mgba = fetch_mgba() out = BUILD / "arm-disasm" out.mkdir(parents=True, exist_ok=True) tool = HERE / "mgba_disasm" options = ["-O1", "-std=gnu11", "-DENABLE_DEBUGGERS", "-DHAVE_STRLCPY"] # HAVE_STRLCPY: glibc 2.38+ has strlcpy; mgba-util's own drags in its text codecs. run(["gcc", *options, f"-I{tool / 'shim'}", f"-I{mgba / 'include'}", f"-I{mgba / 'src'}", str(tool / "mgba_disasm.c"), *(str(mgba / "src" / "arm" / n) for n in ("decoder.c", "decoder-arm.c", "decoder-thumb.c")), "-o", str(out / "mgba_disasm")], out) # fmt: skip return options def build(machine: str) -> Path: out = program(machine) if out.exists(): print(f"already built: {out}") return out jobs = os.environ.get("JOBS", "2") options = build_gba(jobs) if machine == "gba" else build_disasm() upstream = [MGBA, LUA] if machine == "gba" else [MGBA] info = { "tool": TOOL, "tool_version": VERSION, "machine": machine, "upstream": upstream, "options": options, "was": MACHINES[machine]["was"], "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } (out.parent / "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: print(f"{TOOL} {VERSION} (mGBA {MGBA['commit'][:7]}, Lua 5.4.7)") 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:]))