| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218 |
- #!/usr/bin/env python3
- """Build the Prod2U door-temperature final firmware delivery package.
- This is a thin deterministic wrapper that collects:
- - the canonical bitstream (reused when the production source closure is unchanged),
- - final TD reports,
- - source/contracts/TD inputs,
- - generated host contract and golden vectors,
- - verification receipts (when available),
- - package manifest and SHA-256 sums.
- It does not access COM/JTAG or program hardware.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import shutil
- import sys
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- TD_PRIMARY = Path.home() / "CodexTemp" / "cpld-td-primary2"
- BITSTREAM = TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit"
- TD_REPORT = TD_PRIMARY / "report.json"
- REPORT_DIRS = [
- ("syn", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "syn"),
- ("phy", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "phy"),
- ("bitgen", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen"),
- ]
- def _sha256_file(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def _read_json(path: Path) -> Any:
- return json.loads(path.read_text(encoding="utf-8-sig"))
- def _copy_into(dst: Path, src: Path, rel: str) -> None:
- target = dst / rel
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(src, target)
- def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str) -> None:
- zipf.write(src, arcname)
- def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str) -> None:
- zipf.writestr(arcname, text.encode("utf-8"))
- def build_firmware_package(
- *,
- output_dir: Path,
- package_name: str | None,
- artifact_commit: str,
- final_dev_commit: str,
- source_closure_unchanged: bool,
- bitstream_path: Path = BITSTREAM,
- td_report_path: Path = TD_REPORT,
- evidence_dir: Path | None = None,
- ) -> Path:
- if not bitstream_path.is_file():
- raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
- if not td_report_path.is_file():
- raise FileNotFoundError(f"TD report not found: {td_report_path}")
- bitstream_sha256 = _sha256_file(bitstream_path)
- name = package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}"
- output_dir = Path(output_dir).resolve()
- output_dir.mkdir(parents=True, exist_ok=True)
- zip_path = output_dir / f"{name}.zip"
- if zip_path.exists():
- zip_path.unlink()
- td_report = _read_json(td_report_path)
- timing = td_report.get("timing", {})
- resources_section = td_report.get("resources", {})
- utilization = resources_section.get("utilization", {})
- manifest: dict[str, Any] = {
- "schema": "prod2u-door-temp-final-package-manifest-v1",
- "package_name": name,
- "created_at": datetime.now(timezone.utc).isoformat(),
- "artifact_source_commit": artifact_commit,
- "final_dev_commit": final_dev_commit,
- "source_closure_unchanged": source_closure_unchanged,
- "verification_scope": "offline",
- "hardware_validation": "not_run",
- "bitstream_sha256": bitstream_sha256,
- "resources": {
- "lut": utilization.get("lut", {}).get("used"),
- "register": utilization.get("reg", {}).get("used"),
- "packed_slice": resources_section.get("packing", {}).get("total_slices"),
- "bram": utilization.get("bram", {}).get("used"),
- "dsp": utilization.get("dsp", {}).get("used"),
- },
- "timing": {
- "fmax_mhz": timing.get("fmax_mhz"),
- "setup_slack_ns": timing.get("worst_setup_slack_ns"),
- "hold_slack_ns": timing.get("worst_hold_slack_ns"),
- },
- }
- sha256_entries: list[str] = []
- def add_and_hash(src: Path, arcname: str) -> None:
- _add_file(zipf, src, arcname)
- sha256_entries.append(f"{_sha256_file(src)} {arcname}")
- def add_text_and_hash(text: str, arcname: str) -> None:
- _add_text(zipf, text, arcname)
- sha256_entries.append(f"{hashlib.sha256(text.encode('utf-8')).hexdigest()} {arcname}")
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
- # Bitstream and provenance
- add_and_hash(bitstream_path, "fw.bit")
- add_text_and_hash(bitstream_sha256, "BITSTREAM-SHA256.txt")
- add_text_and_hash(artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt")
- add_text_and_hash(final_dev_commit, "FINAL-DEV-COMMIT.txt")
- add_text_and_hash(
- "true" if source_closure_unchanged else "false",
- "SOURCE-CLOSURE-UNCHANGED.txt",
- )
- # Final TD report and selected report files
- add_and_hash(td_report_path, "td/final_td_report.json")
- for stage, stage_dir in REPORT_DIRS:
- if stage_dir.is_dir():
- for item in stage_dir.iterdir():
- if item.is_file() and item.suffix.casefold() in {
- ".rpt", ".timing", ".area", ".qor", ".log"
- }:
- add_and_hash(item, f"td/{stage}/{item.name}")
- # Project contract and protocol
- add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json")
- add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md")
- add_and_hash(ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md")
- # Generated artifacts
- for gen in (ROOT / "src" / "generated").iterdir():
- if gen.is_file():
- add_and_hash(gen, f"src/generated/{gen.name}")
- # Constraints and TD inputs
- for adc in (ROOT / "constraints").iterdir():
- if adc.is_file():
- add_and_hash(adc, f"constraints/{adc.name}")
- for td_item in (ROOT / "td").rglob("*"):
- if td_item.is_file():
- rel = td_item.relative_to(ROOT / "td")
- if rel.parts and rel.parts[0] == "build":
- continue
- arcname = "td/" + "/".join(rel.parts)
- add_and_hash(td_item, arcname)
- # Source closure manifest
- add_and_hash(ROOT / "config" / "source_closure.json", "config/source_closure.json")
- # Optional verification/matrix evidence
- if evidence_dir is not None and evidence_dir.is_dir():
- for ev_file in evidence_dir.rglob("*"):
- if ev_file.is_file():
- arcname = "evidence/" + "/".join(ev_file.relative_to(evidence_dir).parts)
- add_and_hash(ev_file, arcname)
- # Manifest and SHA256SUMS
- manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
- add_text_and_hash(manifest_text, "PACKAGE-MANIFEST.json")
- add_text_and_hash("\n".join(sha256_entries) + "\n", "SHA256SUMS.txt")
- return zip_path
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
- parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
- parser.add_argument("--artifact-commit", required=True)
- parser.add_argument("--final-dev-commit", required=True)
- parser.add_argument("--source-closure-unchanged", action="store_true")
- parser.add_argument("--bitstream", type=Path, default=BITSTREAM)
- parser.add_argument("--td-report", type=Path, default=TD_REPORT)
- parser.add_argument("--evidence-dir", type=Path, default=None)
- args = parser.parse_args(argv)
- try:
- path = build_firmware_package(
- output_dir=args.output_dir,
- package_name=args.package_name,
- artifact_commit=args.artifact_commit,
- final_dev_commit=args.final_dev_commit,
- source_closure_unchanged=args.source_closure_unchanged,
- bitstream_path=args.bitstream,
- td_report_path=args.td_report,
- evidence_dir=args.evidence_dir,
- )
- except FileNotFoundError as exc:
- print(f"blocked: {exc}", file=sys.stderr)
- return 1
- print(json.dumps({"status": "pass", "package": str(path), "bitstream": str(BITSTREAM)}, indent=2))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|