|
@@ -0,0 +1,306 @@
|
|
|
|
|
+#!/usr/bin/env python3
|
|
|
|
|
+"""Deterministic Base/Current/Delivery packager for 6400-front-rear."""
|
|
|
|
|
+
|
|
|
|
|
+from __future__ import annotations
|
|
|
|
|
+
|
|
|
|
|
+import hashlib
|
|
|
|
|
+import json
|
|
|
|
|
+import os
|
|
|
|
|
+import shutil
|
|
|
|
|
+import stat
|
|
|
|
|
+import subprocess
|
|
|
|
|
+import sys
|
|
|
|
|
+import tempfile
|
|
|
|
|
+import zipfile
|
|
|
|
|
+from pathlib import Path, PurePosixPath
|
|
|
|
|
+
|
|
|
|
|
+ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
+FIXED_TIME = (1980, 1, 1, 0, 0, 0)
|
|
|
|
|
+COMMON = (
|
|
|
|
|
+ "PACKAGE-MANIFEST.json",
|
|
|
|
|
+ "SHA256SUMS",
|
|
|
|
|
+ "PACKAGE-SELF-CHECK.py",
|
|
|
|
|
+ "START-HERE.zh-CN.md",
|
|
|
|
|
+ "EXCLUSIONS.json",
|
|
|
|
|
+)
|
|
|
|
|
+EXCLUSION_RULES = [
|
|
|
|
|
+ ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
|
|
|
|
|
+ "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
|
|
|
|
|
+ "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
|
|
|
|
|
+ "agent scratch/stale progress", "nested archives unless explicitly selected",
|
|
|
|
|
+]
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def sha_bytes(data: bytes) -> str:
|
|
|
|
|
+ return hashlib.sha256(data).hexdigest()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def sha_file(path: Path) -> str:
|
|
|
|
|
+ digest = hashlib.sha256()
|
|
|
|
|
+ with path.open("rb") as handle:
|
|
|
|
|
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
|
|
|
+ digest.update(chunk)
|
|
|
|
|
+ return digest.hexdigest()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def git(*args: str) -> str:
|
|
|
|
|
+ return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def clean_identity() -> tuple[str, str]:
|
|
|
|
|
+ if git("status", "--porcelain"):
|
|
|
|
|
+ raise SystemExit("canonical package requires an exact clean commit")
|
|
|
|
|
+ return git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def safe_name(name: str) -> str:
|
|
|
|
|
+ if not name or "\\" in name or name.startswith("/"):
|
|
|
|
|
+ raise ValueError(f"unsafe ZIP member: {name!r}")
|
|
|
|
|
+ parts = PurePosixPath(name).parts
|
|
|
|
|
+ if ".." in parts or "." in parts:
|
|
|
|
|
+ raise ValueError(f"unsafe ZIP member: {name!r}")
|
|
|
|
|
+ return name
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def role_for(path: str) -> str:
|
|
|
|
|
+ if path.startswith("generated/") or path.startswith("contracts/"):
|
|
|
|
|
+ return "contract"
|
|
|
|
|
+ if path.startswith("src/"):
|
|
|
|
|
+ return "rtl-source"
|
|
|
|
|
+ if path.startswith("tests/"):
|
|
|
|
|
+ return "verification"
|
|
|
|
|
+ if path.startswith("tools/"):
|
|
|
|
|
+ return "replay-tool"
|
|
|
|
|
+ if path.endswith(".bit"):
|
|
|
|
|
+ return "bitstream"
|
|
|
|
|
+ if path.endswith(".exe"):
|
|
|
|
|
+ return "offline-gui"
|
|
|
|
|
+ if "RECEIPT" in path or "STATUS" in path:
|
|
|
|
|
+ return "evidence"
|
|
|
|
|
+ return "metadata"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def read_paths(paths: list[str]) -> dict[str, bytes]:
|
|
|
|
|
+ out: dict[str, bytes] = {}
|
|
|
|
|
+ for relative in sorted(set(paths)):
|
|
|
|
|
+ safe_name(relative)
|
|
|
|
|
+ source = ROOT / relative
|
|
|
|
|
+ if not source.is_file() or source.is_symlink():
|
|
|
|
|
+ raise SystemExit(f"selected package path missing or unsafe: {relative}")
|
|
|
|
|
+ out[relative] = source.read_bytes()
|
|
|
|
|
+ return out
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def production_sources() -> list[str]:
|
|
|
|
|
+ payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
|
|
|
|
|
+ return list(payload["sources"])
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def replay_paths() -> list[str]:
|
|
|
|
|
+ payload = json.loads((ROOT / "products/6400-front-rear/analysis-replay-closure.json").read_text())
|
|
|
|
|
+ return list(payload["paths"])
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def base_paths() -> list[str]:
|
|
|
|
|
+ stable_sources = [
|
|
|
|
|
+ path for path in production_sources()
|
|
|
|
|
+ if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
|
|
|
|
|
+ ]
|
|
|
|
|
+ stable_tools = [
|
|
|
|
|
+ "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
|
|
|
|
|
+ "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
|
|
|
|
|
+ "tools/generate_6400_v1.py", "tools/target_registry.py", "tools/run_6400_td.py",
|
|
|
|
|
+ "tools/package_target.py", "tools/package_6400_canonical.py",
|
|
|
|
|
+ "tests/unit/test_6400_closure_separation.py",
|
|
|
|
|
+ ]
|
|
|
|
|
+ board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml"]
|
|
|
|
|
+ return sorted(set(stable_sources + stable_tools + board_contracts))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def current_paths() -> list[str]:
|
|
|
|
|
+ base = set(base_paths())
|
|
|
|
|
+ product = [
|
|
|
|
|
+ "contracts/6400-fixed-point.yaml", "contracts/6400-snapshot.yaml", "contracts/6400-wire.yaml",
|
|
|
|
|
+ "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
|
|
|
|
|
+ "products/6400-front-rear/analysis-replay-closure.json", "projects/registry.json",
|
|
|
|
|
+ ]
|
|
|
|
|
+ generated = [p.relative_to(ROOT).as_posix() for p in (ROOT / "generated/6400").glob("*") if p.is_file()]
|
|
|
|
|
+ specific_sources = [p for p in production_sources() if p not in base]
|
|
|
|
|
+ focused = [p for p in replay_paths() if p not in base]
|
|
|
|
|
+ focused.append("tests/unit/test_6400_canonical_packages.py")
|
|
|
|
|
+ return sorted(set(product + generated + specific_sources + focused))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def fingerprint(files: dict[str, bytes]) -> str:
|
|
|
|
|
+ lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
|
|
|
|
|
+ return sha_bytes("".join(lines).encode())[:12]
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+SELF_CHECK = r'''#!/usr/bin/env python3
|
|
|
|
|
+import hashlib,json,pathlib,sys,zipfile
|
|
|
|
|
+root=pathlib.Path(__file__).resolve().parent
|
|
|
|
|
+def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
|
|
|
|
|
+for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
|
|
|
|
|
+ digest,name=line.split(' ',1); p=root/name
|
|
|
|
|
+ if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
|
|
|
|
|
+manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
|
|
|
|
|
+for item in manifest['items']:
|
|
|
|
|
+ p=root/item['path']
|
|
|
|
|
+ if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
|
|
|
|
|
+ raise SystemExit('MANIFEST_MISMATCH '+item['path'])
|
|
|
|
|
+if manifest['profile']=='current' and not (root/'.base-overlay-present').exists():
|
|
|
|
|
+ print('BASE_REQUIRED'); raise SystemExit(3)
|
|
|
|
|
+print('PASS')
|
|
|
|
|
+'''
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
|
|
|
|
|
+ items = [
|
|
|
|
|
+ {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
|
|
|
|
|
+ "source_commit": commit, "source_tree": tree}
|
|
|
|
|
+ for name, data in sorted(selected.items())
|
|
|
|
|
+ ]
|
|
|
|
|
+ manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
|
|
|
|
|
+ "product": "6400-front-rear", "source_commit": commit,
|
|
|
|
|
+ "source_tree": tree, "items": items, **extra}
|
|
|
|
|
+ selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
|
|
|
|
|
+ selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
|
|
|
|
|
+ selected["START-HERE.zh-CN.md"] = (
|
|
|
|
|
+ f"# 6400-front-rear {profile}\n\n先运行 `python3 PACKAGE-SELF-CHECK.py`。"
|
|
|
|
|
+ "硬件、COM、JTAG 均未运行;不得把分析证据当作真机验收。\n"
|
|
|
|
|
+ ).encode()
|
|
|
|
|
+ selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
|
|
|
|
|
+ "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
|
|
|
|
|
+ selected["SHA256SUMS"] = "".join(
|
|
|
|
|
+ f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
|
|
|
|
|
+ ).encode()
|
|
|
|
|
+ return selected
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def write_zip(path: Path, files: dict[str, bytes]) -> Path:
|
|
|
|
|
+ path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
+ if path.exists():
|
|
|
|
|
+ path.unlink()
|
|
|
|
|
+ seen: set[str] = set()
|
|
|
|
|
+ with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
|
|
|
|
+ for name, data in sorted(files.items()):
|
|
|
|
|
+ safe_name(name)
|
|
|
|
|
+ if name in seen:
|
|
|
|
|
+ raise SystemExit(f"duplicate ZIP member: {name}")
|
|
|
|
|
+ seen.add(name)
|
|
|
|
|
+ info = zipfile.ZipInfo(name, FIXED_TIME)
|
|
|
|
|
+ info.create_system = 3
|
|
|
|
|
+ info.external_attr = (stat.S_IFREG | (0o755 if name == "PACKAGE-SELF-CHECK.py" else 0o644)) << 16
|
|
|
|
|
+ archive.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
|
|
|
|
|
+ verify_zip(path)
|
|
|
|
|
+ return path
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def verify_zip(path: Path) -> None:
|
|
|
|
|
+ with zipfile.ZipFile(path) as archive:
|
|
|
|
|
+ names = archive.namelist()
|
|
|
|
|
+ if names != sorted(names) or len(names) != len(set(names)):
|
|
|
|
|
+ raise SystemExit("ZIP members are not sorted/unique")
|
|
|
|
|
+ for name in names:
|
|
|
|
|
+ safe_name(name)
|
|
|
|
|
+ for line in archive.read("SHA256SUMS").decode().splitlines():
|
|
|
|
|
+ digest, name = line.split(" ", 1)
|
|
|
|
|
+ if sha_bytes(archive.read(name)) != digest:
|
|
|
|
|
+ raise SystemExit(f"package hash mismatch: {name}")
|
|
|
|
|
+ if not set(COMMON).issubset(names):
|
|
|
|
|
+ raise SystemExit("package common files missing")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def extract_safe(path: Path, dest: Path) -> None:
|
|
|
|
|
+ with zipfile.ZipFile(path) as archive:
|
|
|
|
|
+ for info in archive.infolist():
|
|
|
|
|
+ safe_name(info.filename)
|
|
|
|
|
+ archive.extractall(dest)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def package_base(output: Path) -> Path:
|
|
|
|
|
+ commit, tree = clean_identity()
|
|
|
|
|
+ selected = read_paths(base_paths())
|
|
|
|
|
+ base_id = fingerprint(selected)
|
|
|
|
|
+ selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v1",
|
|
|
|
|
+ "raw_reference_included": False, "source_status": "pointer-only",
|
|
|
|
|
+ "board": "FCB V1.1"}, indent=2, sort_keys=True) + "\n").encode()
|
|
|
|
|
+ payload = common_payload("base", commit, tree, selected, {"base_id": base_id})
|
|
|
|
|
+ return write_zip(output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip", payload)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
|
|
|
|
|
+ verify_zip(base_zip)
|
|
|
|
|
+ with zipfile.ZipFile(base_zip) as archive:
|
|
|
|
|
+ manifest_bytes = archive.read("PACKAGE-MANIFEST.json")
|
|
|
|
|
+ manifest = json.loads(manifest_bytes)
|
|
|
|
|
+ if manifest.get("profile") != "base":
|
|
|
|
|
+ raise SystemExit("selected Base package is not profile=base")
|
|
|
|
|
+ return str(manifest["base_id"]), manifest, sha_bytes(manifest_bytes)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def package_current(output: Path, base_zip: Path) -> Path:
|
|
|
|
|
+ commit, tree = clean_identity()
|
|
|
|
|
+ base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
|
|
|
|
|
+ expected = fingerprint(read_paths(base_paths()))
|
|
|
|
|
+ if expected != base_id:
|
|
|
|
|
+ raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
|
|
|
|
|
+ selected = read_paths(current_paths())
|
|
|
|
|
+ required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
|
|
|
|
|
+ "base_zip_sha256": sha_file(base_zip),
|
|
|
|
|
+ "base_manifest_sha256": base_manifest_sha,
|
|
|
|
|
+ "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
|
|
|
|
|
+ selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
|
|
|
|
|
+ selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
|
|
|
|
|
+ payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
|
|
|
|
|
+ path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
|
|
|
|
|
+ with tempfile.TemporaryDirectory() as tmp:
|
|
|
|
|
+ root = Path(tmp)
|
|
|
|
|
+ extract_safe(base_zip, root)
|
|
|
|
|
+ extract_safe(path, root)
|
|
|
|
|
+ (root / ".base-overlay-present").write_text("base+current\n")
|
|
|
|
|
+ subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
|
|
|
|
|
+ subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
|
|
|
|
|
+ subprocess.run([sys.executable, "tools/generate_6400_v1.py", "--check"], cwd=root, check=True)
|
|
|
|
|
+ subprocess.run([sys.executable, "-m", "pytest", "-q", "tests/unit/test_6400_canonical_packages.py"], cwd=root, check=True)
|
|
|
|
|
+ return path
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path, status_json: Path) -> Path:
|
|
|
|
|
+ commit, tree = clean_identity()
|
|
|
|
|
+ receipt = json.loads(td_receipt.read_text())
|
|
|
|
|
+ if receipt.get("status") != "PASS" or receipt.get("commit") != commit:
|
|
|
|
|
+ raise SystemExit("delivery TD receipt is not bound to current clean commit")
|
|
|
|
|
+ bit = Path(str(receipt["bitstream"]))
|
|
|
|
|
+ if not bit.is_absolute(): bit = td_receipt.parent / bit
|
|
|
|
|
+ if sha_file(bit) != receipt.get("bitstream_sha256"):
|
|
|
|
|
+ raise SystemExit("delivery bitstream hash mismatch")
|
|
|
|
|
+ gui_meta = json.loads((gui_exe.parent / "gui-build-metadata.json").read_text())
|
|
|
|
|
+ contract_sha = json.loads((ROOT / "generated/6400/host-contract.json").read_text())["contract_sha256"]
|
|
|
|
|
+ if gui_meta != {"profile": "6400-front-rear", "commit": commit,
|
|
|
|
|
+ "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit)}:
|
|
|
|
|
+ raise SystemExit("delivery GUI metadata binding mismatch")
|
|
|
|
|
+ external = {bit.name: bit, gui_exe.name: gui_exe, gui_zip.name: gui_zip,
|
|
|
|
|
+ "TD-BUILD-RECEIPT.json": td_receipt, "CANDIDATE-STATUS.json": status_json}
|
|
|
|
|
+ selected = {name: path.read_bytes() for name, path in external.items()}
|
|
|
|
|
+ for relative in ["generated/6400/host-contract.json", "generated/6400/golden-vectors.json",
|
|
|
|
|
+ "generated/6400/contract-sha256.txt"]:
|
|
|
|
|
+ selected[relative] = (ROOT / relative).read_bytes()
|
|
|
|
|
+ binding = {"schema": "prod2u-artifact-delivery-binding-v1", "commit": commit,
|
|
|
|
|
+ "tree": tree, "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit),
|
|
|
|
|
+ "gui_sha256": sha_file(gui_exe), "hardware": "NOT_RUN"}
|
|
|
|
|
+ selected["ARTIFACT-TO-DELIVERY-BINDING.json"] = (json.dumps(binding, indent=2, sort_keys=True) + "\n").encode()
|
|
|
|
|
+ payload = common_payload("delivery", commit, tree, selected, binding)
|
|
|
|
|
+ return write_zip(output / f"Prod2U-6400-Delivery-{commit[:8]}.zip", payload)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def tamper_must_fail(path: Path) -> None:
|
|
|
|
|
+ with tempfile.TemporaryDirectory() as tmp:
|
|
|
|
|
+ root = Path(tmp)
|
|
|
|
|
+ extract_safe(path, root)
|
|
|
|
|
+ manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
|
|
|
|
|
+ victim = root / manifest["items"][0]["path"]
|
|
|
|
|
+ victim.write_bytes(victim.read_bytes() + b"X")
|
|
|
|
|
+ result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
|
|
|
|
|
+ if result.returncode == 0:
|
|
|
|
|
+ raise SystemExit("tamper self-check unexpectedly passed")
|