package_target.py 33 KB

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