package_target.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #!/usr/bin/env python3
  2. """Target-bound source/review/firmware packager with fail-closed release pins."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import re
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import zipfile
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. _ROOT = Path(__file__).resolve().parents[1]
  17. if str(_ROOT) not in sys.path:
  18. sys.path.insert(0, str(_ROOT))
  19. from tools.generate_target import generate_named_target
  20. from tools.generate_6400_v1 import generate as generate_6400_v1
  21. from tools.run_6400_td import HARDWARE_PROFILES, source_closure as td_source_closure
  22. from tools.target_registry import ROOT, load_source_closure, release_blocked, resolve_target
  23. CANDIDATE_NOTICE_ZH_CN = "候选,仅供审核;未冻结TTL Pin/未做硬件验证前不要烧录"
  24. DO_NOT_PROGRAM_LINE = "DO NOT PROGRAM / 不要烧录"
  25. def _sha256(path: Path) -> str:
  26. digest = hashlib.sha256()
  27. with path.open("rb") as handle:
  28. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  29. digest.update(chunk)
  30. return digest.hexdigest()
  31. def _git(repo: Path, *args: str) -> str:
  32. try:
  33. return subprocess.check_output(["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL).strip()
  34. except (OSError, subprocess.CalledProcessError):
  35. return os.environ.get("PROD2U_COMMIT", "unknown")
  36. def _add(zipf: zipfile.ZipFile, src: Path, dest: str, sums: dict[str, str]) -> None:
  37. zipf.write(src, dest)
  38. sums[dest] = _sha256(src)
  39. def _check_active_6400_generated() -> None:
  40. expected = generate_6400_v1(ROOT / "generated/6400")
  41. drift = [
  42. str(path.relative_to(ROOT))
  43. for path, content in expected.items()
  44. if not path.is_file() or path.read_bytes() != content
  45. ]
  46. if drift:
  47. raise SystemExit("6400 package blocked: active generated contract drift: " + ", ".join(drift))
  48. def _resolve_6400_profile(target_name: str, profile_name: str | None) -> str:
  49. if target_name in HARDWARE_PROFILES:
  50. if profile_name is not None and profile_name != target_name:
  51. raise SystemExit("6400 package blocked: target/profile mismatch")
  52. return target_name
  53. if target_name == "6400-sim-debug" or profile_name == "6400-sim-debug":
  54. raise SystemExit("6400 package blocked: Sim-Debug cannot produce a hardware package")
  55. if target_name != "6400" or profile_name not in HARDWARE_PROFILES:
  56. raise SystemExit(
  57. "6400 package blocked: explicitly select --profile "
  58. "6400-control or 6400-identification"
  59. )
  60. return profile_name
  61. def _validated_td_bitstream(
  62. profile_name: str, receipt_path: Path | None, commit: str
  63. ) -> tuple[Path, dict[str, object]]:
  64. if receipt_path is None or not receipt_path.is_file():
  65. raise SystemExit("6400 firmware package blocked: explicit --td-receipt is required")
  66. receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
  67. profile = HARDWARE_PROFILES[profile_name]
  68. project_path = ROOT / str(profile["project"])
  69. closure_path = ROOT / str(profile["closure"])
  70. expected = {
  71. "schema": "prod2u-6400-td-receipt-v1",
  72. "status": "PASS",
  73. "profile": profile_name,
  74. "project": str(profile["project"]),
  75. "source_closure": str(profile["closure"]),
  76. "commit": commit,
  77. "production": bool(profile["production"]),
  78. "stimulus": bool(profile["stimulus"]),
  79. "simulation_only": False,
  80. "artifact_basename": str(profile["artifact_basename"]),
  81. "timing_pass_25mhz": True,
  82. "project_sha256": _sha256(project_path),
  83. "source_closure_sha256": _sha256(closure_path),
  84. }
  85. mismatches = [
  86. f"{key}: expected {value!r}, got {receipt.get(key)!r}"
  87. for key, value in expected.items()
  88. if receipt.get(key) != value
  89. ]
  90. if mismatches:
  91. raise SystemExit("6400 firmware package blocked: TD receipt mismatch: " + "; ".join(mismatches))
  92. known_unbound_ports = receipt.get("known_unbound_ports")
  93. if (
  94. not isinstance(known_unbound_ports, list)
  95. or any(
  96. not isinstance(port, str) or not port
  97. for port in known_unbound_ports
  98. )
  99. or len(set(known_unbound_ports)) != len(known_unbound_ports)
  100. ):
  101. raise SystemExit(
  102. "6400 firmware package blocked: TD receipt has invalid known_unbound_ports"
  103. )
  104. deployment_status = receipt.get("deployment_status")
  105. if not isinstance(deployment_status, str) or not deployment_status:
  106. raise SystemExit(
  107. "6400 firmware package blocked: TD receipt has invalid deployment_status"
  108. )
  109. bitstream_value = receipt.get("bitstream")
  110. if not isinstance(bitstream_value, str) or not bitstream_value:
  111. raise SystemExit("6400 firmware package blocked: TD receipt has no bitstream")
  112. bitstream = Path(bitstream_value)
  113. if not bitstream.is_absolute():
  114. bitstream = receipt_path.parent / bitstream
  115. expected_name = f"{profile['artifact_basename']}.bit"
  116. if bitstream.name != expected_name or not bitstream.is_file() or bitstream.stat().st_size == 0:
  117. raise SystemExit("6400 firmware package blocked: receipt bitstream is missing or misnamed")
  118. if receipt.get("bitstream_sha256") != _sha256(bitstream):
  119. raise SystemExit("6400 firmware package blocked: receipt bitstream SHA-256 mismatch")
  120. return bitstream.resolve(), receipt
  121. def build_target_package(
  122. target_name: str,
  123. kind: str,
  124. output_dir: Path,
  125. include_reference: bool = False,
  126. *,
  127. profile_name: str | None = None,
  128. td_receipt: Path | None = None,
  129. ) -> Path:
  130. is_6400 = target_name == "6400" or target_name.startswith("6400-")
  131. receipt_payload: dict[str, object] | None = None
  132. expanded_closure: dict[str, object] | None = None
  133. hardware_validation = "NOT RUN"
  134. known_unbound_ports: tuple[str, ...] = ()
  135. deployment_status: str | None = None
  136. if is_6400:
  137. selected_profile = _resolve_6400_profile(target_name, profile_name)
  138. profile = HARDWARE_PROFILES[selected_profile]
  139. _check_active_6400_generated()
  140. project_path = ROOT / str(profile["project"])
  141. closure_path = ROOT / str(profile["closure"])
  142. generated_dir = ROOT / "generated/6400"
  143. project = json.loads(project_path.read_text(encoding="utf-8"))
  144. sources, _closure_inputs = td_source_closure(selected_profile)
  145. top_module = str(project["top"])
  146. project_id = selected_profile
  147. target_alias = "6400"
  148. package_label = selected_profile
  149. blocked, pins = False, ()
  150. expanded_closure = {
  151. "schema": "prod2u-source-closure-expanded-v1",
  152. "project_id": selected_profile,
  153. "top_module": top_module,
  154. "sources": sources,
  155. }
  156. else:
  157. target = resolve_target(target_name)
  158. generate_named_target(target.alias)
  159. project_path = target.project_config
  160. closure_path = target.source_closure
  161. generated_dir = target.generated_dir
  162. project = json.loads(project_path.read_text(encoding="utf-8"))
  163. blocked, pins = release_blocked(target, project)
  164. sources = list(load_source_closure(target))
  165. top_module = target.top_module
  166. project_id = target.project_id
  167. target_alias = target.alias
  168. package_label = target.alias
  169. selected_profile = target.profile
  170. if kind == "firmware" and blocked:
  171. raise SystemExit(
  172. "release_blocked\n" + "\n".join(f"{name} pin unresolved" for name in pins)
  173. )
  174. commit = _git(ROOT, "rev-parse", "HEAD")
  175. bitstream_path: Path | None = None
  176. if kind == "firmware" and is_6400:
  177. if not re.fullmatch(r"[0-9a-f]{40}", commit):
  178. raise SystemExit("6400 firmware package blocked: exact Git commit is unavailable")
  179. bitstream_path, receipt_payload = _validated_td_bitstream(
  180. selected_profile, td_receipt, commit
  181. )
  182. ports_value = receipt_payload["known_unbound_ports"]
  183. status_value = receipt_payload["deployment_status"]
  184. assert isinstance(ports_value, list)
  185. assert all(isinstance(port, str) for port in ports_value)
  186. assert isinstance(status_value, str)
  187. known_unbound_ports = tuple(ports_value)
  188. deployment_status = status_value
  189. blocked = bool(known_unbound_ports) or hardware_validation != "PASS"
  190. pins = known_unbound_ports
  191. run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  192. name = f"prod2u-{package_label}-{kind}-{commit[:12]}-{run_id}"
  193. output_dir.mkdir(parents=True, exist_ok=True)
  194. zip_path = output_dir / f"{name}.zip"
  195. manifest = {
  196. "schema": "prod2u-target-package-v1",
  197. "target_alias": target_alias,
  198. "profile": selected_profile,
  199. "firmware_role": (
  200. "production"
  201. if selected_profile == "6400-control"
  202. else "identification" if selected_profile == "6400-identification" else "legacy"
  203. ),
  204. "project_id": project_id,
  205. "top": top_module,
  206. "kind": kind,
  207. "commit": commit,
  208. "run_id": run_id,
  209. "project_config_sha256": _sha256(project_path),
  210. "source_manifest_sha256": _sha256(closure_path),
  211. "bitstream_sha256": _sha256(bitstream_path) if bitstream_path else None,
  212. "hardware_validation": hardware_validation,
  213. "release_blocked": blocked,
  214. "unresolved_pins": list(pins),
  215. "include_reference": include_reference,
  216. }
  217. if is_6400:
  218. manifest.update(
  219. {
  220. "production": bool(profile["production"]),
  221. "stimulus": bool(profile["stimulus"]),
  222. "simulation_only": False,
  223. }
  224. )
  225. if is_6400 and kind == "firmware":
  226. manifest.update(
  227. {
  228. "candidate_notice_zh_CN": CANDIDATE_NOTICE_ZH_CN,
  229. "candidate_only": blocked,
  230. "deployable": not blocked,
  231. "deployment_status": deployment_status,
  232. "known_unbound_ports": list(known_unbound_ports),
  233. "unresolved_ports": list(known_unbound_ports),
  234. }
  235. )
  236. with tempfile.TemporaryDirectory() as tmp:
  237. stage = Path(tmp)
  238. (stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  239. if is_6400 and kind == "firmware" and blocked:
  240. (stage / "CANDIDATE-NOTICE.zh-CN.txt").write_text(
  241. DO_NOT_PROGRAM_LINE + "\n"
  242. + CANDIDATE_NOTICE_ZH_CN + "\n"
  243. + f"未冻结端口:{', '.join(known_unbound_ports)}\n"
  244. + f"部署状态:{deployment_status}\n"
  245. + f"硬件验证:{hardware_validation}\n",
  246. encoding="utf-8",
  247. )
  248. shutil.copy2(project_path, stage / "project.json")
  249. shutil.copy2(closure_path, stage / "source-closure.json")
  250. if expanded_closure is not None:
  251. (stage / "source-closure-expanded.json").write_text(
  252. json.dumps(expanded_closure, indent=2, sort_keys=True) + "\n",
  253. encoding="utf-8",
  254. )
  255. gen_dir = stage / ("generated/6400" if is_6400 else "generated")
  256. if generated_dir.is_dir():
  257. shutil.copytree(generated_dir, gen_dir)
  258. src_dir = stage / "src"
  259. src_dir.mkdir()
  260. for rel in sources:
  261. dest = stage / rel
  262. dest.parent.mkdir(parents=True, exist_ok=True)
  263. shutil.copy2(ROOT / rel, dest)
  264. if bitstream_path is not None:
  265. bitstream_name = bitstream_path.name
  266. shutil.copy2(bitstream_path, stage / bitstream_name)
  267. (stage / "BITSTREAM-SHA256.txt").write_text(
  268. f"{_sha256(bitstream_path)} {bitstream_name}\n",
  269. encoding="ascii",
  270. )
  271. role = "生产" if selected_profile == "6400-control" else "Identification 专用"
  272. (stage / "FLASH-INSTRUCTIONS.zh-CN.txt").write_text(
  273. DO_NOT_PROGRAM_LINE + "\n"
  274. + CANDIDATE_NOTICE_ZH_CN + "\n\n"
  275. + f"6400 {role}固件审核说明\n"
  276. "========================\n"
  277. "目标器件:EF2L45BG256B(6400 前后独立温控)\n"
  278. f"固件文件:{bitstream_name}\n"
  279. "请审核 BITSTREAM-SHA256.txt 与 TD-BUILD-RECEIPT.json 后再冻结制品。\n"
  280. f"Host 串口使用 921600 8N1;每条合法命令先独立 ACK;Profile={selected_profile}。\n"
  281. "本包只包含 6400 固件,不能用于 MRDIMM 门控板。\n"
  282. + (
  283. "本固件含 SET_STIMULUS,仅限 Identification,不得作为 Production。\n"
  284. if selected_profile == "6400-identification"
  285. else "Production 固件不包含 SET_STIMULUS(stimulus=false)。\n"
  286. )
  287. + "\n"
  288. "注意:本次交付未执行真实 JTAG/硬件烧录,硬件验证状态为 NOT RUN。\n",
  289. encoding="utf-8",
  290. )
  291. assert receipt_payload is not None
  292. (stage / "TD-BUILD-RECEIPT.json").write_text(
  293. json.dumps(receipt_payload, indent=2, sort_keys=True) + "\n",
  294. encoding="utf-8",
  295. )
  296. if include_reference:
  297. ref = ROOT / "reference"
  298. if ref.is_dir():
  299. shutil.copytree(ref, stage / "reference", dirs_exist_ok=True)
  300. sums: dict[str, str] = {}
  301. if zip_path.exists():
  302. zip_path.unlink()
  303. with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zipf:
  304. for path in sorted(stage.rglob("*")):
  305. if path.is_file():
  306. _add(zipf, path, path.relative_to(stage).as_posix(), sums)
  307. zipf.writestr("SHA256SUMS", "".join(f"{digest} {name}\n" for name, digest in sorted(sums.items())))
  308. _selftest(zip_path)
  309. return zip_path
  310. def _selftest(zip_path: Path) -> None:
  311. with tempfile.TemporaryDirectory() as tmp:
  312. dest = Path(tmp) / "unpacked"
  313. dest.mkdir()
  314. with zipfile.ZipFile(zip_path) as zipf:
  315. for info in zipf.infolist():
  316. if info.filename.startswith("/") or ".." in Path(info.filename).parts:
  317. raise SystemExit(f"unsafe zip path: {info.filename}")
  318. zipf.extractall(dest)
  319. manifest = json.loads((dest / "manifest.json").read_text(encoding="utf-8"))
  320. if manifest.get("hardware_validation") != "NOT RUN":
  321. raise SystemExit("package selftest: hardware_validation must be NOT RUN")
  322. sums = (dest / "SHA256SUMS").read_text(encoding="utf-8").splitlines()
  323. for line in sums:
  324. digest, name = line.split(" ", 1)
  325. observed = _sha256(dest / name)
  326. if observed != digest:
  327. raise SystemExit(f"hash mismatch {name}")
  328. if manifest.get("target_alias") == "6400":
  329. profile_name = manifest.get("profile")
  330. if profile_name not in HARDWARE_PROFILES:
  331. raise SystemExit("package selftest: invalid 6400 hardware profile")
  332. members = [path.relative_to(dest).as_posix() for path in dest.rglob("*")]
  333. if any(name.startswith("src/generated/6400/") for name in members):
  334. raise SystemExit("package selftest: historical src/generated/6400 leaked")
  335. closure = json.loads(
  336. (dest / "source-closure-expanded.json").read_text(encoding="utf-8")
  337. )
  338. closure_text = "\n".join(closure["sources"])
  339. if "src/generated/6400" in closure_text or "prod2u_6400_front_back_top" in closure_text:
  340. raise SystemExit("package selftest: historical 6400 closure leaked")
  341. if manifest.get("target_alias") == "6400" and manifest.get("kind") == "firmware":
  342. expected_name = (
  343. "prod2u_6400_front_back.bit"
  344. if manifest["profile"] == "6400-control"
  345. else "prod2u_6400_identification.bit"
  346. )
  347. bit = dest / expected_name
  348. if not bit.is_file() or _sha256(bit) != manifest.get("bitstream_sha256"):
  349. raise SystemExit("package selftest: 6400 bitstream identity mismatch")
  350. receipt = json.loads(
  351. (dest / "TD-BUILD-RECEIPT.json").read_text(encoding="utf-8")
  352. )
  353. if receipt.get("profile") != manifest["profile"] or receipt.get(
  354. "bitstream_sha256"
  355. ) != manifest["bitstream_sha256"]:
  356. raise SystemExit("package selftest: TD receipt/profile identity mismatch")
  357. receipt_ports = receipt.get("known_unbound_ports")
  358. if (
  359. manifest.get("release_blocked") is not True
  360. or manifest.get("deployable") is not False
  361. or manifest.get("candidate_only") is not True
  362. or manifest.get("known_unbound_ports") != receipt_ports
  363. or manifest.get("unresolved_ports") != receipt_ports
  364. or manifest.get("unresolved_pins") != receipt_ports
  365. or manifest.get("deployment_status") != receipt.get("deployment_status")
  366. ):
  367. raise SystemExit("package selftest: unsafe deployment gate mismatch")
  368. if not (dest / "CANDIDATE-NOTICE.zh-CN.txt").is_file():
  369. raise SystemExit("package selftest: candidate notice missing")
  370. production = manifest["profile"] == "6400-control"
  371. if manifest.get("production") is not production or manifest.get(
  372. "stimulus"
  373. ) is production:
  374. raise SystemExit("package selftest: firmware profile semantics mismatch")
  375. instructions = (dest / "FLASH-INSTRUCTIONS.zh-CN.txt").read_text(
  376. encoding="utf-8"
  377. )
  378. if (
  379. not instructions.startswith(DO_NOT_PROGRAM_LINE)
  380. or "921600 8N1" not in instructions
  381. or "独立 ACK" not in instructions
  382. ):
  383. raise SystemExit("package selftest: Host UART/ACK contract missing")
  384. def main(argv: list[str] | None = None) -> int:
  385. parser = argparse.ArgumentParser()
  386. parser.add_argument("--target", required=True)
  387. parser.add_argument("--kind", choices=("source", "review", "firmware"), default="source")
  388. parser.add_argument(
  389. "--profile",
  390. choices=("6400-control", "6400-identification", "6400-sim-debug"),
  391. )
  392. parser.add_argument("--td-receipt", type=Path)
  393. parser.add_argument("--output-dir", type=Path, default=ROOT / "dist")
  394. parser.add_argument("--include-reference", action="store_true")
  395. args = parser.parse_args(argv)
  396. path = build_target_package(
  397. args.target,
  398. args.kind,
  399. args.output_dir,
  400. args.include_reference,
  401. profile_name=args.profile,
  402. td_receipt=args.td_receipt,
  403. )
  404. print(json.dumps({"status": "pass", "package": str(path), "sha256": _sha256(path)}, indent=2))
  405. return 0
  406. if __name__ == "__main__":
  407. raise SystemExit(main())