|
|
@@ -0,0 +1,948 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Strict Prod2U PROGRAM_SRAM transaction parser and Tcl generator."""
|
|
|
+
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import argparse
|
|
|
+import ctypes
|
|
|
+import hashlib
|
|
|
+import json
|
|
|
+import ntpath
|
|
|
+import os
|
|
|
+import re
|
|
|
+import shutil
|
|
|
+import subprocess
|
|
|
+import time
|
|
|
+from datetime import datetime, timezone
|
|
|
+from pathlib import Path
|
|
|
+from typing import Any, Callable
|
|
|
+
|
|
|
+
|
|
|
+SCHEMA_NAME = "prod2u-program-sram-receipt-v1"
|
|
|
+TARGET_CHIP = "EF2L45"
|
|
|
+JTAG_SPEED_CODE = 2
|
|
|
+JTAG_SPEED_HZ = 200000
|
|
|
+BIT_TO_VEC_FREQUENCY = "0.200000"
|
|
|
+EXPECTED_MARKERS = (
|
|
|
+ "download_start",
|
|
|
+ "chip_validation",
|
|
|
+ "bit_to_vec_start",
|
|
|
+ "bit_to_vec_finish",
|
|
|
+ "program_start",
|
|
|
+ "program_finish",
|
|
|
+ "download_finish",
|
|
|
+)
|
|
|
+SETUP_MARKERS = ("connect_cable_start", "connect_cable_finish")
|
|
|
+BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
|
|
|
+SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
|
|
|
+ERROR_RE = re.compile(
|
|
|
+ r"\b(?:PRG-8\d{3}|ERROR|FATAL|failed|couldn't read file|invalid command name)\b",
|
|
|
+ re.IGNORECASE,
|
|
|
+)
|
|
|
+FORBIDDEN_RE = re.compile(
|
|
|
+ r"(?<![A-Za-z0-9])(?:flash|erase|spi(?:bin)?|nonvolatile)(?![A-Za-z0-9])",
|
|
|
+ re.IGNORECASE,
|
|
|
+)
|
|
|
+START_COMMAND_RE = re.compile(r'^RUN-1002\s*:\s*start command "(?P<command>.+)"\s*$')
|
|
|
+FINISH_COMMAND_RE = re.compile(r'^RUN-1003\s*:\s*finish command "(?P<command>.+)"(?:\s+in\s+.+)?$')
|
|
|
+CHIP_RE = re.compile(r"^PRG-2014\s*:\s*Chip validation success:\s*(?P<chip>\S+)\s*$")
|
|
|
+DOWNLOAD_RE = re.compile(
|
|
|
+ r"^download\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s+"
|
|
|
+ r"-mode\s+(?P<mode>\S+)\s+-spd\s+(?P<speed>\d+)\s+-cable\s+(?P<cable>\d+)\s*$"
|
|
|
+)
|
|
|
+BIT_TO_VEC_RE = re.compile(
|
|
|
+ r"^bit_to_vec\s+-chip\s+(?P<chip>\S+)\s+-m\s+(?P<mode>\S+)\s+"
|
|
|
+ r"-freq\s+(?P<freq>\S+)\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s*$"
|
|
|
+)
|
|
|
+PROGRAM_RE = re.compile(
|
|
|
+ r"^program\s+-cable\s+(?P<cable>\d+)\s+-mode\s+(?P<mode>\S+)\s+"
|
|
|
+ r"-spd\s+(?P<speed>\d+)\s+-p\s*$"
|
|
|
+)
|
|
|
+PROGRAM_TIMEOUT_SECONDS = 60
|
|
|
+PROCESS_CLEANUP_WAIT_SECONDS = 5.0
|
|
|
+MUTEX_NAME = r"Global\Prod2UProgramSram"
|
|
|
+
|
|
|
+
|
|
|
+def utc_now() -> str:
|
|
|
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
|
+
|
|
|
+
|
|
|
+def sha256_bytes(data: bytes) -> str:
|
|
|
+ return hashlib.sha256(data).hexdigest()
|
|
|
+
|
|
|
+
|
|
|
+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 staged_bitstream_path(build_id: str) -> str:
|
|
|
+ """Return the only accepted Windows staging path for a build identity."""
|
|
|
+ if not BUILD_ID_RE.fullmatch(build_id):
|
|
|
+ raise ValueError("build_id must be eight uppercase hexadecimal characters")
|
|
|
+ return f"C:\\P2U\\{build_id}\\fw.bit"
|
|
|
+
|
|
|
+
|
|
|
+def _strip_path_token(value: str) -> str:
|
|
|
+ if value.startswith("{") and value.endswith("}"):
|
|
|
+ return value[1:-1]
|
|
|
+ if value.startswith('"') and value.endswith('"'):
|
|
|
+ return value[1:-1]
|
|
|
+ return value
|
|
|
+
|
|
|
+
|
|
|
+def _canonical_windows_path(value: str, *, td_bin: str) -> str:
|
|
|
+ normalized = _strip_path_token(value).replace("/", "\\")
|
|
|
+ if not ntpath.isabs(normalized):
|
|
|
+ normalized = ntpath.join(td_bin, normalized)
|
|
|
+ return ntpath.normcase(ntpath.normpath(normalized))
|
|
|
+
|
|
|
+
|
|
|
+def build_program_tcl(bitstream_path: str) -> str:
|
|
|
+ """Generate the fixed one-attempt SRAM-only BitWriter Tcl program."""
|
|
|
+ canonical = ntpath.normpath(bitstream_path)
|
|
|
+ match = re.fullmatch(r"C:\\P2U\\([0-9A-F]{8})\\fw\.bit", canonical, re.IGNORECASE)
|
|
|
+ if match is None:
|
|
|
+ raise ValueError("bitstream_path must be C:\\P2U\\<BUILD_ID>\\fw.bit")
|
|
|
+ build_id = match.group(1).upper()
|
|
|
+ expected = staged_bitstream_path(build_id).replace("\\", "/")
|
|
|
+ return (
|
|
|
+ "connect_cable -allink\n"
|
|
|
+ f"download -bit {{{expected}}} -mode jtag -spd 2 -cable 0\n"
|
|
|
+ "exit\n"
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+class WindowsNamedMutex:
|
|
|
+ """Non-waiting process-wide PROGRAM_SRAM lock backed by a Windows mutex."""
|
|
|
+
|
|
|
+ def __init__(self, name: str = MUTEX_NAME) -> None:
|
|
|
+ self.name = name
|
|
|
+ self.handle: int | None = None
|
|
|
+
|
|
|
+ def __enter__(self) -> "WindowsNamedMutex":
|
|
|
+ if os.name != "nt":
|
|
|
+ raise RuntimeError("Prod2U PROGRAM_SRAM is supported only on Windows")
|
|
|
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
+ kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
|
|
|
+ kernel32.CreateMutexW.restype = ctypes.c_void_p
|
|
|
+ kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
|
|
+ kernel32.WaitForSingleObject.restype = ctypes.c_uint32
|
|
|
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
|
+ kernel32.CloseHandle.restype = ctypes.c_bool
|
|
|
+ handle = kernel32.CreateMutexW(None, False, self.name)
|
|
|
+ if not handle:
|
|
|
+ raise OSError(ctypes.get_last_error(), "CreateMutexW failed")
|
|
|
+ result = kernel32.WaitForSingleObject(handle, 0)
|
|
|
+ if result not in (0x00000000, 0x00000080):
|
|
|
+ kernel32.CloseHandle(handle)
|
|
|
+ raise TimeoutError("Prod2U PROGRAM_SRAM mutex busy")
|
|
|
+ self.handle = int(handle)
|
|
|
+ return self
|
|
|
+
|
|
|
+ def __exit__(self, exc_type, exc, tb) -> bool:
|
|
|
+ if self.handle is not None:
|
|
|
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
+ kernel32.ReleaseMutex.argtypes = [ctypes.c_void_p]
|
|
|
+ kernel32.ReleaseMutex.restype = ctypes.c_bool
|
|
|
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
|
+ kernel32.CloseHandle.restype = ctypes.c_bool
|
|
|
+ kernel32.ReleaseMutex(ctypes.c_void_p(self.handle))
|
|
|
+ kernel32.CloseHandle(ctypes.c_void_p(self.handle))
|
|
|
+ self.handle = None
|
|
|
+ return False
|
|
|
+
|
|
|
+
|
|
|
+def close_td_processes(td_root: Path) -> dict[str, Any]:
|
|
|
+ """Gracefully close, then bound-force-close, TD processes from one install root."""
|
|
|
+ root = str(td_root.resolve())
|
|
|
+ script = r'''
|
|
|
+$ErrorActionPreference = 'Stop'
|
|
|
+if ([string]::IsNullOrWhiteSpace($env:PROD2U_TD_ROOT)) { throw 'PROD2U_TD_ROOT is required' }
|
|
|
+$root = [System.IO.Path]::GetFullPath($env:PROD2U_TD_ROOT).TrimEnd('\')
|
|
|
+$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar
|
|
|
+$allowed = @('td','bw','bitwriter','chipwatcher','bw_commands_prompt')
|
|
|
+function Find-TdProcesses {
|
|
|
+ @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
|
|
|
+ try {
|
|
|
+ $path = $_.Path
|
|
|
+ $fullPath = [System.IO.Path]::GetFullPath($path)
|
|
|
+ $path -and
|
|
|
+ ($fullPath.Equals($root, [System.StringComparison]::OrdinalIgnoreCase) -or
|
|
|
+ $fullPath.StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)) -and
|
|
|
+ ($allowed -contains $_.ProcessName.ToLowerInvariant())
|
|
|
+ } catch { $false }
|
|
|
+ })
|
|
|
+}
|
|
|
+$initial = Find-TdProcesses
|
|
|
+$graceful = @()
|
|
|
+foreach ($process in $initial) {
|
|
|
+ $null = $process.CloseMainWindow()
|
|
|
+ $graceful += ('{0}:{1}' -f $process.ProcessName, $process.Id)
|
|
|
+}
|
|
|
+Start-Sleep -Seconds 5
|
|
|
+$survivors = Find-TdProcesses
|
|
|
+$forced = @()
|
|
|
+foreach ($process in $survivors) {
|
|
|
+ Stop-Process -Id $process.Id -Force -ErrorAction Stop
|
|
|
+ $forced += ('{0}:{1}' -f $process.ProcessName, $process.Id)
|
|
|
+}
|
|
|
+Start-Sleep -Milliseconds 250
|
|
|
+$remaining = @(Find-TdProcesses | ForEach-Object { '{0}:{1}' -f $_.ProcessName, $_.Id })
|
|
|
+[ordered]@{
|
|
|
+ status = $(if ($remaining.Count -eq 0) { 'pass' } else { 'fail' })
|
|
|
+ td_root = $root
|
|
|
+ graceful_close_requested = $graceful
|
|
|
+ forced_terminated = $forced
|
|
|
+ wait_seconds = 5.0
|
|
|
+ remaining = $remaining
|
|
|
+} | ConvertTo-Json -Compress
|
|
|
+'''
|
|
|
+ env = os.environ.copy()
|
|
|
+ env["PROD2U_TD_ROOT"] = root
|
|
|
+ result = subprocess.run(
|
|
|
+ ["powershell.exe", "-NoProfile", "-Command", script],
|
|
|
+ capture_output=True,
|
|
|
+ text=True,
|
|
|
+ check=False,
|
|
|
+ timeout=15,
|
|
|
+ env=env,
|
|
|
+ )
|
|
|
+ if result.returncode != 0:
|
|
|
+ return {
|
|
|
+ "status": "fail",
|
|
|
+ "td_root": root,
|
|
|
+ "graceful_close_requested": [],
|
|
|
+ "forced_terminated": [],
|
|
|
+ "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
|
|
|
+ "remaining": [],
|
|
|
+ "error": result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}",
|
|
|
+ }
|
|
|
+ try:
|
|
|
+ payload = json.loads(result.stdout)
|
|
|
+ except json.JSONDecodeError as exc:
|
|
|
+ return {
|
|
|
+ "status": "fail",
|
|
|
+ "td_root": root,
|
|
|
+ "graceful_close_requested": [],
|
|
|
+ "forced_terminated": [],
|
|
|
+ "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
|
|
|
+ "remaining": [],
|
|
|
+ "error": f"invalid process cleanup JSON: {exc}",
|
|
|
+ }
|
|
|
+ return payload
|
|
|
+
|
|
|
+
|
|
|
+def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
|
|
|
+ if not log_dir.is_dir():
|
|
|
+ return {}
|
|
|
+ snapshot: dict[str, dict[str, int]] = {}
|
|
|
+ for path in log_dir.glob("bw_*.log"):
|
|
|
+ if not path.is_file():
|
|
|
+ continue
|
|
|
+ stat = path.stat()
|
|
|
+ snapshot[str(path.resolve())] = {
|
|
|
+ "size": stat.st_size,
|
|
|
+ "file_id": stat.st_ino,
|
|
|
+ "created_ns": stat.st_ctime_ns,
|
|
|
+ }
|
|
|
+ return snapshot
|
|
|
+
|
|
|
+
|
|
|
+def _read_bitwriter_log_deltas(
|
|
|
+ log_dir: Path,
|
|
|
+ before: dict[str, dict[str, int]],
|
|
|
+) -> tuple[bytes, list[dict[str, Any]], list[str]]:
|
|
|
+ chunks: list[bytes] = []
|
|
|
+ sources: list[dict[str, Any]] = []
|
|
|
+ issues: list[str] = []
|
|
|
+ if not log_dir.is_dir():
|
|
|
+ return b"", sources, issues
|
|
|
+ for path in sorted(log_dir.glob("bw_*.log"), key=lambda candidate: candidate.name.casefold()):
|
|
|
+ if not path.is_file():
|
|
|
+ continue
|
|
|
+ resolved = str(path.resolve())
|
|
|
+ previous = before.get(resolved)
|
|
|
+ stat = path.stat()
|
|
|
+ size = stat.st_size
|
|
|
+ start = int(previous["size"]) if previous is not None else 0
|
|
|
+ if previous is not None and (
|
|
|
+ stat.st_ino != int(previous["file_id"])
|
|
|
+ or stat.st_ctime_ns != int(previous["created_ns"])
|
|
|
+ or size < start
|
|
|
+ ):
|
|
|
+ issues.append("bitwriter_log_replaced_or_truncated")
|
|
|
+ continue
|
|
|
+ if size == start:
|
|
|
+ continue
|
|
|
+ with path.open("rb") as stream:
|
|
|
+ stream.seek(start)
|
|
|
+ data = stream.read()
|
|
|
+ if not data:
|
|
|
+ continue
|
|
|
+ chunks.append(data)
|
|
|
+ sources.append(
|
|
|
+ {
|
|
|
+ "path": resolved,
|
|
|
+ "start_offset": start,
|
|
|
+ "byte_count": len(data),
|
|
|
+ "sha256": sha256_bytes(data),
|
|
|
+ }
|
|
|
+ )
|
|
|
+ return b"\n".join(chunks), sources, list(dict.fromkeys(issues))
|
|
|
+
|
|
|
+
|
|
|
+class _IoCounters(ctypes.Structure):
|
|
|
+ _fields_ = [
|
|
|
+ ("ReadOperationCount", ctypes.c_uint64),
|
|
|
+ ("WriteOperationCount", ctypes.c_uint64),
|
|
|
+ ("OtherOperationCount", ctypes.c_uint64),
|
|
|
+ ("ReadTransferCount", ctypes.c_uint64),
|
|
|
+ ("WriteTransferCount", ctypes.c_uint64),
|
|
|
+ ("OtherTransferCount", ctypes.c_uint64),
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
+class _JobBasicLimitInformation(ctypes.Structure):
|
|
|
+ _fields_ = [
|
|
|
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
|
|
|
+ ("PerJobUserTimeLimit", ctypes.c_int64),
|
|
|
+ ("LimitFlags", ctypes.c_uint32),
|
|
|
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
|
|
|
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
|
|
|
+ ("ActiveProcessLimit", ctypes.c_uint32),
|
|
|
+ ("Affinity", ctypes.c_size_t),
|
|
|
+ ("PriorityClass", ctypes.c_uint32),
|
|
|
+ ("SchedulingClass", ctypes.c_uint32),
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
+class _JobExtendedLimitInformation(ctypes.Structure):
|
|
|
+ _fields_ = [
|
|
|
+ ("BasicLimitInformation", _JobBasicLimitInformation),
|
|
|
+ ("IoInfo", _IoCounters),
|
|
|
+ ("ProcessMemoryLimit", ctypes.c_size_t),
|
|
|
+ ("JobMemoryLimit", ctypes.c_size_t),
|
|
|
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
|
|
|
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
+def windows_process_is_running(pid: int) -> bool:
|
|
|
+ if os.name != "nt":
|
|
|
+ return False
|
|
|
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
+ kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_bool, ctypes.c_uint32]
|
|
|
+ kernel32.OpenProcess.restype = ctypes.c_void_p
|
|
|
+ kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
|
|
+ kernel32.WaitForSingleObject.restype = ctypes.c_uint32
|
|
|
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
|
+ kernel32.CloseHandle.restype = ctypes.c_bool
|
|
|
+ handle = kernel32.OpenProcess(0x00100000, False, int(pid))
|
|
|
+ if not handle:
|
|
|
+ return False
|
|
|
+ try:
|
|
|
+ return kernel32.WaitForSingleObject(handle, 0) == 0x00000102
|
|
|
+ finally:
|
|
|
+ kernel32.CloseHandle(handle)
|
|
|
+
|
|
|
+
|
|
|
+def run_process_in_job(
|
|
|
+ command: list[str],
|
|
|
+ *,
|
|
|
+ cwd: str,
|
|
|
+ timeout: float,
|
|
|
+ capture_output: bool,
|
|
|
+ text: bool,
|
|
|
+ check: bool,
|
|
|
+) -> subprocess.CompletedProcess[str]:
|
|
|
+ """Run one process in a kill-on-close Windows Job Object."""
|
|
|
+ if os.name != "nt":
|
|
|
+ return subprocess.run(
|
|
|
+ command,
|
|
|
+ cwd=cwd,
|
|
|
+ timeout=timeout,
|
|
|
+ capture_output=capture_output,
|
|
|
+ text=text,
|
|
|
+ check=check,
|
|
|
+ )
|
|
|
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
|
|
|
+ kernel32.CreateJobObjectW.restype = ctypes.c_void_p
|
|
|
+ kernel32.SetInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
|
|
|
+ kernel32.SetInformationJobObject.restype = ctypes.c_bool
|
|
|
+ kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
|
|
|
+ kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
|
|
|
+ kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
|
|
+ kernel32.TerminateJobObject.restype = ctypes.c_bool
|
|
|
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
|
+ kernel32.CloseHandle.restype = ctypes.c_bool
|
|
|
+ job = kernel32.CreateJobObjectW(None, None)
|
|
|
+ if not job:
|
|
|
+ raise OSError(ctypes.get_last_error(), "CreateJobObjectW failed")
|
|
|
+ info = _JobExtendedLimitInformation()
|
|
|
+ info.BasicLimitInformation.LimitFlags = 0x00002000
|
|
|
+ if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
|
|
|
+ error = ctypes.get_last_error()
|
|
|
+ kernel32.CloseHandle(job)
|
|
|
+ raise OSError(error, "SetInformationJobObject failed")
|
|
|
+ stdout_pipe = subprocess.PIPE if capture_output else None
|
|
|
+ stderr_pipe = subprocess.PIPE if capture_output else None
|
|
|
+ process = subprocess.Popen(
|
|
|
+ command,
|
|
|
+ cwd=cwd,
|
|
|
+ stdout=stdout_pipe,
|
|
|
+ stderr=stderr_pipe,
|
|
|
+ text=text,
|
|
|
+ )
|
|
|
+ try:
|
|
|
+ if not kernel32.AssignProcessToJobObject(job, ctypes.c_void_p(int(process._handle))):
|
|
|
+ process.kill()
|
|
|
+ process.wait()
|
|
|
+ raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
|
|
|
+ try:
|
|
|
+ stdout, stderr = process.communicate(timeout=timeout)
|
|
|
+ except subprocess.TimeoutExpired as exc:
|
|
|
+ kernel32.TerminateJobObject(job, 1)
|
|
|
+ stdout, stderr = process.communicate()
|
|
|
+ raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr) from exc
|
|
|
+ result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
|
|
|
+ if check and result.returncode != 0:
|
|
|
+ raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
|
|
|
+ return result
|
|
|
+ finally:
|
|
|
+ kernel32.CloseHandle(job)
|
|
|
+
|
|
|
+
|
|
|
+def _artifact(path: Path) -> dict[str, Any]:
|
|
|
+ return {"path": str(path), "size": path.stat().st_size, "sha256": sha256_file(path)}
|
|
|
+
|
|
|
+
|
|
|
+def _recompute_receipt_status(receipt: dict[str, Any]) -> None:
|
|
|
+ failures = list(dict.fromkeys(receipt["parser"]["failures"]))
|
|
|
+ receipt["parser"]["failures"] = failures
|
|
|
+ receipt["parser"]["status"] = "pass" if not failures else "fail"
|
|
|
+ if any(failure.startswith("forbidden_action:") for failure in failures):
|
|
|
+ receipt["status"] = "fail_forbidden_action"
|
|
|
+ else:
|
|
|
+ receipt["status"] = receipt["parser"]["status"]
|
|
|
+
|
|
|
+
|
|
|
+def execute_program_sram(
|
|
|
+ *,
|
|
|
+ source_bitstream: Path,
|
|
|
+ expected_bitstream_sha256: str,
|
|
|
+ build_id: str,
|
|
|
+ output_dir: Path,
|
|
|
+ td_root: Path,
|
|
|
+ run_id: str,
|
|
|
+ process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
|
|
|
+ cleanup_runner: Callable[[Path], dict[str, Any]] = close_td_processes,
|
|
|
+ mutex_factory: Callable[[], Any] = WindowsNamedMutex,
|
|
|
+) -> dict[str, Any]:
|
|
|
+ """Execute exactly one SRAM download and return a strict transaction receipt."""
|
|
|
+ source_bitstream = Path(source_bitstream)
|
|
|
+ output_dir = Path(output_dir)
|
|
|
+ td_root = Path(td_root)
|
|
|
+ if output_dir.exists() and any(output_dir.iterdir()):
|
|
|
+ raise FileExistsError(f"output directory is not empty: {output_dir}")
|
|
|
+ if not source_bitstream.is_file():
|
|
|
+ raise FileNotFoundError(source_bitstream)
|
|
|
+ if not SHA256_RE.fullmatch(expected_bitstream_sha256):
|
|
|
+ raise ValueError("expected bitstream SHA256 must be 64 hexadecimal characters")
|
|
|
+ source_sha256 = sha256_file(source_bitstream)
|
|
|
+ if source_sha256.casefold() != expected_bitstream_sha256.casefold():
|
|
|
+ raise ValueError("bitstream SHA256 mismatch before staging")
|
|
|
+ staged = Path(staged_bitstream_path(build_id))
|
|
|
+ bw_exe = td_root / "bin" / "bw_commands_prompt.exe"
|
|
|
+ if not bw_exe.is_file():
|
|
|
+ raise FileNotFoundError(bw_exe)
|
|
|
+
|
|
|
+ output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
+ tcl_path = output_dir / "program-sram.tcl"
|
|
|
+ stdout_path = output_dir / "bitwriter-stdout.log"
|
|
|
+ stderr_path = output_dir / "bitwriter-stderr.log"
|
|
|
+ delta_path = output_dir / "bitwriter-log-delta.log"
|
|
|
+ started_at = utc_now()
|
|
|
+ start_monotonic = time.monotonic()
|
|
|
+
|
|
|
+ with mutex_factory():
|
|
|
+ cleanup = cleanup_runner(td_root)
|
|
|
+ if cleanup.get("status") != "pass":
|
|
|
+ raise RuntimeError(f"TD process cleanup failed: {cleanup}")
|
|
|
+
|
|
|
+ stage_root = staged.parent.parent
|
|
|
+ stage_root.mkdir(parents=True, exist_ok=True)
|
|
|
+ staged.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ if ntpath.normcase(str(staged.parent.resolve().parent)) != ntpath.normcase(str(stage_root.resolve())):
|
|
|
+ raise ValueError("staging build directory resolves outside C:\\P2U")
|
|
|
+ staged_temp = staged.parent / f".{staged.name}.{os.getpid()}.{time.time_ns()}.tmp"
|
|
|
+ try:
|
|
|
+ shutil.copy2(source_bitstream, staged_temp)
|
|
|
+ if sha256_file(staged_temp).casefold() != expected_bitstream_sha256.casefold():
|
|
|
+ raise ValueError("bitstream SHA256 mismatch in staging temporary file")
|
|
|
+ os.replace(staged_temp, staged)
|
|
|
+ finally:
|
|
|
+ if staged_temp.exists():
|
|
|
+ staged_temp.unlink()
|
|
|
+ staged_sha256 = sha256_file(staged)
|
|
|
+ if staged_sha256.casefold() != expected_bitstream_sha256.casefold():
|
|
|
+ raise ValueError("bitstream SHA256 mismatch after staging")
|
|
|
+ tcl_path.write_text(build_program_tcl(str(staged)), encoding="ascii", newline="\n")
|
|
|
+
|
|
|
+ log_dir = td_root / "bin" / "log"
|
|
|
+ before = _snapshot_bitwriter_logs(log_dir)
|
|
|
+ timed_out = False
|
|
|
+ try:
|
|
|
+ tcl_cli_path = tcl_path.absolute().as_posix()
|
|
|
+ completed = process_runner(
|
|
|
+ [str(bw_exe), tcl_cli_path],
|
|
|
+ cwd=str(td_root / "bin"),
|
|
|
+ timeout=PROGRAM_TIMEOUT_SECONDS,
|
|
|
+ capture_output=True,
|
|
|
+ text=True,
|
|
|
+ check=False,
|
|
|
+ )
|
|
|
+ exit_code = int(completed.returncode)
|
|
|
+ stdout = completed.stdout or ""
|
|
|
+ stderr = completed.stderr or ""
|
|
|
+ except subprocess.TimeoutExpired as exc:
|
|
|
+ timed_out = True
|
|
|
+ exit_code = -1
|
|
|
+ stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
|
|
|
+ stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
|
|
|
+ delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
|
|
|
+
|
|
|
+ stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
|
|
|
+ stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
|
|
|
+ delta_path.write_bytes(delta_bytes)
|
|
|
+ parser_text = delta_bytes.decode("utf-8", errors="replace") if len(delta_sources) == 1 and not delta_issues else ""
|
|
|
+ receipt = build_program_sram_receipt(
|
|
|
+ transcript=parser_text,
|
|
|
+ build_id=build_id,
|
|
|
+ bitstream_path=str(staged),
|
|
|
+ bitstream_bytes=staged.read_bytes(),
|
|
|
+ expected_bitstream_sha256=expected_bitstream_sha256,
|
|
|
+ exit_code=exit_code,
|
|
|
+ run_id=run_id,
|
|
|
+ command_execution_attempted=True,
|
|
|
+ timed_out=timed_out,
|
|
|
+ td_bin=str(td_root / "bin"),
|
|
|
+ )
|
|
|
+ authoritative_marker_signature = _marker_signature(parser_text)
|
|
|
+ if not delta_bytes:
|
|
|
+ receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
|
|
|
+ receipt["parser"]["ordered_markers_complete"] = False
|
|
|
+ if len(delta_sources) > 1:
|
|
|
+ receipt["parser"]["failures"].append("ambiguous_bitwriter_log_sources")
|
|
|
+ receipt["parser"]["ordered_markers_complete"] = False
|
|
|
+ receipt["parser"]["failures"].extend(delta_issues)
|
|
|
+ for stream_name, output in (("stdout", stdout), ("stderr", stderr)):
|
|
|
+ output_failures, output_error_markers, output_forbidden = _transcript_failures(output)
|
|
|
+ receipt["parser"]["failures"].extend(output_failures)
|
|
|
+ receipt["parser"]["error_markers"] = list(
|
|
|
+ dict.fromkeys(receipt["parser"]["error_markers"] + output_error_markers)
|
|
|
+ )
|
|
|
+ if _contains_transaction_marker(output):
|
|
|
+ output_signature = _marker_signature(output)
|
|
|
+ if (
|
|
|
+ stream_name == "stdout"
|
|
|
+ and authoritative_marker_signature
|
|
|
+ and output_signature == authoritative_marker_signature
|
|
|
+ ):
|
|
|
+ receipt["parser"]["stdout_transaction_mirror"] = True
|
|
|
+ else:
|
|
|
+ receipt["parser"]["failures"].append(f"transaction_marker_mismatch:{stream_name}")
|
|
|
+ if output_forbidden:
|
|
|
+ receipt["safety"]["flash_attempted"] = True
|
|
|
+ receipt["safety"]["programs_nonvolatile"] = True
|
|
|
+ receipt["execution"].update(
|
|
|
+ {
|
|
|
+ "timeout_seconds": PROGRAM_TIMEOUT_SECONDS,
|
|
|
+ "started_at": started_at,
|
|
|
+ "finished_at": utc_now(),
|
|
|
+ "duration_seconds": round(time.monotonic() - start_monotonic, 6),
|
|
|
+ }
|
|
|
+ )
|
|
|
+ receipt["tool"] = {
|
|
|
+ "path": str(bw_exe),
|
|
|
+ "td_root": str(td_root),
|
|
|
+ "td_bin": str(td_root / "bin"),
|
|
|
+ }
|
|
|
+ receipt["mutex"] = {"name": MUTEX_NAME, "acquired": True}
|
|
|
+ receipt["process_cleanup"] = cleanup
|
|
|
+ receipt["artifacts"] = {
|
|
|
+ "tcl": _artifact(tcl_path),
|
|
|
+ "stdout": _artifact(stdout_path),
|
|
|
+ "stderr": _artifact(stderr_path),
|
|
|
+ "log_delta": _artifact(delta_path),
|
|
|
+ "log_delta_sources": delta_sources,
|
|
|
+ }
|
|
|
+ _recompute_receipt_status(receipt)
|
|
|
+ receipt_path = output_dir / "program-sram-receipt.json"
|
|
|
+ receipt_temp = output_dir / ".program-sram-receipt.json.tmp"
|
|
|
+ receipt_temp.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8", newline="\n")
|
|
|
+ os.replace(receipt_temp, receipt_path)
|
|
|
+ return receipt
|
|
|
+
|
|
|
+
|
|
|
+def _contains_transaction_marker(transcript: str) -> bool:
|
|
|
+ return any(
|
|
|
+ START_COMMAND_RE.match(line.strip())
|
|
|
+ or FINISH_COMMAND_RE.match(line.strip())
|
|
|
+ or CHIP_RE.match(line.strip())
|
|
|
+ for line in transcript.splitlines()
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+def _marker_records(transcript: str) -> list[dict[str, Any]]:
|
|
|
+ records: list[dict[str, Any]] = []
|
|
|
+ for line_number, raw_line in enumerate(transcript.splitlines(), start=1):
|
|
|
+ line = raw_line.strip()
|
|
|
+ start = START_COMMAND_RE.match(line)
|
|
|
+ finish = FINISH_COMMAND_RE.match(line)
|
|
|
+ chip = CHIP_RE.match(line)
|
|
|
+ if start:
|
|
|
+ command = start.group("command")
|
|
|
+ if command == "connect_cable -allink":
|
|
|
+ records.append({"marker": "connect_cable_start", "command": command, "line": line_number})
|
|
|
+ elif command.startswith("download "):
|
|
|
+ records.append({"marker": "download_start", "command": command, "line": line_number})
|
|
|
+ elif command.startswith("bit_to_vec "):
|
|
|
+ records.append({"marker": "bit_to_vec_start", "command": command, "line": line_number})
|
|
|
+ elif command.startswith("program "):
|
|
|
+ records.append({"marker": "program_start", "command": command, "line": line_number})
|
|
|
+ else:
|
|
|
+ records.append(
|
|
|
+ {
|
|
|
+ "marker": "unrecognized_run_operation",
|
|
|
+ "operation": _operation_name(command),
|
|
|
+ "line": line_number,
|
|
|
+ }
|
|
|
+ )
|
|
|
+ elif finish:
|
|
|
+ command = finish.group("command")
|
|
|
+ if command == "connect_cable -allink":
|
|
|
+ records.append({"marker": "connect_cable_finish", "command": command, "line": line_number})
|
|
|
+ elif command.startswith("bit_to_vec "):
|
|
|
+ records.append({"marker": "bit_to_vec_finish", "command": command, "line": line_number})
|
|
|
+ elif command.startswith("program "):
|
|
|
+ records.append({"marker": "program_finish", "command": command, "line": line_number})
|
|
|
+ elif command.startswith("download "):
|
|
|
+ records.append({"marker": "download_finish", "command": command, "line": line_number})
|
|
|
+ else:
|
|
|
+ records.append(
|
|
|
+ {
|
|
|
+ "marker": "unrecognized_run_operation",
|
|
|
+ "operation": _operation_name(command),
|
|
|
+ "line": line_number,
|
|
|
+ }
|
|
|
+ )
|
|
|
+ elif chip:
|
|
|
+ records.append(
|
|
|
+ {
|
|
|
+ "marker": "chip_validation",
|
|
|
+ "chip": chip.group("chip"),
|
|
|
+ "line": line_number,
|
|
|
+ }
|
|
|
+ )
|
|
|
+ return records
|
|
|
+
|
|
|
+
|
|
|
+def _operation_name(command: str) -> str:
|
|
|
+ parts = command.split(maxsplit=1)
|
|
|
+ return parts[0].casefold() if parts else "<empty>"
|
|
|
+
|
|
|
+
|
|
|
+def _marker_failures(records: list[dict[str, Any]]) -> list[str]:
|
|
|
+ failures: list[str] = []
|
|
|
+ observed_all = [str(record["marker"]) for record in records]
|
|
|
+ observed = [marker for marker in observed_all if marker in EXPECTED_MARKERS]
|
|
|
+ setup_observed = [marker for marker in observed_all if marker in SETUP_MARKERS]
|
|
|
+ for record in records:
|
|
|
+ if record["marker"] == "unrecognized_run_operation":
|
|
|
+ failures.append(f"unrecognized_run_operation:{record['operation']}")
|
|
|
+ if setup_observed and (
|
|
|
+ setup_observed != list(SETUP_MARKERS)
|
|
|
+ or observed_all[: len(SETUP_MARKERS)] != list(SETUP_MARKERS)
|
|
|
+ ):
|
|
|
+ failures.append("connect_cable_marker_mismatch")
|
|
|
+ if any(observed.count(expected) != 1 for expected in EXPECTED_MARKERS) or any(
|
|
|
+ marker == "unrecognized_run_operation" for marker in observed_all
|
|
|
+ ):
|
|
|
+ failures.append("transaction_count_not_one")
|
|
|
+ for index, expected in enumerate(EXPECTED_MARKERS):
|
|
|
+ if expected not in observed:
|
|
|
+ failures.append(f"missing_marker:{expected}")
|
|
|
+ elif index >= len(observed) or observed[index] != expected:
|
|
|
+ failures.append(f"out_of_order_marker:{expected}")
|
|
|
+ if len(observed) != len(EXPECTED_MARKERS) and not any(
|
|
|
+ failure == "transaction_count_not_one" for failure in failures
|
|
|
+ ):
|
|
|
+ failures.append("marker_count_mismatch")
|
|
|
+ return failures
|
|
|
+
|
|
|
+
|
|
|
+def _marker_signature(transcript: str) -> list[tuple[str, str]]:
|
|
|
+ signature: list[tuple[str, str]] = []
|
|
|
+ for record in _marker_records(transcript):
|
|
|
+ detail = str(record.get("command") or record.get("chip") or record.get("operation") or "")
|
|
|
+ signature.append((str(record["marker"]), detail))
|
|
|
+ return signature
|
|
|
+
|
|
|
+
|
|
|
+def _record(records: list[dict[str, Any]], marker: str) -> dict[str, Any] | None:
|
|
|
+ matches = [record for record in records if record["marker"] == marker]
|
|
|
+ return matches[0] if len(matches) == 1 else None
|
|
|
+
|
|
|
+
|
|
|
+def _command_failures(
|
|
|
+ records: list[dict[str, Any]], *, expected_staging_path: str, td_bin: str
|
|
|
+) -> tuple[list[str], dict[str, Any]]:
|
|
|
+ failures: list[str] = []
|
|
|
+ details: dict[str, Any] = {}
|
|
|
+ expected_path = _canonical_windows_path(expected_staging_path, td_bin=td_bin)
|
|
|
+
|
|
|
+ chip = _record(records, "chip_validation")
|
|
|
+ if chip is not None and chip.get("chip") != TARGET_CHIP:
|
|
|
+ failures.append("chip_mismatch")
|
|
|
+
|
|
|
+ observed_paths: list[str] = []
|
|
|
+ for marker in ("download_start", "download_finish"):
|
|
|
+ record = _record(records, marker)
|
|
|
+ if record is None:
|
|
|
+ continue
|
|
|
+ command = str(record["command"])
|
|
|
+ parsed = DOWNLOAD_RE.match(command)
|
|
|
+ if parsed is None:
|
|
|
+ failures.append("download_command_mismatch")
|
|
|
+ continue
|
|
|
+ if parsed.group("mode") != "jtag" or parsed.group("cable") != "0":
|
|
|
+ failures.append("download_command_mismatch")
|
|
|
+ if parsed.group("speed") != str(JTAG_SPEED_CODE):
|
|
|
+ failures.append("jtag_speed_mismatch")
|
|
|
+ observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
|
|
|
+
|
|
|
+ for marker in ("bit_to_vec_start", "bit_to_vec_finish"):
|
|
|
+ record = _record(records, marker)
|
|
|
+ if record is None:
|
|
|
+ continue
|
|
|
+ command = str(record["command"])
|
|
|
+ parsed = BIT_TO_VEC_RE.match(command)
|
|
|
+ if parsed is None:
|
|
|
+ failures.append("bit_to_vec_command_mismatch")
|
|
|
+ continue
|
|
|
+ if parsed.group("chip") != TARGET_CHIP:
|
|
|
+ failures.append("chip_mismatch")
|
|
|
+ if parsed.group("mode") != "jtag_burst":
|
|
|
+ failures.append("bit_to_vec_mode_mismatch")
|
|
|
+ if parsed.group("freq") != BIT_TO_VEC_FREQUENCY:
|
|
|
+ failures.append("bit_to_vec_frequency_mismatch")
|
|
|
+ observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
|
|
|
+
|
|
|
+ for marker in ("program_start", "program_finish"):
|
|
|
+ record = _record(records, marker)
|
|
|
+ if record is None:
|
|
|
+ continue
|
|
|
+ command = str(record["command"])
|
|
|
+ parsed = PROGRAM_RE.match(command)
|
|
|
+ if parsed is None:
|
|
|
+ failures.append("program_command_mismatch")
|
|
|
+ continue
|
|
|
+ if parsed.group("cable") != "0" or parsed.group("mode") != "svf":
|
|
|
+ failures.append("program_command_mismatch")
|
|
|
+ if parsed.group("speed") != str(JTAG_SPEED_CODE):
|
|
|
+ failures.append("jtag_speed_mismatch")
|
|
|
+
|
|
|
+ if observed_paths and any(path != expected_path for path in observed_paths):
|
|
|
+ failures.append("staging_path_mismatch")
|
|
|
+ if len(set(observed_paths)) > 1:
|
|
|
+ failures.append("transaction_bitstream_path_mismatch")
|
|
|
+ details["expected_staging_path"] = expected_path
|
|
|
+ details["observed_bitstream_paths"] = sorted(set(observed_paths))
|
|
|
+ return failures, details
|
|
|
+
|
|
|
+
|
|
|
+def _transcript_failures(transcript: str) -> tuple[list[str], list[str], bool]:
|
|
|
+ failures: list[str] = []
|
|
|
+ error_markers: list[str] = []
|
|
|
+ forbidden = False
|
|
|
+ for raw_line in transcript.splitlines():
|
|
|
+ for match in ERROR_RE.finditer(raw_line):
|
|
|
+ marker = match.group(0)
|
|
|
+ if marker.casefold() not in {item.casefold() for item in error_markers}:
|
|
|
+ error_markers.append(marker)
|
|
|
+ failures.append(f"error_marker:{marker}")
|
|
|
+ for match in FORBIDDEN_RE.finditer(raw_line):
|
|
|
+ forbidden = True
|
|
|
+ action = match.group(0).lower()
|
|
|
+ failure = f"forbidden_action:{action}"
|
|
|
+ if failure not in failures:
|
|
|
+ failures.append(failure)
|
|
|
+ return failures, error_markers, forbidden
|
|
|
+
|
|
|
+
|
|
|
+def build_program_sram_receipt(
|
|
|
+ *,
|
|
|
+ transcript: str,
|
|
|
+ build_id: str,
|
|
|
+ bitstream_path: str,
|
|
|
+ bitstream_bytes: bytes,
|
|
|
+ expected_bitstream_sha256: str,
|
|
|
+ exit_code: int,
|
|
|
+ run_id: str,
|
|
|
+ command_execution_attempted: bool = False,
|
|
|
+ timed_out: bool = False,
|
|
|
+ td_bin: str = "",
|
|
|
+) -> dict[str, Any]:
|
|
|
+ """Build a strict receipt from the exact BitWriter log increment."""
|
|
|
+ failures: list[str] = []
|
|
|
+ try:
|
|
|
+ expected_staging_path = staged_bitstream_path(build_id)
|
|
|
+ except ValueError:
|
|
|
+ expected_staging_path = ""
|
|
|
+ failures.append("build_id_invalid")
|
|
|
+
|
|
|
+ records = _marker_records(transcript)
|
|
|
+ failures.extend(_marker_failures(records))
|
|
|
+ command_failures, command_details = _command_failures(
|
|
|
+ records,
|
|
|
+ expected_staging_path=expected_staging_path,
|
|
|
+ td_bin=td_bin,
|
|
|
+ )
|
|
|
+ failures.extend(command_failures)
|
|
|
+ transcript_failures, error_markers, forbidden = _transcript_failures(transcript)
|
|
|
+ failures.extend(transcript_failures)
|
|
|
+
|
|
|
+ actual_sha256 = hashlib.sha256(bitstream_bytes).hexdigest()
|
|
|
+ if not SHA256_RE.fullmatch(expected_bitstream_sha256):
|
|
|
+ failures.append("bitstream_sha256_invalid")
|
|
|
+ elif actual_sha256.casefold() != expected_bitstream_sha256.casefold():
|
|
|
+ failures.append("bitstream_sha256_mismatch")
|
|
|
+ staging_matches = (
|
|
|
+ bool(expected_staging_path)
|
|
|
+ and _canonical_windows_path(bitstream_path, td_bin=td_bin)
|
|
|
+ == _canonical_windows_path(expected_staging_path, td_bin=td_bin)
|
|
|
+ )
|
|
|
+ if not staging_matches:
|
|
|
+ failures.append("staging_path_mismatch")
|
|
|
+ if exit_code != 0:
|
|
|
+ failures.append("exit_code_nonzero")
|
|
|
+ if not command_execution_attempted:
|
|
|
+ failures.append("program_command_not_executed")
|
|
|
+ if timed_out:
|
|
|
+ failures.append("program_timeout")
|
|
|
+
|
|
|
+ failures = list(dict.fromkeys(failures))
|
|
|
+ transaction_records = [record for record in records if record["marker"] in EXPECTED_MARKERS]
|
|
|
+ setup_records = [record for record in records if record["marker"] in SETUP_MARKERS]
|
|
|
+ ordered_markers_complete = (
|
|
|
+ [record["marker"] for record in transaction_records] == list(EXPECTED_MARKERS)
|
|
|
+ and not any(failure.startswith(("missing_marker:", "out_of_order_marker:")) for failure in failures)
|
|
|
+ and "connect_cable_marker_mismatch" not in failures
|
|
|
+ )
|
|
|
+ parser_status = "pass" if not failures else "fail"
|
|
|
+ status = "fail_forbidden_action" if forbidden else parser_status
|
|
|
+
|
|
|
+ return {
|
|
|
+ "schema": SCHEMA_NAME,
|
|
|
+ "status": status,
|
|
|
+ "run_id": run_id,
|
|
|
+ "request": {
|
|
|
+ "operation": "PROGRAM_SRAM",
|
|
|
+ "target_chip": TARGET_CHIP,
|
|
|
+ "cable_index": 0,
|
|
|
+ "speed_code": JTAG_SPEED_CODE,
|
|
|
+ "speed_hz": JTAG_SPEED_HZ,
|
|
|
+ "attempt_limit": 1,
|
|
|
+ "power_cycle_allowed": False,
|
|
|
+ },
|
|
|
+ "bitstream": {
|
|
|
+ "path": bitstream_path,
|
|
|
+ "sha256": actual_sha256,
|
|
|
+ "build_id": build_id,
|
|
|
+ },
|
|
|
+ "staging": {
|
|
|
+ "expected_path": expected_staging_path,
|
|
|
+ "observed_path": bitstream_path,
|
|
|
+ "matches_expected_path": staging_matches,
|
|
|
+ },
|
|
|
+ "execution": {
|
|
|
+ "exit_code": exit_code,
|
|
|
+ "timed_out": timed_out,
|
|
|
+ "attempt_count": 1,
|
|
|
+ "retry_count": 0,
|
|
|
+ "power_cycle_count": 0,
|
|
|
+ "command_execution_attempted": command_execution_attempted,
|
|
|
+ },
|
|
|
+ "parser": {
|
|
|
+ "status": parser_status,
|
|
|
+ "exit_code_trusted": False,
|
|
|
+ "ordered_markers": list(EXPECTED_MARKERS),
|
|
|
+ "ordered_markers_complete": ordered_markers_complete,
|
|
|
+ "observed_markers": [record["marker"] for record in transaction_records],
|
|
|
+ "observed_marker_lines": [record["line"] for record in transaction_records],
|
|
|
+ "setup_markers": [record["marker"] for record in setup_records],
|
|
|
+ "setup_marker_lines": [record["line"] for record in setup_records],
|
|
|
+ "stdout_transaction_mirror": False,
|
|
|
+ "error_markers": error_markers,
|
|
|
+ "failures": failures,
|
|
|
+ "transcript_sha256": hashlib.sha256(transcript.encode("utf-8")).hexdigest(),
|
|
|
+ **command_details,
|
|
|
+ },
|
|
|
+ "safety": {
|
|
|
+ "flash_attempted": forbidden,
|
|
|
+ "programs_nonvolatile": forbidden,
|
|
|
+ "power_cycle_attempted": False,
|
|
|
+ "driver_install_attempted": False,
|
|
|
+ "toggles_dtr_rts": False,
|
|
|
+ "real_ptc_fan_action_attempted": False,
|
|
|
+ "external_programming_command_executed": command_execution_attempted,
|
|
|
+ },
|
|
|
+ "authority_boundary": (
|
|
|
+ "This receipt proves only one parsed PROGRAM_SRAM transaction against the staged bitstream. "
|
|
|
+ "It does not certify flash, thermal performance, real PTC/FAN load behavior, or PID closed-loop behavior."
|
|
|
+ ),
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def build_parser() -> argparse.ArgumentParser:
|
|
|
+ parser = argparse.ArgumentParser(description=__doc__)
|
|
|
+ parser.add_argument("--transcript", type=Path, required=True, help="captured BitWriter log increment")
|
|
|
+ parser.add_argument("--bitstream", type=Path, required=True, help="staged bitstream to hash")
|
|
|
+ parser.add_argument("--build-id", required=True)
|
|
|
+ parser.add_argument("--sha256", required=True, dest="expected_bitstream_sha256")
|
|
|
+ parser.add_argument("--exit-code", type=int, default=0, help="observed tool exit code")
|
|
|
+ parser.add_argument("--run-id", required=True)
|
|
|
+ parser.add_argument("--td-bin", default="")
|
|
|
+ parser.add_argument("--receipt", type=Path, help="optional JSON receipt output path")
|
|
|
+ return parser
|
|
|
+
|
|
|
+
|
|
|
+def main(argv: list[str] | None = None) -> int:
|
|
|
+ args = build_parser().parse_args(argv)
|
|
|
+ receipt = build_program_sram_receipt(
|
|
|
+ transcript=args.transcript.read_text(encoding="utf-8", errors="replace"),
|
|
|
+ build_id=args.build_id,
|
|
|
+ bitstream_path=str(args.bitstream),
|
|
|
+ bitstream_bytes=args.bitstream.read_bytes(),
|
|
|
+ expected_bitstream_sha256=args.expected_bitstream_sha256,
|
|
|
+ exit_code=args.exit_code,
|
|
|
+ run_id=args.run_id,
|
|
|
+ command_execution_attempted=False,
|
|
|
+ timed_out=False,
|
|
|
+ td_bin=args.td_bin,
|
|
|
+ )
|
|
|
+ encoded = json.dumps(receipt, indent=2) + "\n"
|
|
|
+ if args.receipt is not None:
|
|
|
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ args.receipt.write_text(encoded, encoding="utf-8", newline="\n")
|
|
|
+ print(encoded, end="")
|
|
|
+ return 0 if receipt["status"] == "pass" else 1
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ raise SystemExit(main())
|