"""Download checksum-verified external tools and build without sudo.""" import argparse import hashlib import json import os from pathlib import Path import platform import shutil import subprocess import tarfile try: import fcntl except ImportError: # Windows: no flock; main() refuses with a clear message instead of an import crash fcntl = None from environment import DEPENDENCIES, dependency_dir, tools_dir def source_manifest(archive, name): """Derive the source inventory from the checksum-verified archive, not disk.""" files = {} with tarfile.open(archive) as tar: for member in tar: if member.isfile(): path = Path(member.name) if path.is_absolute() or ".." in path.parts: raise ValueError(f"unsafe archive path: {member.name}") relative = (path if name == "actionlint" else Path(*path.parts[1:])).as_posix() files[relative] = {"bytes": member.size, "sha256": hashlib.sha256(tar.extractfile(member).read()).hexdigest(), "executable": bool(member.mode & 0o111)} return {"schema": 1, "archive_sha256": DEPENDENCIES[name]["sha256"], "files": files} def generated_file(name, path): """Only known output locations/suffixes are excluded from source inventory.""" parts = Path(path).parts if name == "cc65": return (parts[0] == "wrk" and Path(path).suffix in (".o", ".d", ".a")) or path in ( "bin/ca65", "bin/ld65", "bin/da65", "bin/cc65") if name == "geargrafx": return ((parts[0] in ("src", "platforms") and Path(path).suffix in (".o", ".d")) or path in ("platforms/libretro/geargrafx_libretro.so", "platforms/linux/geargrafx")) return False def verify_sources(destination, name, manifest): metadata = {".verified-archive-sha256", ".source-integrity.json", ".source-integrity.json.tmp"} for path in destination.rglob("*"): relative = path.relative_to(destination).as_posix() # manifest keys are POSIX paths on every host if path.is_symlink(): raise ValueError(f"unexpected cache symlink: {path}") if (path.is_file() and relative not in manifest["files"] and relative not in metadata and not generated_file(name, relative)): raise ValueError(f"unexpected source cache file: {path}") for relative, record in manifest["files"].items(): path = destination / relative if (not path.is_file() or path.stat().st_size != record["bytes"] or bool(path.stat().st_mode & 0o111) != record["executable"] or hashlib.sha256(path.read_bytes()).hexdigest() != record["sha256"]): raise ValueError(f"source cache integrity mismatch: {path}; inspect/remove this dependency cache") def save_manifest(destination, manifest): temporary = destination / ".source-integrity.json.tmp" temporary.write_text(json.dumps(manifest, sort_keys=True) + "\n") temporary.replace(destination / ".source-integrity.json") def fetch(name, desktop=False, debugger=False): dep = DEPENDENCIES[name] cache = tools_dir() archive = cache / f"{name}-{dep['revision']}.tar.gz" if not archive.exists(): temporary = archive.with_suffix(".download") subprocess.run(["curl", "--fail", "--location", "--retry", "3", "--connect-timeout", "15", "--max-time", "180", dep["url"], "--output", str(temporary)], check=True) temporary.replace(archive) if hashlib.sha256(archive.read_bytes()).hexdigest() != dep["sha256"]: raise ValueError(f"checksum mismatch: {archive}; remove the corrupt archive and retry") manifest = source_manifest(archive, name) destination = dependency_dir(name) if desktop: destination = destination.with_name(destination.name + "-desktop") if debugger: destination = destination.with_name(destination.name + "-debugger") stamp = destination / ".verified-archive-sha256" if destination.exists(): if not stamp.is_file() or stamp.read_text().strip() != dep["sha256"]: raise ValueError(f"unverified existing source directory: {destination}") inventory = destination / ".source-integrity.json" if inventory.exists(): try: saved = json.loads(inventory.read_text()) except (ValueError, OSError) as error: raise ValueError(f"corrupt source integrity manifest: {inventory}") from error if saved != manifest: raise ValueError(f"source integrity manifest differs from verified archive: {inventory}") verify_sources(destination, name, manifest) if not inventory.exists(): # Upgrade an old cache only after every original file was verified. save_manifest(destination, manifest) return destination staging = destination.with_name(destination.name + ".extracting") if staging.exists(): # This is exclusively our staging area; final source directories are preserved. shutil.rmtree(staging) staging.mkdir() with tarfile.open(archive) as tar: # Python 3.10-compatible validation. Upstream agent metadata has symlinks; # omit links entirely (none are used by the pinned build targets). members = [] for member in tar.getmembers(): if member.issym() or member.islnk(): continue parts = Path(member.name).parts if Path(member.name).is_absolute() or ".." in parts: raise ValueError(f"unsafe archive path: {member.name}") if not member.isdir() and not member.isfile(): raise ValueError(f"unsupported archive member: {member.name}") members.append(member) tar.extractall(staging, members=members) extracted = staging if name != "actionlint": entries = list(staging.iterdir()) if len(entries) != 1 or not entries[0].is_dir(): raise ValueError("source archive must have exactly one root") extracted = entries[0] verify_sources(extracted, name, manifest) save_manifest(extracted, manifest) (extracted / ".verified-archive-sha256").write_text(dep["sha256"] + "\n") extracted.rename(destination) # Publish only a complete, verified source tree. if name != "actionlint": staging.rmdir() return destination def debugger_overrides(platform_dir): """Make variable overrides for the instruction-debugger build (single source for build and probe flags).""" includes = subprocess.run(["make", "-s", "--no-print-directory", "-C", str(platform_dir), "--eval", "print-includes:;@echo $(INCLUDES)", "print-includes"], capture_output=True, text=True, check=True).stdout.strip() # Overrides replace the Makefile's own CFLAGS/CXXFLAGS, so -DGG_DISABLE_DISASSEMBLER is deliberately absent. flags = ("-O2 -fPIC -fno-exceptions -D__LIBRETRO__ -DZ7_ST -DZSTD_DISABLE_ASM " "-DGG_DISABLE_VGMRECORDER -DGG_ENABLE_CDROM_CUEBIN_READAHEAD -pthread " + includes) return ["CFLAGS=" + flags, "CXXFLAGS=" + flags + " -fno-rtti"] def build_geargrafx(source, jobs, debugger=False, desktop=False): platform_dir = source / ("platforms/linux" if desktop else "platforms/libretro") command = ["make", "-C", str(platform_dir), f"-j{jobs}", f"GIT_VERSION={DEPENDENCIES['geargrafx']['revision']}"] if debugger: # Upstream's libretro default disables its debugger even with DEBUG=1. # Override supported compiler variables, leaving every source byte intact. command += debugger_overrides(platform_dir) subprocess.run(command, check=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("target", choices=["all", "cc65", "geargrafx", "actionlint"]) parser.add_argument("--desktop", action="store_true") parser.add_argument("--debugger", action="store_true") args = parser.parse_args() if platform.system() != "Linux" or platform.machine() != "x86_64": raise ValueError("supported bootstrap host: Linux x86_64") required = ["curl", "make", "gcc", "g++", "ar"] missing = [name for name in required if not shutil.which(name)] if missing: raise ValueError(f"missing host tools: {', '.join(missing)}; see docs/building.md") if args.debugger and (args.target != "geargrafx" or args.desktop): raise ValueError("--debugger requires geargrafx without --desktop") if args.desktop: if args.target != "geargrafx": raise ValueError("--desktop is only valid with geargrafx") if not shutil.which("pkg-config") or subprocess.run( ["pkg-config", "--exists", "sdl3"]).returncode: raise ValueError("desktop/MCP requires SDL3 development files; see docs/emulator-geargrafx.md") jobs = int(os.environ.get("JOBS", "2")) if not 1 <= jobs <= 64: raise ValueError("JOBS must be between 1 and 64") cache = tools_dir() if fcntl is None: raise ValueError("setup needs POSIX file locks (fcntl); run it on Linux or WSL, see docs/building.md") cache.mkdir(parents=True, exist_ok=True) with (cache / ".setup.lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) names = ["cc65", "geargrafx", "actionlint"] if args.target == "all" else [args.target] for name in names: source = fetch(name, args.desktop, args.debugger) if name == "cc65": subprocess.run(["make", "-C", str(source), f"-j{jobs}", f"BUILD_ID=Git {DEPENDENCIES[name]['revision'][:9]}", "ca65", "ld65", "da65", "cc65"], check=True) elif name == "geargrafx": build_geargrafx(source, jobs, args.debugger, args.desktop) else: (source / "actionlint").chmod(0o755) print(f"READY {name}: {DEPENDENCIES[name]['revision']}", flush=True) if args.target == "all": source = fetch("geargrafx", debugger=True) build_geargrafx(source, jobs, debugger=True) print(f"READY geargrafx instruction debugger: {DEPENDENCIES['geargrafx']['revision']}", flush=True) if __name__ == "__main__": try: main() except (ValueError, OSError, subprocess.CalledProcessError) as error: raise SystemExit(f"setup: {error}") from error