build_firmware_package.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. #!/usr/bin/env python3
  2. """Build the Prod2U door-temperature final firmware delivery package.
  3. This is a deterministic wrapper that collects:
  4. - the canonical bitstream from an explicit TD root,
  5. - original and provenance-augmented TD reports,
  6. - source-closure comparison across artifact/matrix/final dev commits,
  7. - selected TD stage evidence (syn/phy/bitgen reports and logs),
  8. - source/contracts/TD inputs,
  9. - generated host contract and golden vectors,
  10. - verification receipts (when available),
  11. - package manifest, SHA-256 sums, and an external selftest sidecar.
  12. It does not access COM/JTAG or program hardware.
  13. """
  14. from __future__ import annotations
  15. import argparse
  16. import hashlib
  17. import json
  18. import shutil
  19. import subprocess
  20. import sys
  21. import zipfile
  22. from datetime import datetime, timezone
  23. from pathlib import Path
  24. from typing import Any
  25. ROOT = Path(__file__).resolve().parents[1]
  26. TD_STAGE_SUFFIXES = {".rpt", ".timing", ".area", ".qor", ".log", ".logw"}
  27. REPO_TD_INPUTS = [
  28. "td/prod2u_p4_normal_v3.prj",
  29. "td/syn/prod2u_p4_normal_v3.tcl",
  30. "td/phy/prod2u_p4_normal_v3.tcl",
  31. "td/bitgen/prod2u_p4_normal_v3.tcl",
  32. ]
  33. class PackagingError(RuntimeError):
  34. """Raised when the firmware package cannot be produced safely."""
  35. def _sha256_file(path: Path) -> str:
  36. digest = hashlib.sha256()
  37. with path.open("rb") as stream:
  38. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  39. digest.update(chunk)
  40. return digest.hexdigest()
  41. def _sha256_bytes(data: bytes) -> str:
  42. return hashlib.sha256(data).hexdigest()
  43. def _read_json(path: Path) -> Any:
  44. return json.loads(path.read_text(encoding="utf-8-sig"))
  45. def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
  46. """Return the contents of a tracked path at a specific commit."""
  47. completed = subprocess.run(
  48. ["git", "-C", str(repo_root), "show", f"{commit}:{relative_path}"],
  49. stdout=subprocess.PIPE,
  50. stderr=subprocess.PIPE,
  51. check=False,
  52. )
  53. if completed.returncode != 0:
  54. raise PackagingError(
  55. f"git show failed for {commit}:{relative_path}: {completed.stderr.decode('utf-8', errors='ignore').strip()}"
  56. )
  57. return completed.stdout
  58. def _resolve_path(path: Path) -> Path:
  59. return Path(path).expanduser().resolve()
  60. def _inside(root: Path, candidate: Path) -> bool:
  61. """Return True if candidate is root or under root."""
  62. root = _resolve_path(root)
  63. candidate = _resolve_path(candidate)
  64. try:
  65. candidate.relative_to(root)
  66. return True
  67. except ValueError:
  68. return False
  69. def _validate_td_root(
  70. *,
  71. td_root: Path,
  72. bitstream_path: Path,
  73. td_report_path: Path,
  74. ) -> None:
  75. """Ensure bitstream and report belong to the selected TD root."""
  76. if not _inside(td_root, bitstream_path):
  77. raise PackagingError(f"bitstream {bitstream_path} is outside selected td_root {td_root}")
  78. if not _inside(td_root, td_report_path):
  79. raise PackagingError(f"td report {td_report_path} is outside selected td_root {td_root}")
  80. def _bitstream_path_from_td_root(td_root: Path) -> Path:
  81. return _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit")
  82. def _report_path_from_td_root(td_root: Path) -> Path:
  83. return _resolve_path(td_root / "report.json")
  84. def generate_source_closure_comparison(
  85. *,
  86. td_report: dict[str, Any],
  87. artifact_commit: str,
  88. matrix_commit: str,
  89. final_dev_commit: str,
  90. repo_root: Path = ROOT,
  91. ) -> dict[str, Any]:
  92. """Compare synthesis inputs across artifact, matrix, and final dev commits."""
  93. inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {})
  94. if not inputs:
  95. raise PackagingError("TD report has no synthesis_input_manifest.inputs")
  96. entries: list[dict[str, Any]] = []
  97. production_changed_paths: list[str] = []
  98. all_same = True
  99. for relative_path, artifact_sha in sorted(inputs.items()):
  100. row: dict[str, Any] = {"path": relative_path, "artifact_expected_sha256": artifact_sha}
  101. values: list[str | None] = []
  102. for commit, key in [
  103. (artifact_commit, "artifact_source_sha256"),
  104. (matrix_commit, "matrix_commit_sha256"),
  105. (final_dev_commit, "final_dev_commit_sha256"),
  106. ]:
  107. try:
  108. content = _git_show_file(repo_root, commit, relative_path)
  109. sha = _sha256_bytes(content)
  110. except PackagingError:
  111. sha = None
  112. row[key] = sha
  113. values.append(sha)
  114. if values[0] == values[1] == values[2] and values[0] is not None:
  115. row["status"] = "same"
  116. else:
  117. row["status"] = "different"
  118. all_same = False
  119. if values[0] != values[2]:
  120. production_changed_paths.append(relative_path)
  121. entries.append(row)
  122. comparison_text = json.dumps(
  123. {
  124. "artifact_source_commit": artifact_commit,
  125. "matrix_commit": matrix_commit,
  126. "final_dev_commit": final_dev_commit,
  127. "source_closure_equal": all_same,
  128. "production_changed_paths": production_changed_paths,
  129. "entries": entries,
  130. },
  131. sort_keys=True,
  132. )
  133. source_set_sha256 = _sha256_bytes(comparison_text.encode("utf-8"))
  134. return {
  135. "schema": "prod2u-source-closure-comparison-v1",
  136. "artifact_source_commit": artifact_commit,
  137. "matrix_commit": matrix_commit,
  138. "final_dev_commit": final_dev_commit,
  139. "source_closure_equal": all_same,
  140. "production_changed_paths": production_changed_paths,
  141. "source_set_sha256": source_set_sha256,
  142. "inputs": entries,
  143. }
  144. def generate_td_provenance(
  145. *,
  146. original_report: dict[str, Any],
  147. artifact_commit: str,
  148. source_closure_comparison_sha256: str,
  149. bitstream_sha256: str,
  150. matrix_run_id: str | None,
  151. ) -> dict[str, Any]:
  152. """Bind the original TD run to the current matrix and source closure."""
  153. return {
  154. "schema": "prod2u-td-provenance-v1",
  155. "status": "bound_by_source_closure_comparison",
  156. "artifact_source_commit": artifact_commit,
  157. "original_td_run_id": original_report.get("run_id"),
  158. "original_placeholder_verification_run_id": original_report.get("verification_run_id"),
  159. "matrix_run_id": matrix_run_id,
  160. "source_closure_comparison_sha256": source_closure_comparison_sha256,
  161. "bitstream_sha256": bitstream_sha256,
  162. "original_report_path": "td/original-final_td_report.json",
  163. "project_config_sha256": original_report.get("project_config_sha256"),
  164. "td_source_manifest_sha256": original_report.get("td_source_manifest_sha256"),
  165. "synthesis_input_manifest_sha256": original_report.get("synthesis_input_manifest", {}).get("sha256"),
  166. }
  167. def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str, sha256_entries: list[str]) -> None:
  168. zipf.write(src, arcname)
  169. sha256_entries.append(f"{_sha256_file(src)} {arcname}")
  170. def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str, sha256_entries: list[str]) -> None:
  171. payload = text.encode("utf-8")
  172. zipf.writestr(arcname, payload)
  173. sha256_entries.append(f"{_sha256_bytes(payload)} {arcname}")
  174. def _collect_td_stage_files(td_root: Path) -> list[tuple[Path, str]]:
  175. """Collect allowed evidence files from the selected TD build stages."""
  176. collected: list[tuple[Path, str]] = []
  177. stages = ["syn", "phy", "bitgen"]
  178. for stage in stages:
  179. stage_dir = _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / stage)
  180. if not stage_dir.is_dir():
  181. continue
  182. for item in stage_dir.iterdir():
  183. if item.is_file() and item.suffix.casefold() in TD_STAGE_SUFFIXES:
  184. collected.append((item, f"td/{stage}/{item.name}"))
  185. return collected
  186. def _selftest_package(
  187. *,
  188. zip_path: Path,
  189. expected_manifest: dict[str, Any],
  190. td_root: Path,
  191. ) -> dict[str, Any]:
  192. """Verify the built firmware package before writing the sidecar."""
  193. failures: list[str] = []
  194. with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
  195. names = set(zipf.namelist())
  196. required = {
  197. "fw.bit",
  198. "BITSTREAM-SHA256.txt",
  199. "ARTIFACT-SOURCE-COMMIT.txt",
  200. "MATRIX-COMMIT.txt",
  201. "FINAL-DEV-COMMIT.txt",
  202. "SOURCE-CLOSURE-UNCHANGED.txt",
  203. "PACKAGE-MANIFEST.json",
  204. "SHA256SUMS.txt",
  205. "td/original-final_td_report.json",
  206. "td/TD-PROVENANCE.json",
  207. "evidence/SOURCE-CLOSURE-COMPARISON.json",
  208. "project.json",
  209. "config/source_closure.json",
  210. }
  211. missing = sorted(required - names)
  212. if missing:
  213. failures.append(f"missing_required_files:{missing}")
  214. bad = zipf.testzip()
  215. if bad is not None:
  216. failures.append(f"crc_failed:{bad}")
  217. manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
  218. if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
  219. failures.append("bitstream_sha_manifest_mismatch")
  220. # Detect stale repo TD logs from ROOT/td that should not be present
  221. for name in names:
  222. if name.startswith("td/") and "td_20260630" in name:
  223. failures.append(f"stale_td_log_in_package:{name}")
  224. return {
  225. "status": "fail" if failures else "pass",
  226. "failures": failures,
  227. "package_path": str(zip_path),
  228. "package_sha256": _sha256_file(zip_path),
  229. "td_root": str(td_root),
  230. }
  231. def build_firmware_package(
  232. *,
  233. output_dir: Path,
  234. package_name: str | None,
  235. td_root: Path,
  236. artifact_commit: str,
  237. matrix_commit: str,
  238. final_dev_commit: str,
  239. source_closure_unchanged: bool,
  240. bitstream_path: Path | None = None,
  241. td_report_path: Path | None = None,
  242. matrix_receipt_path: Path | None = None,
  243. matrix_run_id: str | None = None,
  244. ) -> tuple[Path, Path]:
  245. """Build and selftest the final firmware ZIP."""
  246. td_root = _resolve_path(td_root)
  247. if bitstream_path is None:
  248. bitstream_path = _bitstream_path_from_td_root(td_root)
  249. if td_report_path is None:
  250. td_report_path = _report_path_from_td_root(td_root)
  251. bitstream_path = _resolve_path(bitstream_path)
  252. td_report_path = _resolve_path(td_report_path)
  253. _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path)
  254. if not bitstream_path.is_file():
  255. raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
  256. if not td_report_path.is_file():
  257. raise FileNotFoundError(f"TD report not found: {td_report_path}")
  258. td_report = _read_json(td_report_path)
  259. bitstream_sha256 = _sha256_file(bitstream_path)
  260. # Strong binding checks
  261. report_bitstream_sha = td_report.get("bitstream_sha256")
  262. if report_bitstream_sha and report_bitstream_sha != bitstream_sha256:
  263. raise PackagingError(
  264. f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}"
  265. )
  266. report_commit = td_report.get("commit_full") or td_report.get("commit")
  267. if report_commit and report_commit != artifact_commit:
  268. raise PackagingError(
  269. f"TD report commit {report_commit} does not match artifact_source_commit {artifact_commit}"
  270. )
  271. report_project_sha = td_report.get("project_config_sha256")
  272. current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json")
  273. if report_project_sha and report_project_sha != current_project_sha:
  274. raise PackagingError(
  275. f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
  276. )
  277. comparison = generate_source_closure_comparison(
  278. td_report=td_report,
  279. artifact_commit=artifact_commit,
  280. matrix_commit=matrix_commit,
  281. final_dev_commit=final_dev_commit,
  282. repo_root=ROOT,
  283. )
  284. if not source_closure_unchanged and comparison["source_closure_equal"]:
  285. # Caller claimed changed but comparison says same: trust explicit flag
  286. pass
  287. if source_closure_unchanged and not comparison["source_closure_equal"]:
  288. raise PackagingError(
  289. f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
  290. )
  291. comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n"
  292. comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8"))
  293. provenance = generate_td_provenance(
  294. original_report=td_report,
  295. artifact_commit=artifact_commit,
  296. source_closure_comparison_sha256=comparison_sha256,
  297. bitstream_sha256=bitstream_sha256,
  298. matrix_run_id=matrix_run_id,
  299. )
  300. provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n"
  301. provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8"))
  302. timing = td_report.get("timing", {})
  303. resources_section = td_report.get("resources", {})
  304. utilization = resources_section.get("utilization", {})
  305. manifest: dict[str, Any] = {
  306. "schema": "prod2u-door-temp-final-package-manifest-v2",
  307. "package_name": package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}",
  308. "status": "VERIFIED_OFFLINE",
  309. "created_at": datetime.now(timezone.utc).isoformat(),
  310. "verification_scope": "offline",
  311. "hardware_validation": "not_run",
  312. "artifact_source_commit": artifact_commit,
  313. "matrix_commit": matrix_commit,
  314. "final_dev_commit": final_dev_commit,
  315. "td_run_id": td_report.get("run_id"),
  316. "matrix_run_id": matrix_run_id,
  317. "source_closure_unchanged": comparison["source_closure_equal"],
  318. "project_config_sha256": current_project_sha,
  319. "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
  320. "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
  321. "source_closure_comparison_sha256": comparison_sha256,
  322. "bitstream_sha256": bitstream_sha256,
  323. "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None,
  324. "original_td_receipt_sha256": _sha256_file(td_report_path),
  325. "td_provenance_sha256": provenance_sha256,
  326. "resources": {
  327. "lut": utilization.get("lut", {}).get("used"),
  328. "register": utilization.get("reg", {}).get("used"),
  329. "packed_slice": resources_section.get("packing", {}).get("total_slices"),
  330. "bram": utilization.get("bram", {}).get("used"),
  331. "dsp": utilization.get("dsp", {}).get("used"),
  332. },
  333. "timing": {
  334. "fmax_mhz": timing.get("fmax_mhz"),
  335. "setup_slack_ns": timing.get("worst_setup_slack_ns"),
  336. "hold_slack_ns": timing.get("worst_hold_slack_ns"),
  337. },
  338. }
  339. output_dir = _resolve_path(output_dir)
  340. output_dir.mkdir(parents=True, exist_ok=True)
  341. name = manifest["package_name"]
  342. zip_path = output_dir / f"{name}.zip"
  343. if zip_path.exists():
  344. zip_path.unlink()
  345. sha256_entries: list[str] = []
  346. with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf:
  347. # Bitstream and provenance
  348. _add_file(zipf, bitstream_path, "fw.bit", sha256_entries)
  349. _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries)
  350. _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries)
  351. _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries)
  352. _add_text(zipf, final_dev_commit, "FINAL-DEV-COMMIT.txt", sha256_entries)
  353. _add_text(zipf, "true" if comparison["source_closure_equal"] else "false", "SOURCE-CLOSURE-UNCHANGED.txt", sha256_entries)
  354. # Original TD report and provenance
  355. _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)
  356. _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries)
  357. # Selected TD stage evidence from the explicit TD root
  358. for src, arcname in _collect_td_stage_files(td_root):
  359. _add_file(zipf, src, arcname, sha256_entries)
  360. # Project contract and protocol
  361. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries)
  362. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries)
  363. _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries)
  364. # Generated artifacts
  365. for gen in (ROOT / "src" / "generated").iterdir():
  366. if gen.is_file():
  367. _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries)
  368. # Constraints
  369. for adc in (ROOT / "constraints").iterdir():
  370. if adc.is_file():
  371. _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries)
  372. # Tracked TD inputs from the repo (not the build root)
  373. for td_input in REPO_TD_INPUTS:
  374. src = ROOT / td_input
  375. if src.is_file():
  376. _add_file(zipf, src, td_input, sha256_entries)
  377. # Source closure manifest
  378. _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries)
  379. # Source-closure comparison
  380. _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries)
  381. # Optional matrix receipt
  382. if matrix_receipt_path and matrix_receipt_path.is_file():
  383. _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries)
  384. # Manifest and SHA256SUMS
  385. manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
  386. _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries)
  387. _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries)
  388. selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root)
  389. if selftest["status"] != "pass":
  390. zip_path.unlink(missing_ok=True)
  391. raise PackagingError(f"firmware package selftest failed: {selftest['failures']}")
  392. selftest["package_selftest_status"] = "pass"
  393. selftest["manifest"] = manifest
  394. sidecar_path = output_dir / f"{name}.selftest.json"
  395. sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  396. return zip_path, sidecar_path
  397. def main(argv: list[str] | None = None) -> int:
  398. parser = argparse.ArgumentParser(description=__doc__)
  399. parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
  400. parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
  401. parser.add_argument("--td-root", type=Path, required=True)
  402. parser.add_argument("--bitstream", type=Path, default=None)
  403. parser.add_argument("--td-report", type=Path, default=None)
  404. parser.add_argument("--artifact-commit", required=True)
  405. parser.add_argument("--matrix-commit", required=True)
  406. parser.add_argument("--final-dev-commit", required=True)
  407. parser.add_argument("--source-closure-unchanged", action="store_true")
  408. parser.add_argument("--matrix-receipt", type=Path, default=None)
  409. parser.add_argument("--matrix-run-id", default=None)
  410. args = parser.parse_args(argv)
  411. try:
  412. zip_path, sidecar_path = build_firmware_package(
  413. output_dir=args.output_dir,
  414. package_name=args.package_name,
  415. td_root=args.td_root,
  416. artifact_commit=args.artifact_commit,
  417. matrix_commit=args.matrix_commit,
  418. final_dev_commit=args.final_dev_commit,
  419. source_closure_unchanged=args.source_closure_unchanged,
  420. bitstream_path=args.bitstream,
  421. td_report_path=args.td_report,
  422. matrix_receipt_path=args.matrix_receipt,
  423. matrix_run_id=args.matrix_run_id,
  424. )
  425. except (FileNotFoundError, PackagingError) as exc:
  426. print(f"error: {exc}", file=sys.stderr)
  427. return 1
  428. print(
  429. json.dumps(
  430. {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)},
  431. indent=2,
  432. )
  433. )
  434. return 0
  435. if __name__ == "__main__":
  436. raise SystemExit(main())