#!/usr/bin/env python3 """Target-bound source/review/firmware packager with fail-closed release pins.""" from __future__ import annotations import argparse import hashlib import json import os import shutil import subprocess import sys import tempfile import zipfile from datetime import datetime, timezone from pathlib import Path _ROOT = Path(__file__).resolve().parents[1] if str(_ROOT) not in sys.path: sys.path.insert(0, str(_ROOT)) from tools.generate_target import generate_named_target from tools.target_registry import ROOT, load_source_closure, release_blocked, resolve_target def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _git(repo: Path, *args: str) -> str: try: return subprocess.check_output(["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL).strip() except (OSError, subprocess.CalledProcessError): return os.environ.get("PROD2U_COMMIT", "unknown") def _add(zipf: zipfile.ZipFile, src: Path, dest: str, sums: dict[str, str]) -> None: zipf.write(src, dest) sums[dest] = _sha256(src) def _6400_bitstream() -> Path: configured = os.environ.get("PROD2U_6400_BITSTREAM", "").strip() candidates = [Path(configured)] if configured else [] candidates.extend( ( ROOT / "dist" / "6400-bitstream" / "prod2u_6400_front_back.bit", ROOT / "evidence" / "bitstream" / "prod2u_6400_front_back.bit", ) ) for candidate in candidates: if candidate.is_file() and candidate.stat().st_size > 0: return candidate.resolve() raise SystemExit("firmware package blocked: 6400 production bitstream is missing") def build_target_package( target_name: str, kind: str, output_dir: Path, include_reference: bool = False, ) -> Path: target = resolve_target(target_name) generate_named_target(target.alias) project = json.loads(target.project_config.read_text(encoding="utf-8")) blocked, pins = release_blocked(target, project) if kind == "firmware" and blocked: raise SystemExit( "release_blocked\n" + "\n".join(f"{name} pin unresolved" for name in pins) ) bitstream_path = _6400_bitstream() if kind == "firmware" and target.alias == "6400" else None td_evidence = ROOT / "dist" / "6400-td" if target.alias == "6400" and kind == "firmware" else None commit = _git(ROOT, "rev-parse", "HEAD") run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") name = f"prod2u-{target.alias}-{kind}-{commit[:12]}-{run_id}" output_dir.mkdir(parents=True, exist_ok=True) zip_path = output_dir / f"{name}.zip" sources = load_source_closure(target) manifest = { "schema": "prod2u-target-package-v1", "target_alias": target.alias, "project_id": target.project_id, "top": target.top_module, "kind": kind, "commit": commit, "run_id": run_id, "project_config_sha256": hashlib.sha256(target.project_config.read_bytes()).hexdigest(), "source_manifest_sha256": hashlib.sha256(target.generated_dir.joinpath("td-source-manifest.json").read_bytes()).hexdigest() if (target.generated_dir / "td-source-manifest.json").is_file() else None, "bitstream_sha256": _sha256(bitstream_path) if bitstream_path else None, "hardware_validation": "NOT RUN", "release_blocked": blocked, "unresolved_pins": list(pins), "include_reference": include_reference, } with tempfile.TemporaryDirectory() as tmp: stage = Path(tmp) (stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") shutil.copy2(target.project_config, stage / "project.json") shutil.copy2(target.source_closure, stage / "source-closure.json") gen_dir = stage / "generated" if target.generated_dir.is_dir(): shutil.copytree(target.generated_dir, gen_dir) src_dir = stage / "src" src_dir.mkdir() for rel in sources: dest = stage / rel dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(ROOT / rel, dest) if bitstream_path is not None: shutil.copy2(bitstream_path, stage / "prod2u_6400_front_back.bit") (stage / "BITSTREAM-SHA256.txt").write_text( f"{_sha256(bitstream_path)} prod2u_6400_front_back.bit\n", encoding="ascii", ) (stage / "FLASH-INSTRUCTIONS.zh-CN.txt").write_text( "6400 生产固件刷写说明\n" "========================\n" "目标器件:EF2L45BG256B(6400 前后独立温控)\n" "固件文件:prod2u_6400_front_back.bit\n" "\n" "1. 关闭目标板电源,连接板卡厂商支持的 JTAG 下载器。\n" "2. 在 Anlogic TD 2026.1 SP2 中选择 EF2L45BG256B,打开该 .bit 文件。\n" "3. 先执行 Erase/Program,再执行 Verify;确认校验通过后断电重启。\n" "4. 串口使用 115200 8N1,无硬件流控;上位机选择 6400 HEX GUI。\n" "5. 本包只包含 6400 固件,不能用于 MRDIMM 门控板。\n" "\n" "注意:本次交付未执行真实 JTAG/硬件烧录,硬件验证状态为 NOT RUN。\n", encoding="utf-8", ) if td_evidence is not None and td_evidence.is_dir(): shutil.copytree(td_evidence, stage / "td-evidence", dirs_exist_ok=True) (stage / "TD-BUILD-RECEIPT.json").write_text( json.dumps( { "schema": "prod2u-6400-td-build-receipt-v1", "target_alias": "6400", "project_id": target.project_id, "top_module": target.top_module, "td_version": "TD Release_2026.1_SP2 build 6.2.2.200067", "source_commit": commit, "project_config_sha256": manifest["project_config_sha256"], "source_manifest_sha256": manifest["source_manifest_sha256"], "bitstream": "prod2u_6400_front_back.bit", "bitstream_sha256": manifest["bitstream_sha256"], "stages": ["syn", "phy", "bitgen"], "hardware_validation": "NOT RUN", }, indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) if include_reference: ref = ROOT / "reference" if ref.is_dir(): shutil.copytree(ref, stage / "reference", dirs_exist_ok=True) sums: dict[str, str] = {} if zip_path.exists(): zip_path.unlink() with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zipf: for path in sorted(stage.rglob("*")): if path.is_file(): _add(zipf, path, path.relative_to(stage).as_posix(), sums) zipf.writestr("SHA256SUMS", "".join(f"{digest} {name}\n" for name, digest in sorted(sums.items()))) _selftest(zip_path) return zip_path def _selftest(zip_path: Path) -> None: with tempfile.TemporaryDirectory() as tmp: dest = Path(tmp) / "unpacked" dest.mkdir() with zipfile.ZipFile(zip_path) as zipf: for info in zipf.infolist(): if info.filename.startswith("/") or ".." in Path(info.filename).parts: raise SystemExit(f"unsafe zip path: {info.filename}") zipf.extractall(dest) manifest = json.loads((dest / "manifest.json").read_text(encoding="utf-8")) if manifest.get("hardware_validation") != "NOT RUN": raise SystemExit("package selftest: hardware_validation must be NOT RUN") sums = (dest / "SHA256SUMS").read_text(encoding="utf-8").splitlines() for line in sums: digest, name = line.split(" ", 1) observed = _sha256(dest / name) if observed != digest: raise SystemExit(f"hash mismatch {name}") if manifest.get("target_alias") == "6400" and manifest.get("kind") == "firmware": bit = dest / "prod2u_6400_front_back.bit" if not bit.is_file() or _sha256(bit) != manifest.get("bitstream_sha256"): raise SystemExit("package selftest: 6400 bitstream identity mismatch") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--target", required=True) parser.add_argument("--kind", choices=("source", "review", "firmware"), default="source") parser.add_argument("--output-dir", type=Path, default=ROOT / "dist") parser.add_argument("--include-reference", action="store_true") args = parser.parse_args(argv) path = build_target_package(args.target, args.kind, args.output_dir, args.include_reference) print(json.dumps({"status": "pass", "package": str(path), "sha256": _sha256(path)}, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())