build_firmware_package.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #!/usr/bin/env python3
  2. """Build the Prod2U door-temperature final firmware delivery package.
  3. This is a thin deterministic wrapper that collects:
  4. - the canonical bitstream (reused when the production source closure is unchanged),
  5. - final TD reports,
  6. - source/contracts/TD inputs,
  7. - generated host contract and golden vectors,
  8. - verification receipts (when available),
  9. - package manifest and SHA-256 sums.
  10. It does not access COM/JTAG or program hardware.
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import hashlib
  15. import json
  16. import shutil
  17. import sys
  18. import zipfile
  19. from datetime import datetime, timezone
  20. from pathlib import Path
  21. from typing import Any
  22. ROOT = Path(__file__).resolve().parents[1]
  23. TD_PRIMARY = Path.home() / "CodexTemp" / "cpld-td-primary2"
  24. BITSTREAM = TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit"
  25. TD_REPORT = TD_PRIMARY / "report.json"
  26. REPORT_DIRS = [
  27. ("syn", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "syn"),
  28. ("phy", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "phy"),
  29. ("bitgen", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen"),
  30. ]
  31. def _sha256_file(path: Path) -> str:
  32. digest = hashlib.sha256()
  33. with path.open("rb") as stream:
  34. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  35. digest.update(chunk)
  36. return digest.hexdigest()
  37. def _read_json(path: Path) -> Any:
  38. return json.loads(path.read_text(encoding="utf-8-sig"))
  39. def _copy_into(dst: Path, src: Path, rel: str) -> None:
  40. target = dst / rel
  41. target.parent.mkdir(parents=True, exist_ok=True)
  42. shutil.copy2(src, target)
  43. def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str) -> None:
  44. zipf.write(src, arcname)
  45. def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str) -> None:
  46. zipf.writestr(arcname, text.encode("utf-8"))
  47. def build_firmware_package(
  48. *,
  49. output_dir: Path,
  50. package_name: str | None,
  51. artifact_commit: str,
  52. final_dev_commit: str,
  53. source_closure_unchanged: bool,
  54. bitstream_path: Path = BITSTREAM,
  55. td_report_path: Path = TD_REPORT,
  56. evidence_dir: Path | None = None,
  57. ) -> Path:
  58. if not bitstream_path.is_file():
  59. raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
  60. if not td_report_path.is_file():
  61. raise FileNotFoundError(f"TD report not found: {td_report_path}")
  62. bitstream_sha256 = _sha256_file(bitstream_path)
  63. name = package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}"
  64. output_dir = Path(output_dir).resolve()
  65. output_dir.mkdir(parents=True, exist_ok=True)
  66. zip_path = output_dir / f"{name}.zip"
  67. if zip_path.exists():
  68. zip_path.unlink()
  69. td_report = _read_json(td_report_path)
  70. timing = td_report.get("timing", {})
  71. resources_section = td_report.get("resources", {})
  72. utilization = resources_section.get("utilization", {})
  73. manifest: dict[str, Any] = {
  74. "schema": "prod2u-door-temp-final-package-manifest-v1",
  75. "package_name": name,
  76. "created_at": datetime.now(timezone.utc).isoformat(),
  77. "artifact_source_commit": artifact_commit,
  78. "final_dev_commit": final_dev_commit,
  79. "source_closure_unchanged": source_closure_unchanged,
  80. "verification_scope": "offline",
  81. "hardware_validation": "not_run",
  82. "bitstream_sha256": bitstream_sha256,
  83. "resources": {
  84. "lut": utilization.get("lut", {}).get("used"),
  85. "register": utilization.get("reg", {}).get("used"),
  86. "packed_slice": resources_section.get("packing", {}).get("total_slices"),
  87. "bram": utilization.get("bram", {}).get("used"),
  88. "dsp": utilization.get("dsp", {}).get("used"),
  89. },
  90. "timing": {
  91. "fmax_mhz": timing.get("fmax_mhz"),
  92. "setup_slack_ns": timing.get("worst_setup_slack_ns"),
  93. "hold_slack_ns": timing.get("worst_hold_slack_ns"),
  94. },
  95. }
  96. sha256_entries: list[str] = []
  97. def add_and_hash(src: Path, arcname: str) -> None:
  98. _add_file(zipf, src, arcname)
  99. sha256_entries.append(f"{_sha256_file(src)} {arcname}")
  100. def add_text_and_hash(text: str, arcname: str) -> None:
  101. _add_text(zipf, text, arcname)
  102. sha256_entries.append(f"{hashlib.sha256(text.encode('utf-8')).hexdigest()} {arcname}")
  103. with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
  104. # Bitstream and provenance
  105. add_and_hash(bitstream_path, "fw.bit")
  106. add_text_and_hash(bitstream_sha256, "BITSTREAM-SHA256.txt")
  107. add_text_and_hash(artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt")
  108. add_text_and_hash(final_dev_commit, "FINAL-DEV-COMMIT.txt")
  109. add_text_and_hash(
  110. "true" if source_closure_unchanged else "false",
  111. "SOURCE-CLOSURE-UNCHANGED.txt",
  112. )
  113. # Final TD report and selected report files
  114. add_and_hash(td_report_path, "td/final_td_report.json")
  115. for stage, stage_dir in REPORT_DIRS:
  116. if stage_dir.is_dir():
  117. for item in stage_dir.iterdir():
  118. if item.is_file() and item.suffix.casefold() in {
  119. ".rpt", ".timing", ".area", ".qor", ".log"
  120. }:
  121. add_and_hash(item, f"td/{stage}/{item.name}")
  122. # Project contract and protocol
  123. add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json")
  124. add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md")
  125. add_and_hash(ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md")
  126. # Generated artifacts
  127. for gen in (ROOT / "src" / "generated").iterdir():
  128. if gen.is_file():
  129. add_and_hash(gen, f"src/generated/{gen.name}")
  130. # Constraints and TD inputs
  131. for adc in (ROOT / "constraints").iterdir():
  132. if adc.is_file():
  133. add_and_hash(adc, f"constraints/{adc.name}")
  134. for td_item in (ROOT / "td").rglob("*"):
  135. if td_item.is_file():
  136. rel = td_item.relative_to(ROOT / "td")
  137. if rel.parts and rel.parts[0] == "build":
  138. continue
  139. arcname = "td/" + "/".join(rel.parts)
  140. add_and_hash(td_item, arcname)
  141. # Source closure manifest
  142. add_and_hash(ROOT / "config" / "source_closure.json", "config/source_closure.json")
  143. # Optional verification/matrix evidence
  144. if evidence_dir is not None and evidence_dir.is_dir():
  145. for ev_file in evidence_dir.rglob("*"):
  146. if ev_file.is_file():
  147. arcname = "evidence/" + "/".join(ev_file.relative_to(evidence_dir).parts)
  148. add_and_hash(ev_file, arcname)
  149. # Manifest and SHA256SUMS
  150. manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
  151. add_text_and_hash(manifest_text, "PACKAGE-MANIFEST.json")
  152. add_text_and_hash("\n".join(sha256_entries) + "\n", "SHA256SUMS.txt")
  153. return zip_path
  154. def main(argv: list[str] | None = None) -> int:
  155. parser = argparse.ArgumentParser(description=__doc__)
  156. parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
  157. parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
  158. parser.add_argument("--artifact-commit", required=True)
  159. parser.add_argument("--final-dev-commit", required=True)
  160. parser.add_argument("--source-closure-unchanged", action="store_true")
  161. parser.add_argument("--bitstream", type=Path, default=BITSTREAM)
  162. parser.add_argument("--td-report", type=Path, default=TD_REPORT)
  163. parser.add_argument("--evidence-dir", type=Path, default=None)
  164. args = parser.parse_args(argv)
  165. try:
  166. path = build_firmware_package(
  167. output_dir=args.output_dir,
  168. package_name=args.package_name,
  169. artifact_commit=args.artifact_commit,
  170. final_dev_commit=args.final_dev_commit,
  171. source_closure_unchanged=args.source_closure_unchanged,
  172. bitstream_path=args.bitstream,
  173. td_report_path=args.td_report,
  174. evidence_dir=args.evidence_dir,
  175. )
  176. except FileNotFoundError as exc:
  177. print(f"blocked: {exc}", file=sys.stderr)
  178. return 1
  179. print(json.dumps({"status": "pass", "package": str(path), "bitstream": str(BITSTREAM)}, indent=2))
  180. return 0
  181. if __name__ == "__main__":
  182. raise SystemExit(main())