package_target.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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_manual import generate as generate_6400_manual
  21. from tools.run_6400_td import (
  22. EXPECTED_UNBOUND_PORTS,
  23. HARDWARE_PROFILES,
  24. input_manifest as td_input_manifest,
  25. source_closure as td_source_closure,
  26. )
  27. from tools.target_registry import ROOT, load_source_closure, release_blocked, resolve_target
  28. from tools import package_6400_canonical
  29. CANDIDATE_NOTICE_ZH_CN = "UART + Host-I2C logic-bound TD候选;Pull-up装配和真实硬件验证仍为 NOT RUN"
  30. DO_NOT_PROGRAM_LINE = "DO NOT PROGRAM / 不要烧录"
  31. PRODUCTION_PROGRAM_LINE = "UART + HOST-I2C LOGIC-BOUND TD PASS / HARDWARE NOT RUN"
  32. IDENTIFICATION_PROGRAM_LINE = "IDENTIFICATION ONLY / NOT PRODUCTION / HARDWARE NOT RUN"
  33. CONTROL_DEPLOYMENT_STATUS = "TD_QUALIFIED_HARDWARE_NOT_RUN"
  34. IDENTIFICATION_DEPLOYMENT_STATUS = (
  35. "IDENTIFICATION_ONLY_RS232_ONLY_HARDWARE_NOT_RUN"
  36. )
  37. FORBIDDEN_PROGRAM_INSTRUCTIONS = (
  38. "Erase/Program",
  39. "执行 Erase",
  40. "执行 Program",
  41. "JTAG 下载器",
  42. )
  43. def _sha256(path: Path) -> str:
  44. digest = hashlib.sha256()
  45. with path.open("rb") as handle:
  46. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  47. digest.update(chunk)
  48. return digest.hexdigest()
  49. def _expected_deployment_status(profile_name: str) -> str:
  50. return (
  51. CONTROL_DEPLOYMENT_STATUS
  52. if bool(HARDWARE_PROFILES[profile_name]["production"])
  53. else IDENTIFICATION_DEPLOYMENT_STATUS
  54. )
  55. def _contract_sha256() -> str:
  56. payload = json.loads(
  57. (ROOT / "generated/6400/host-contract.json").read_text(encoding="utf-8")
  58. )
  59. value = payload.get("contract_sha256")
  60. if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
  61. raise SystemExit("6400 package blocked: invalid generated contract SHA-256")
  62. return value
  63. def _git(repo: Path, *args: str) -> str:
  64. try:
  65. return subprocess.check_output(["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL).strip()
  66. except (OSError, subprocess.CalledProcessError):
  67. return os.environ.get("PROD2U_COMMIT", "unknown")
  68. def _add(zipf: zipfile.ZipFile, src: Path, dest: str, sums: dict[str, str]) -> None:
  69. zipf.write(src, dest, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
  70. sums[dest] = _sha256(src)
  71. def _check_active_6400_generated() -> None:
  72. expected = generate_6400_manual()
  73. drift = [
  74. str(path.relative_to(ROOT))
  75. for path, content in expected.items()
  76. if not path.is_file() or path.read_bytes() != content
  77. ]
  78. if drift:
  79. raise SystemExit("6400 package blocked: active generated contract drift: " + ", ".join(drift))
  80. def _resolve_6400_profile(target_name: str, profile_name: str | None) -> str:
  81. if target_name in HARDWARE_PROFILES:
  82. if profile_name is not None and profile_name != target_name:
  83. raise SystemExit("6400 package blocked: target/profile mismatch")
  84. return target_name
  85. if target_name != "6400" or profile_name not in HARDWARE_PROFILES:
  86. raise SystemExit(
  87. "6400 package blocked: explicitly select --profile 6400-front-rear"
  88. )
  89. return profile_name
  90. def _validated_td_bitstream(
  91. profile_name: str, receipt_path: Path | None, package_commit: str
  92. ) -> tuple[Path, dict[str, object]]:
  93. if receipt_path is None or not receipt_path.is_file():
  94. raise SystemExit("6400 firmware package blocked: explicit --td-receipt is required")
  95. receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
  96. profile = HARDWARE_PROFILES[profile_name]
  97. project_path = ROOT / str(profile["project"])
  98. closure_path = ROOT / str(profile["closure"])
  99. current_inputs = td_input_manifest(profile_name)
  100. source_manifest_sha256 = hashlib.sha256(
  101. json.dumps(current_inputs, sort_keys=True, separators=(",", ":")).encode()
  102. ).hexdigest()
  103. expected = {
  104. "schema": "prod2u-6400-td-receipt-v1",
  105. "status": "PASS",
  106. "profile": profile_name,
  107. "project": str(profile["project"]),
  108. "source_closure": str(profile["closure"]),
  109. "production": bool(profile["production"]),
  110. "stimulus": bool(profile["stimulus"]),
  111. "simulation_only": False,
  112. "artifact_basename": str(profile["artifact_basename"]),
  113. "timing_pass_25mhz": True,
  114. "project_sha256": _sha256(project_path),
  115. "source_closure_sha256": _sha256(closure_path),
  116. "source_manifest_sha256": source_manifest_sha256,
  117. "inputs": current_inputs,
  118. "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS),
  119. "deployment_status": _expected_deployment_status(profile_name),
  120. }
  121. mismatches = [
  122. f"{key}: expected {value!r}, got {receipt.get(key)!r}"
  123. for key, value in expected.items()
  124. if receipt.get(key) != value
  125. ]
  126. if mismatches:
  127. raise SystemExit("6400 firmware package blocked: TD receipt mismatch: " + "; ".join(mismatches))
  128. source_commit = receipt.get("commit")
  129. if not isinstance(source_commit, str) or not re.fullmatch(
  130. r"[0-9a-f]{40}", source_commit
  131. ):
  132. raise SystemExit(
  133. "6400 firmware package blocked: TD receipt has invalid source commit"
  134. )
  135. if not re.fullmatch(r"[0-9a-f]{40}", package_commit):
  136. raise SystemExit(
  137. "6400 firmware package blocked: exact package commit is unavailable"
  138. )
  139. warning_audit = receipt.get("warning_audit")
  140. expected_ports = list(EXPECTED_UNBOUND_PORTS)
  141. if not isinstance(warning_audit, dict) or any(
  142. warning_audit.get(key) != value
  143. for key, value in {
  144. "status": "PASS",
  145. "expected_unbound_ports": expected_ports,
  146. "observed_unbound_ports": expected_ports,
  147. "unexpected_unbound_ports": [],
  148. "missing_expected_unbound_ports": [],
  149. }.items()
  150. ):
  151. raise SystemExit(
  152. "6400 firmware package blocked: TD warning audit mismatch"
  153. )
  154. bitstream_value = receipt.get("bitstream")
  155. if not isinstance(bitstream_value, str) or not bitstream_value:
  156. raise SystemExit("6400 firmware package blocked: TD receipt has no bitstream")
  157. bitstream = Path(bitstream_value)
  158. if not bitstream.is_absolute():
  159. bitstream = receipt_path.parent / bitstream
  160. expected_name = f"{profile['artifact_basename']}.bit"
  161. if bitstream.name != expected_name or not bitstream.is_file() or bitstream.stat().st_size == 0:
  162. raise SystemExit("6400 firmware package blocked: receipt bitstream is missing or misnamed")
  163. if receipt.get("bitstream_sha256") != _sha256(bitstream):
  164. raise SystemExit("6400 firmware package blocked: receipt bitstream SHA-256 mismatch")
  165. return bitstream.resolve(), receipt
  166. def build_target_package(
  167. target_name: str,
  168. kind: str,
  169. output_dir: Path,
  170. include_reference: bool = False,
  171. *,
  172. profile_name: str | None = None,
  173. td_receipt: Path | None = None,
  174. ) -> Path:
  175. is_6400 = target_name == "6400" or target_name.startswith("6400-")
  176. receipt_payload: dict[str, object] | None = None
  177. expanded_closure: dict[str, object] | None = None
  178. hardware_validation = "NOT RUN"
  179. known_unbound_ports: tuple[str, ...] = ()
  180. deployment_status: str | None = None
  181. source_commit: str | None = None
  182. if is_6400:
  183. selected_profile = _resolve_6400_profile(target_name, profile_name)
  184. profile = HARDWARE_PROFILES[selected_profile]
  185. _check_active_6400_generated()
  186. project_path = ROOT / str(profile["project"])
  187. closure_path = ROOT / str(profile["closure"])
  188. generated_dir = ROOT / "generated/6400"
  189. project = json.loads(project_path.read_text(encoding="utf-8"))
  190. sources, _closure_inputs = td_source_closure(selected_profile)
  191. top_module = str(project["top"])
  192. project_id = selected_profile
  193. target_alias = "6400"
  194. package_label = selected_profile
  195. blocked, pins = False, ()
  196. expanded_closure = {
  197. "schema": "prod2u-source-closure-expanded-v1",
  198. "project_id": selected_profile,
  199. "top_module": top_module,
  200. "sources": sources,
  201. }
  202. else:
  203. target = resolve_target(target_name)
  204. generate_named_target(target.alias)
  205. project_path = target.project_config
  206. closure_path = target.source_closure
  207. generated_dir = target.generated_dir
  208. project = json.loads(project_path.read_text(encoding="utf-8"))
  209. blocked, pins = release_blocked(target, project)
  210. sources = list(load_source_closure(target))
  211. top_module = target.top_module
  212. project_id = target.project_id
  213. target_alias = target.alias
  214. package_label = target.alias
  215. selected_profile = target.profile
  216. if kind == "firmware" and blocked:
  217. raise SystemExit(
  218. "release_blocked\n" + "\n".join(f"{name} pin unresolved" for name in pins)
  219. )
  220. commit = _git(ROOT, "rev-parse", "HEAD")
  221. bitstream_path: Path | None = None
  222. if kind == "firmware" and is_6400:
  223. if not re.fullmatch(r"[0-9a-f]{40}", commit):
  224. raise SystemExit("6400 firmware package blocked: exact Git commit is unavailable")
  225. bitstream_path, receipt_payload = _validated_td_bitstream(
  226. selected_profile, td_receipt, commit
  227. )
  228. ports_value = receipt_payload["known_unbound_ports"]
  229. status_value = receipt_payload["deployment_status"]
  230. assert isinstance(ports_value, list)
  231. assert all(isinstance(port, str) for port in ports_value)
  232. assert isinstance(status_value, str)
  233. known_unbound_ports = tuple(ports_value)
  234. deployment_status = status_value
  235. source_commit_value = receipt_payload["commit"]
  236. assert isinstance(source_commit_value, str)
  237. source_commit = source_commit_value
  238. # Hardware NOT RUN is an evidence boundary, not a source/TD packaging
  239. # failure. A logic-bound UART + Host-I2C image may be handed to the
  240. # user for programming while remaining explicitly unvalidated on real
  241. # hardware. Identification is never Production, but may be programmed
  242. # for the finite stimulus workflow.
  243. blocked = bool(known_unbound_ports)
  244. pins = known_unbound_ports
  245. run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  246. name = f"prod2u-{package_label}-{kind}-{commit[:12]}-{run_id}"
  247. output_dir.mkdir(parents=True, exist_ok=True)
  248. zip_path = output_dir / f"{name}.zip"
  249. manifest = {
  250. "schema": "prod2u-target-package-v1",
  251. "target_alias": target_alias,
  252. "profile": selected_profile,
  253. "firmware_role": "production" if is_6400 else "legacy",
  254. "project_id": project_id,
  255. "top": top_module,
  256. "kind": kind,
  257. "commit": commit,
  258. "run_id": run_id,
  259. "project_config_sha256": _sha256(project_path),
  260. "source_closure_sha256": _sha256(closure_path),
  261. "source_manifest_sha256": (
  262. receipt_payload.get("source_manifest_sha256")
  263. if receipt_payload is not None
  264. else None
  265. ),
  266. "bitstream_sha256": _sha256(bitstream_path) if bitstream_path else None,
  267. "hardware_validation": hardware_validation,
  268. "release_blocked": blocked,
  269. "unresolved_pins": list(pins),
  270. "include_reference": include_reference,
  271. }
  272. if is_6400:
  273. manifest.update(
  274. {
  275. "contract_sha256": _contract_sha256(),
  276. "production": bool(profile["production"]),
  277. "stimulus": bool(profile["stimulus"]),
  278. "simulation_only": False,
  279. }
  280. )
  281. if is_6400 and kind == "firmware":
  282. manifest.update(
  283. {
  284. "candidate_notice_zh_CN": CANDIDATE_NOTICE_ZH_CN,
  285. "candidate_only": hardware_validation != "PASS",
  286. "td_programmable": not blocked,
  287. # The image is safe to hand off for user-controlled programming
  288. # after TD passes, but real hardware acceptance remains NOT RUN.
  289. "deployable": False,
  290. "production_deployable": False,
  291. "identification_programmable": (
  292. not blocked and not bool(profile["production"])
  293. ),
  294. "hardware_validated": hardware_validation == "PASS",
  295. "deployment_status": deployment_status,
  296. "source_commit": source_commit,
  297. "package_commit": commit,
  298. "known_unbound_ports": list(known_unbound_ports),
  299. "unresolved_ports": list(known_unbound_ports),
  300. }
  301. )
  302. with tempfile.TemporaryDirectory() as tmp:
  303. stage = Path(tmp)
  304. (stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  305. if is_6400 and kind == "firmware" and blocked:
  306. (stage / "CANDIDATE-NOTICE.zh-CN.txt").write_text(
  307. DO_NOT_PROGRAM_LINE + "\n"
  308. + CANDIDATE_NOTICE_ZH_CN + "\n"
  309. + f"未冻结端口:{', '.join(known_unbound_ports)}\n"
  310. + f"部署状态:{deployment_status}\n"
  311. + f"硬件验证:{hardware_validation}\n",
  312. encoding="utf-8",
  313. )
  314. shutil.copy2(project_path, stage / "project.json")
  315. shutil.copy2(closure_path, stage / "source-closure.json")
  316. if expanded_closure is not None:
  317. (stage / "source-closure-expanded.json").write_text(
  318. json.dumps(expanded_closure, indent=2, sort_keys=True) + "\n",
  319. encoding="utf-8",
  320. )
  321. if receipt_payload is not None:
  322. source_manifest_bytes = json.dumps(
  323. receipt_payload["inputs"],
  324. sort_keys=True,
  325. separators=(",", ":"),
  326. ).encode()
  327. (stage / "source-manifest.json").write_bytes(source_manifest_bytes)
  328. gen_dir = stage / ("generated/6400" if is_6400 else "generated")
  329. if generated_dir.is_dir():
  330. shutil.copytree(generated_dir, gen_dir)
  331. src_dir = stage / "src"
  332. src_dir.mkdir()
  333. for rel in sources:
  334. dest = stage / rel
  335. dest.parent.mkdir(parents=True, exist_ok=True)
  336. shutil.copy2(ROOT / rel, dest)
  337. if kind in ("source", "review"):
  338. for category_dir in ("contracts", "config", "docs"):
  339. c_path = ROOT / category_dir
  340. if c_path.is_dir():
  341. shutil.copytree(c_path, stage / category_dir, dirs_exist_ok=True)
  342. for c_file in (ROOT / "constraints").glob("prod2u_6400*"):
  343. dest = stage / "constraints" / c_file.name
  344. dest.parent.mkdir(parents=True, exist_ok=True)
  345. shutil.copy2(c_file, dest)
  346. for td_file in (ROOT / "td").rglob("*"):
  347. if td_file.is_file() and not any(tok in td_file.parts or tok in td_file.name for tok in ("mrdimm", "identification", "sim-debug")):
  348. dest = stage / td_file.relative_to(ROOT)
  349. dest.parent.mkdir(parents=True, exist_ok=True)
  350. shutil.copy2(td_file, dest)
  351. for t_file in (ROOT / "tests").rglob("*"):
  352. if t_file.is_file() and not any(tok in t_file.parts or tok in t_file.name for tok in ("mrdimm", "identification", "sim-debug", "__pycache__")):
  353. dest = stage / t_file.relative_to(ROOT)
  354. dest.parent.mkdir(parents=True, exist_ok=True)
  355. shutil.copy2(t_file, dest)
  356. for tool_file in (ROOT / "tools").rglob("*"):
  357. if tool_file.is_file() and not any(tok in tool_file.parts or tok in tool_file.name for tok in ("mrdimm", "identification", "sim-debug", "__pycache__")):
  358. dest = stage / tool_file.relative_to(ROOT)
  359. dest.parent.mkdir(parents=True, exist_ok=True)
  360. shutil.copy2(tool_file, dest)
  361. for root_meta in ("pyproject.toml", "AGENTS.md", "RECOVERY_STATE.md", "TASK_PLAN.json", "RESULTS.json"):
  362. if (ROOT / root_meta).is_file():
  363. shutil.copy2(ROOT / root_meta, stage / root_meta)
  364. if bitstream_path is not None:
  365. bitstream_name = bitstream_path.name
  366. shutil.copy2(bitstream_path, stage / bitstream_name)
  367. (stage / "BITSTREAM-SHA256.txt").write_text(
  368. f"{_sha256(bitstream_path)} {bitstream_name}\n",
  369. encoding="ascii",
  370. )
  371. role = "生产"
  372. instruction_header = (
  373. DO_NOT_PROGRAM_LINE
  374. if blocked
  375. else (
  376. PRODUCTION_PROGRAM_LINE
  377. if is_6400
  378. else IDENTIFICATION_PROGRAM_LINE
  379. )
  380. )
  381. (stage / "FLASH-INSTRUCTIONS.zh-CN.txt").write_text(
  382. instruction_header + "\n"
  383. + CANDIDATE_NOTICE_ZH_CN + "\n\n"
  384. + f"6400 {role}固件审核说明\n"
  385. "========================\n"
  386. "目标器件:EF2L45BG256B(6400 前后独立温控)\n"
  387. f"固件文件:{bitstream_name}\n"
  388. "请审核 BITSTREAM-SHA256.txt 与 TD-BUILD-RECEIPT.json 后再冻结制品。\n"
  389. f"Host 串口仅使用 CON78 RS-232 921600 8N1;每条合法命令先独立 ACK;Profile={selected_profile}。\n"
  390. "本包只包含 6400 固件,不能用于 MRDIMM 门控板。\n"
  391. + "本固件对保留的 SET_STIMULUS 返回 UNSUPPORTED NACK。\n"
  392. + "\n"
  393. "注意:本次交付未执行真实 JTAG/硬件烧录,硬件验证状态为 NOT RUN。\n",
  394. encoding="utf-8",
  395. )
  396. assert receipt_payload is not None
  397. (stage / "TD-BUILD-RECEIPT.json").write_text(
  398. json.dumps(receipt_payload, indent=2, sort_keys=True) + "\n",
  399. encoding="utf-8",
  400. )
  401. # Preserve original area reports, timing reports, and toolchain logs
  402. reports_dir = stage / "reports"
  403. reports_dir.mkdir(parents=True, exist_ok=True)
  404. metrics = receipt_payload.get("metrics", {})
  405. for rep in metrics.get("area_reports", []):
  406. p = Path(rep)
  407. if p.is_file():
  408. shutil.copy2(p, reports_dir / p.name)
  409. timing_rep = metrics.get("timing_report")
  410. if timing_rep and Path(timing_rep).is_file():
  411. shutil.copy2(Path(timing_rep), reports_dir / Path(timing_rep).name)
  412. for st_info in receipt_payload.get("stages", {}).values():
  413. log_p = Path(st_info.get("log", ""))
  414. if log_p.is_file():
  415. shutil.copy2(log_p, reports_dir / log_p.name)
  416. if include_reference:
  417. ref = ROOT / "reference"
  418. if ref.is_dir():
  419. shutil.copytree(ref, stage / "reference", dirs_exist_ok=True)
  420. # Exclusion packaging enforcement: Candidates = Included ∪ Excluded (disjoint)
  421. from tools import exclusion_packager
  422. universe = exclusion_packager.scan_candidate_universe(ROOT)
  423. included_from_root = {}
  424. for p in stage.rglob("*"):
  425. if p.is_file():
  426. rel = p.relative_to(stage).as_posix()
  427. if rel in universe:
  428. included_from_root[rel] = universe[rel]
  429. elif (ROOT / rel).is_file():
  430. included_from_root[rel] = {"path": rel, "size": (ROOT / rel).stat().st_size}
  431. rules = exclusion_packager.get_6400_v2_exclusion_rules(kind)
  432. exclusions = []
  433. for rel_path, item in sorted(universe.items()):
  434. if rel_path in included_from_root:
  435. continue
  436. matched = False
  437. for pred, type_str, reason_str in rules:
  438. if pred(rel_path, item):
  439. exclusions.append({
  440. "path": rel_path,
  441. "type": type_str,
  442. "reason": reason_str,
  443. "size": item["size"],
  444. })
  445. matched = True
  446. break
  447. if not matched:
  448. exclusions.append({
  449. "path": rel_path,
  450. "type": "unselected",
  451. "reason": f"File not selected for {kind} package",
  452. "size": item["size"],
  453. })
  454. assert len(included_from_root) + len(exclusions) == len(universe), "Partition count mismatch"
  455. assert set(included_from_root.keys()).isdisjoint({x["path"] for x in exclusions}), "Overlap detected"
  456. excl_payload = {
  457. "schema": "prod2u-package-exclusions-v2",
  458. "scope": f"{selected_profile} {kind} package",
  459. "total_candidates": len(universe),
  460. "included_count": len(included_from_root),
  461. "excluded_count": len(exclusions),
  462. "exclusions": exclusions,
  463. }
  464. (stage / "EXCLUSIONS.json").write_text(json.dumps(excl_payload, indent=2) + "\n", encoding="utf-8")
  465. shutil.copy2(ROOT / "tools/package_archive.py", stage / "PACKAGE-SELF-CHECK.py")
  466. sums: dict[str, str] = {}
  467. if zip_path.exists():
  468. zip_path.unlink()
  469. with zipfile.ZipFile(
  470. zip_path,
  471. "w",
  472. compression=zipfile.ZIP_DEFLATED,
  473. compresslevel=9,
  474. allowZip64=True,
  475. ) as zipf:
  476. for path in sorted(stage.rglob("*")):
  477. if path.is_file():
  478. _add(zipf, path, path.relative_to(stage).as_posix(), sums)
  479. zipf.writestr(
  480. "SHA256SUMS",
  481. "".join(f"{digest} {name}\n" for name, digest in sorted(sums.items())),
  482. compress_type=zipfile.ZIP_DEFLATED,
  483. compresslevel=9,
  484. )
  485. _selftest(zip_path)
  486. return zip_path
  487. def _selftest(zip_path: Path) -> None:
  488. with tempfile.TemporaryDirectory() as tmp:
  489. dest = Path(tmp) / "unpacked"
  490. dest.mkdir()
  491. with zipfile.ZipFile(zip_path) as zipf:
  492. for info in zipf.infolist():
  493. if info.filename.startswith("/") or ".." in Path(info.filename).parts:
  494. raise SystemExit(f"unsafe zip path: {info.filename}")
  495. zipf.extractall(dest)
  496. manifest = json.loads((dest / "manifest.json").read_text(encoding="utf-8"))
  497. if manifest.get("hardware_validation") != "NOT RUN":
  498. raise SystemExit("package selftest: hardware_validation must be NOT RUN")
  499. sums = (dest / "SHA256SUMS").read_text(encoding="utf-8").splitlines()
  500. for line in sums:
  501. digest, name = line.split(" ", 1)
  502. observed = _sha256(dest / name)
  503. if observed != digest:
  504. raise SystemExit(f"hash mismatch {name}")
  505. if (dest / "EXCLUSIONS.json").is_file():
  506. excl_meta = json.loads((dest / "EXCLUSIONS.json").read_text(encoding="utf-8"))
  507. if "exclusions" in excl_meta:
  508. excl_paths = {x["path"] for x in excl_meta["exclusions"]}
  509. members = {path.relative_to(dest).as_posix() for path in dest.rglob("*") if path.is_file()}
  510. overlap = excl_paths.intersection(members)
  511. if overlap:
  512. raise SystemExit(f"package selftest: exclusion/inclusion overlap: {overlap}")
  513. for item in excl_meta["exclusions"]:
  514. if not all(k in item for k in ("path", "type", "reason", "size")):
  515. raise SystemExit(f"package selftest: invalid exclusion entry: {item.get('path')}")
  516. if "total_candidates" in excl_meta:
  517. if excl_meta["total_candidates"] != excl_meta.get("included_count", 0) + excl_meta.get("excluded_count", 0):
  518. raise SystemExit("package selftest: exclusion partition count mismatch")
  519. if manifest.get("target_alias") == "6400":
  520. profile_name = manifest.get("profile")
  521. if profile_name not in HARDWARE_PROFILES:
  522. raise SystemExit("package selftest: invalid 6400 hardware profile")
  523. members = [path.relative_to(dest).as_posix() for path in dest.rglob("*")]
  524. if any(name.startswith("src/generated/6400/") for name in members):
  525. raise SystemExit("package selftest: historical src/generated/6400 leaked")
  526. closure = json.loads(
  527. (dest / "source-closure-expanded.json").read_text(encoding="utf-8")
  528. )
  529. closure_text = "\n".join(closure["sources"])
  530. if "src/generated/6400" in closure_text or "prod2u_6400_front_back_top" in closure_text:
  531. raise SystemExit("package selftest: historical 6400 closure leaked")
  532. if manifest.get("target_alias") in ("6400", "6400-v2") and manifest.get("kind") == "firmware":
  533. profile_name = manifest["profile"]
  534. profile = HARDWARE_PROFILES[profile_name]
  535. expected_name = f"{profile['artifact_basename']}.bit"
  536. bit = dest / expected_name
  537. if not bit.is_file() or _sha256(bit) != manifest.get("bitstream_sha256"):
  538. raise SystemExit("package selftest: 6400 bitstream identity mismatch")
  539. receipt = json.loads(
  540. (dest / "TD-BUILD-RECEIPT.json").read_text(encoding="utf-8")
  541. )
  542. if receipt.get("profile") != profile_name or receipt.get(
  543. "bitstream_sha256"
  544. ) != manifest["bitstream_sha256"]:
  545. raise SystemExit("package selftest: TD receipt/profile identity mismatch")
  546. embedded_contract = json.loads(
  547. (dest / "generated/6400/host-contract.json").read_text(
  548. encoding="utf-8"
  549. )
  550. )
  551. if (
  552. manifest.get("contract_sha256")
  553. != embedded_contract.get("contract_sha256")
  554. or manifest.get("source_commit") != receipt.get("commit")
  555. or manifest.get("package_commit") != manifest.get("commit")
  556. or receipt.get("inputs") != td_input_manifest(profile_name)
  557. ):
  558. raise SystemExit("package selftest: firmware provenance mismatch")
  559. expected_input_sha = hashlib.sha256(
  560. json.dumps(
  561. receipt["inputs"], sort_keys=True, separators=(",", ":")
  562. ).encode()
  563. ).hexdigest()
  564. if (
  565. receipt.get("source_manifest_sha256") != expected_input_sha
  566. or receipt.get("project_sha256") != _sha256(dest / "project.json")
  567. or receipt.get("source_closure_sha256")
  568. != _sha256(dest / "source-closure.json")
  569. or manifest.get("source_closure_sha256")
  570. != receipt.get("source_closure_sha256")
  571. or manifest.get("source_manifest_sha256") != expected_input_sha
  572. or not (dest / "source-manifest.json").is_file()
  573. or _sha256(dest / "source-manifest.json") != expected_input_sha
  574. ):
  575. raise SystemExit("package selftest: TD input digest mismatch")
  576. receipt_ports = receipt.get("known_unbound_ports")
  577. expected_ports = list(EXPECTED_UNBOUND_PORTS)
  578. warning_audit = receipt.get("warning_audit")
  579. if (
  580. manifest.get("release_blocked") is not False
  581. or manifest.get("td_programmable") is not True
  582. or manifest.get("candidate_only") is not True
  583. or manifest.get("hardware_validated") is not False
  584. or manifest.get("deployable") is not False
  585. or manifest.get("production_deployable") is not False
  586. or manifest.get("identification_programmable")
  587. is not (not bool(profile["production"]))
  588. or receipt_ports != expected_ports
  589. or manifest.get("known_unbound_ports") != receipt_ports
  590. or manifest.get("unresolved_ports") != receipt_ports
  591. or manifest.get("unresolved_pins") != receipt_ports
  592. or receipt.get("deployment_status")
  593. != _expected_deployment_status(profile_name)
  594. or manifest.get("deployment_status")
  595. != receipt.get("deployment_status")
  596. or not isinstance(warning_audit, dict)
  597. or warning_audit.get("status") != "PASS"
  598. or warning_audit.get("observed_unbound_ports") != expected_ports
  599. ):
  600. raise SystemExit("package selftest: unsafe deployment gate mismatch")
  601. if (dest / "CANDIDATE-NOTICE.zh-CN.txt").exists():
  602. raise SystemExit("package selftest: stale release-block notice present")
  603. if (
  604. manifest.get("production") is not bool(profile["production"])
  605. or manifest.get("stimulus") is not bool(profile["stimulus"])
  606. or (not bool(profile["production"]) and manifest.get("deployable"))
  607. ):
  608. raise SystemExit("package selftest: firmware profile semantics mismatch")
  609. instructions = (dest / "FLASH-INSTRUCTIONS.zh-CN.txt").read_text(
  610. encoding="utf-8"
  611. )
  612. expected_header = (
  613. PRODUCTION_PROGRAM_LINE
  614. if bool(profile["production"])
  615. else IDENTIFICATION_PROGRAM_LINE
  616. )
  617. if (
  618. not instructions.startswith(expected_header)
  619. or "921600 8N1" not in instructions
  620. or "独立 ACK" not in instructions
  621. or any(token in instructions for token in FORBIDDEN_PROGRAM_INSTRUCTIONS)
  622. ):
  623. raise SystemExit("package selftest: Host UART/ACK contract missing")
  624. def main(argv: list[str] | None = None) -> int:
  625. parser = argparse.ArgumentParser()
  626. parser.add_argument("--target", required=True)
  627. parser.add_argument("--kind", choices=("source", "review", "firmware", "analysis-base", "analysis-current", "gui", "delivery"), default="source")
  628. parser.add_argument(
  629. "--profile",
  630. choices=tuple(HARDWARE_PROFILES),
  631. )
  632. parser.add_argument("--td-receipt", type=Path)
  633. parser.add_argument("--base-zip", type=Path)
  634. parser.add_argument("--gui-exe", type=Path)
  635. parser.add_argument("--gui-zip", type=Path)
  636. parser.add_argument("--status-json", type=Path)
  637. parser.add_argument("--output-dir", type=Path, default=ROOT / "dist")
  638. parser.add_argument("--include-reference", action="store_true")
  639. args = parser.parse_args(argv)
  640. if args.kind == "analysis-base":
  641. path = package_6400_canonical.package_base(args.output_dir)
  642. elif args.kind == "analysis-current":
  643. if args.base_zip is None:
  644. parser.error("--base-zip is required for analysis-current")
  645. path = package_6400_canonical.package_current(args.output_dir, args.base_zip)
  646. elif args.kind == "delivery":
  647. required = (args.td_receipt, args.gui_exe, args.gui_zip, args.status_json)
  648. if any(value is None for value in required):
  649. parser.error("delivery requires --td-receipt --gui-exe --gui-zip --status-json")
  650. path = package_6400_canonical.package_delivery(
  651. args.output_dir, args.td_receipt, args.gui_exe, args.gui_zip, args.status_json
  652. )
  653. elif args.kind == "gui":
  654. if args.gui_exe is None:
  655. parser.error("gui requires --gui-exe")
  656. path = package_6400_canonical.package_gui(args.output_dir, args.gui_exe)
  657. else:
  658. path = build_target_package(
  659. args.target,
  660. args.kind,
  661. args.output_dir,
  662. args.include_reference,
  663. profile_name=args.profile,
  664. td_receipt=args.td_receipt,
  665. )
  666. print(json.dumps({"status": "pass", "package": str(path), "sha256": _sha256(path)}, indent=2))
  667. return 0
  668. if __name__ == "__main__":
  669. raise SystemExit(main())