#!/usr/bin/env python3 """Strict Prod2U PROGRAM_SRAM transaction parser and Tcl generator.""" from __future__ import annotations import argparse import ctypes import getpass import hashlib import json import locale import ntpath import os import re import shutil import subprocess import tempfile import time from ctypes import wintypes 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"(?.+)"\s*$') FINISH_COMMAND_RE = re.compile(r'^RUN-1003\s*:\s*finish command "(?P.+)"(?:\s+in\s+.+)?$') CHIP_RE = re.compile(r"^PRG-2014\s*:\s*Chip validation success:\s*(?P\S+)\s*$") DOWNLOAD_RE = re.compile( r"^download\s+-bit\s+(?P\{[^}]+\}|\"[^\"]+\"|\S+)\s+" r"-mode\s+(?P\S+)\s+-spd\s+(?P\d+)\s+-cable\s+(?P\d+)\s*$" ) BIT_TO_VEC_RE = re.compile( r"^bit_to_vec\s+-chip\s+(?P\S+)\s+-m\s+(?P\S+)\s+" r"-freq\s+(?P\S+)\s+-bit\s+(?P\{[^}]+\}|\"[^\"]+\"|\S+)\s*$" ) PROGRAM_RE = re.compile( r"^program\s+-cable\s+(?P\d+)\s+-mode\s+(?P\S+)\s+" r"-spd\s+(?P\d+)\s+-p\s*$" ) PROGRAM_TIMEOUT_SECONDS = 60 PROCESS_CLEANUP_WAIT_SECONDS = 5.0 MUTEX_NAME = r"Global\Prod2UProgramSram" TD_PROCESS_EXECUTABLES = ( "td.exe", "td_commands_prompt.exe", "bw.exe", "bw_commands_prompt.exe", "hwserver.exe", ) 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\\\\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 class WindowsTdProcessAdapter: """Read and control qualified Anlogic processes with PID-reuse checks.""" def __init__(self, runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> None: self.runner = runner def _run_json(self, script: str, *, env: dict[str, str] | None = None) -> Any: command_env = os.environ.copy() if env: command_env.update(env) result = self.runner( ["powershell.exe", "-NoProfile", "-Command", script], capture_output=True, text=True, check=False, timeout=15, env=command_env, ) if result.returncode != 0: detail = result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}" raise RuntimeError(detail) try: return json.loads(result.stdout) except json.JSONDecodeError as exc: raise RuntimeError(f"invalid process audit JSON: {exc}") from exc def discover(self) -> list[dict[str, Any]]: candidate_names = ", ".join(f"'{name}'" for name in TD_PROCESS_EXECUTABLES) script = rf''' $ErrorActionPreference = 'Stop' $candidateNames = @({candidate_names}) $records = @() $candidates = @(Get-CimInstance Win32_Process | Where-Object {{ $candidateNames -contains ([string]$_.Name).ToLowerInvariant() }} | Sort-Object ProcessId) foreach ($process in $candidates) {{ $record = [ordered]@{{ pid = [int]$process.ProcessId name = [string]$process.Name path = $null user = $null session_id = $null parent_pid = $null command_line = $null start_time = $null exe_sha256 = $null }} try {{ if ([string]::IsNullOrWhiteSpace([string]$process.ExecutablePath)) {{ throw 'path unavailable' }} $record.path = [System.IO.Path]::GetFullPath([string]$process.ExecutablePath) $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwner if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{ throw ('owner unavailable: return={0}' -f $owner.ReturnValue) }} $record.user = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{ [string]$owner.User }} else {{ '{0}\{1}' -f $owner.Domain, $owner.User }}) $record.session_id = [int]$process.SessionId $record.parent_pid = [int]$process.ParentProcessId if ([string]::IsNullOrWhiteSpace([string]$process.CommandLine)) {{ throw 'command line unavailable' }} $record.command_line = [string]$process.CommandLine if ($null -eq $process.CreationDate) {{ throw 'start time unavailable' }} $record.start_time = ([DateTime]$process.CreationDate).ToUniversalTime().ToString('o') $record.exe_sha256 = (Get-FileHash -LiteralPath $record.path -Algorithm SHA256).Hash.ToLowerInvariant() }} catch {{ $record.identity_error = $_.Exception.Message }} $records += [pscustomobject]$record }} [ordered]@{{ processes = @($records) }} | ConvertTo-Json -Compress -Depth 4 ''' payload = self._run_json(script) processes = payload.get("processes") if isinstance(payload, dict) else None if not isinstance(processes, list): raise RuntimeError("process discovery did not return an array") return processes def _identity_action(self, process: dict[str, Any], action: str) -> dict[str, Any]: if action == "close": action_script = "$native = Get-Process -Id $pidValue -ErrorAction Stop; $null = $native.CloseMainWindow()" elif action == "probe": action_script = "" elif action == "force": action_script = "Stop-Process -Id $pidValue -Force -ErrorAction Stop" else: raise ValueError(f"unknown process action: {action}") script = rf''' $ErrorActionPreference = 'Stop' $pidValue = [int]$env:PROD2U_PROCESS_PID $expectedPath = [System.IO.Path]::GetFullPath($env:PROD2U_PROCESS_PATH) $expectedStart = $env:PROD2U_PROCESS_START $expectedOwner = $env:PROD2U_PROCESS_OWNER $expectedSession = [int]$env:PROD2U_PROCESS_SESSION $expectedParent = [int]$env:PROD2U_PROCESS_PARENT $expectedCommandLine = $env:PROD2U_PROCESS_COMMAND_LINE $expectedSha256 = $env:PROD2U_PROCESS_SHA256 $current = Get-CimInstance Win32_Process -Filter ("ProcessId = {{0}}" -f $pidValue) if ($null -eq $current) {{ [ordered]@{{ status = 'not_running'; running = $false }} | ConvertTo-Json -Compress exit 0 }} if ([string]::IsNullOrWhiteSpace([string]$current.ExecutablePath)) {{ throw 'current process path unavailable' }} $currentPath = [System.IO.Path]::GetFullPath([string]$current.ExecutablePath) $currentStart = ([DateTime]$current.CreationDate).ToUniversalTime().ToString('o') $owner = Invoke-CimMethod -InputObject $current -MethodName GetOwner if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{ throw 'current process owner unavailable' }} $currentOwner = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{ [string]$owner.User }} else {{ '{{0}}\{{1}}' -f $owner.Domain, $owner.User }}) $currentSha256 = (Get-FileHash -LiteralPath $currentPath -Algorithm SHA256).Hash.ToLowerInvariant() if (-not $currentPath.Equals($expectedPath, [System.StringComparison]::OrdinalIgnoreCase) -or -not $currentStart.Equals($expectedStart, [System.StringComparison]::Ordinal) -or -not $currentOwner.Equals($expectedOwner, [System.StringComparison]::OrdinalIgnoreCase) -or [int]$current.SessionId -ne $expectedSession -or [int]$current.ParentProcessId -ne $expectedParent -or -not ([string]$current.CommandLine).Equals($expectedCommandLine, [System.StringComparison]::Ordinal) -or -not $currentSha256.Equals($expectedSha256, [System.StringComparison]::OrdinalIgnoreCase)) {{ throw 'process identity changed before action' }} {action_script} [ordered]@{{ status = 'ok'; running = $true }} | ConvertTo-Json -Compress ''' return self._run_json( script, env={ "PROD2U_PROCESS_PID": str(process["pid"]), "PROD2U_PROCESS_PATH": str(process["path"]), "PROD2U_PROCESS_START": str(process["start_time"]), "PROD2U_PROCESS_OWNER": str(process["user"]), "PROD2U_PROCESS_SESSION": str(process["session_id"]), "PROD2U_PROCESS_PARENT": str(process["parent_pid"]), "PROD2U_PROCESS_COMMAND_LINE": str(process["command_line"]), "PROD2U_PROCESS_SHA256": str(process["exe_sha256"]), }, ) def request_close(self, process: dict[str, Any]) -> None: self._identity_action(process, "close") def is_running(self, process: dict[str, Any]) -> bool: return bool(self._identity_action(process, "probe").get("running")) def force_stop(self, process: dict[str, Any]) -> None: self._identity_action(process, "force") def _process_identity_errors(process: Any, *, td_root: str) -> tuple[dict[str, Any] | None, list[str]]: if not isinstance(process, dict): return None, ["identity_unreadable:unknown:record"] pid = process.get("pid") pid_label = str(pid) if isinstance(pid, int) and not isinstance(pid, bool) else "unknown" errors: list[str] = [] if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0: errors.append("identity_unreadable:unknown:pid") name = process.get("name") if not isinstance(name, str) or not name.strip(): errors.append(f"identity_unreadable:{pid_label}:name") elif name.casefold() not in {candidate.casefold() for candidate in TD_PROCESS_EXECUTABLES}: errors.append(f"unexpected_process_name:{pid_label}") for field in ("path", "user", "command_line", "start_time", "exe_sha256"): value = process.get(field) if not isinstance(value, str) or not value.strip(): errors.append(f"identity_unreadable:{pid_label}:{field}") identity_error = process.get("identity_error") if identity_error: errors.append(f"identity_unreadable:{pid_label}:adapter:{identity_error}") path = process.get("path") if isinstance(path, str) and path.strip(): canonical_path = ntpath.normcase(ntpath.normpath(path)) canonical_root = ntpath.normcase(ntpath.normpath(td_root)).rstrip("\\/") root_prefix = canonical_root + "\\" if not ntpath.isabs(path) or not canonical_path.startswith(root_prefix): errors.append(f"unknown_process_path:{pid_label}") if isinstance(name, str) and name.strip() and ntpath.basename(canonical_path) != name.casefold(): errors.append(f"process_name_path_mismatch:{pid_label}") exe_sha256 = process.get("exe_sha256") if isinstance(exe_sha256, str) and exe_sha256.strip() and not re.fullmatch(r"[0-9a-f]{64}", exe_sha256): errors.append(f"identity_unreadable:{pid_label}:exe_sha256") for field in ("session_id", "parent_pid"): value = process.get(field) if not isinstance(value, int) or isinstance(value, bool) or value < 0: errors.append(f"identity_unreadable:{pid_label}:{field}") if errors: return None, errors return { "pid": int(pid), "name": str(name), "path": str(process["path"]), "user": str(process["user"]), "session_id": int(process["session_id"]), "parent_pid": int(process["parent_pid"]), "command_line": str(process["command_line"]), "start_time": str(process["start_time"]), "exe_sha256": str(process["exe_sha256"]), }, [] def _canonical_command_line(value: str) -> str: return value.strip() def _validate_ownership_policy(policy: Any) -> list[str]: if not isinstance(policy, dict): return ["ownership_policy_missing"] errors: list[str] = [] for field in ("owner", "command_line"): if not isinstance(policy.get(field), str) or not policy[field].strip(): errors.append(f"ownership_policy_invalid:{field}") for field in ("session_id", "parent_pid"): value = policy.get(field) if not isinstance(value, int) or isinstance(value, bool) or value < 0: errors.append(f"ownership_policy_invalid:{field}") binaries = policy.get("approved_binaries") if not isinstance(binaries, list) or not binaries: errors.append("ownership_policy_invalid:approved_binaries") else: for binary in binaries: if not isinstance(binary, dict): errors.append("ownership_policy_invalid:approved_binary") continue if not all(isinstance(binary.get(field), str) and binary[field].strip() for field in ("name", "path")): errors.append("ownership_policy_invalid:approved_binary_identity") if not isinstance(binary.get("exe_sha256"), str) or not SHA256_RE.fullmatch(binary["exe_sha256"]): errors.append("ownership_policy_invalid:approved_binary_hash") return list(dict.fromkeys(errors)) def _is_harness_owned(process: dict[str, Any], policy: dict[str, Any]) -> bool: binary_matches = any( str(process["name"]).casefold() == str(binary["name"]).casefold() and ntpath.normcase(ntpath.normpath(str(process["path"]))) == ntpath.normcase(ntpath.normpath(str(binary["path"]))) and str(process["exe_sha256"]).casefold() == str(binary["exe_sha256"]).casefold() for binary in policy["approved_binaries"] ) return ( binary_matches and str(process["user"]).casefold() == str(policy["owner"]).casefold() and process["session_id"] == policy["session_id"] and process["parent_pid"] == policy["parent_pid"] and _canonical_command_line(str(process["command_line"])) == _canonical_command_line(str(policy["command_line"])) ) def build_process_ownership_policy(*, executable: Path, command: list[str]) -> dict[str, Any]: """Build the exact identity policy for a process launched by this harness.""" executable = executable.resolve() if os.name == "nt": session_id = ctypes.c_uint32() kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) kernel32.ProcessIdToSessionId.argtypes = [ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32)] kernel32.ProcessIdToSessionId.restype = ctypes.c_bool if not kernel32.ProcessIdToSessionId(os.getpid(), ctypes.byref(session_id)): raise OSError(ctypes.get_last_error(), "ProcessIdToSessionId failed") domain = os.environ.get("USERDOMAIN", "").strip() username = os.environ.get("USERNAME", "").strip() or getpass.getuser() owner = f"{domain}\\{username}" if domain else username current_session = int(session_id.value) else: owner = getpass.getuser() current_session = 0 return { "owner": owner, "session_id": current_session, "parent_pid": os.getpid(), "approved_binaries": [ { "name": executable.name.casefold(), "path": str(executable), "exe_sha256": sha256_file(executable), } ], "command_line": subprocess.list2cmdline(command), } def close_td_processes( td_root: Path, *, ownership_policy: dict[str, Any] | None = None, process_adapter: Any | None = None, sleeper: Callable[[float], None] = time.sleep, ) -> dict[str, Any]: """Terminate only processes proven to be owned by this harness invocation.""" root = str(td_root.resolve()) adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter() discovered: list[dict[str, Any]] = [] harness_owned: list[dict[str, Any]] = [] blocking: list[dict[str, Any]] = [] graceful: list[dict[str, Any]] = [] forced: list[dict[str, Any]] = [] errors = _validate_ownership_policy(ownership_policy) def result(status: str, *, remaining: list[dict[str, Any]] | None = None, audited: bool) -> dict[str, Any]: return { "status": status, "td_root": root, "identity_audit_completed_before_action": audited, "ownership_policy": ownership_policy, "discovered_processes": discovered, "harness_owned_processes": harness_owned, "blocking_processes": blocking, "graceful_close_requested": graceful, "forced_terminated": forced, "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS, "remaining": remaining or [], "post_action_audit_completed": False, "post_action_discovered_processes": [], "post_action_harness_owned_processes": [], "post_action_blocking_processes": [], "residual_processes": [], "post_action_errors": [], "errors": list(dict.fromkeys(errors)), } if errors: return result("fail", audited=False) try: raw_processes = adapter.discover() except Exception as exc: errors.append(f"process_discovery_failed:{exc}") return result("fail", audited=False) if not isinstance(raw_processes, list): errors.append("process_discovery_failed:not_an_array") return result("fail", audited=False) for raw_process in raw_processes: process, process_errors = _process_identity_errors(raw_process, td_root=root) errors.extend(process_errors) if process is not None: discovered.append(process) if errors: return result("fail", audited=False) for process in discovered: if _is_harness_owned(process, ownership_policy): harness_owned.append(process) else: blocking.append(process) if blocking: errors.append("blocking_td_processes_present") return result("fail", remaining=discovered, audited=True) try: for process in harness_owned: adapter.request_close(process) graceful.append(process) if harness_owned: sleeper(PROCESS_CLEANUP_WAIT_SECONDS) for process in harness_owned: if adapter.is_running(process): adapter.force_stop(process) forced.append(process) raw_remaining = adapter.discover() except Exception as exc: errors.append(f"process_control_failed:{exc}") return result("fail", audited=True) remaining: list[dict[str, Any]] = [] if not isinstance(raw_remaining, list): errors.append("final_process_discovery_failed:not_an_array") else: for raw_process in raw_remaining: process, process_errors = _process_identity_errors(raw_process, td_root=root) errors.extend(process_errors) if process is not None: remaining.append(process) if remaining: errors.append("qualified_processes_remaining") return result("pass" if not errors else "fail", remaining=remaining, audited=True) def audit_td_processes( td_root: Path, *, ownership_policy: dict[str, Any], process_adapter: Any | None = None, ) -> dict[str, Any]: """Perform a non-destructive post-action audit of all TD candidates.""" root = str(td_root.resolve()) adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter() errors = _validate_ownership_policy(ownership_policy) discovered: list[dict[str, Any]] = [] harness_owned: list[dict[str, Any]] = [] blocking: list[dict[str, Any]] = [] audit_completed = False if not errors: try: raw_processes = adapter.discover() except Exception as exc: errors.append(f"post_action_process_discovery_failed:{exc}") raw_processes = [] if not isinstance(raw_processes, list): errors.append("post_action_process_discovery_failed:not_an_array") else: for raw_process in raw_processes: process, process_errors = _process_identity_errors(raw_process, td_root=root) errors.extend(process_errors) if process is not None: discovered.append(process) audit_completed = not errors if not errors: for process in discovered: if _is_harness_owned(process, ownership_policy): harness_owned.append(process) else: blocking.append(process) if discovered: errors.append("post_action_td_processes_remaining") return { "status": "pass" if not errors else "fail", "post_action_audit_completed": audit_completed, "post_action_discovered_processes": discovered, "post_action_harness_owned_processes": harness_owned, "post_action_blocking_processes": blocking, "residual_processes": discovered, "post_action_errors": list(dict.fromkeys(errors)), } 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), ] class _StartupInfoW(ctypes.Structure): _fields_ = [ ("cb", wintypes.DWORD), ("lpReserved", wintypes.LPWSTR), ("lpDesktop", wintypes.LPWSTR), ("lpTitle", wintypes.LPWSTR), ("dwX", wintypes.DWORD), ("dwY", wintypes.DWORD), ("dwXSize", wintypes.DWORD), ("dwYSize", wintypes.DWORD), ("dwXCountChars", wintypes.DWORD), ("dwYCountChars", wintypes.DWORD), ("dwFillAttribute", wintypes.DWORD), ("dwFlags", wintypes.DWORD), ("wShowWindow", wintypes.WORD), ("cbReserved2", wintypes.WORD), ("lpReserved2", ctypes.POINTER(wintypes.BYTE)), ("hStdInput", wintypes.HANDLE), ("hStdOutput", wintypes.HANDLE), ("hStdError", wintypes.HANDLE), ] class _ProcessInformation(ctypes.Structure): _fields_ = [ ("hProcess", wintypes.HANDLE), ("hThread", wintypes.HANDLE), ("dwProcessId", wintypes.DWORD), ("dwThreadId", wintypes.DWORD), ] 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.CreateProcessW.argtypes = [ wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, wintypes.BOOL, wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(_StartupInfoW), ctypes.POINTER(_ProcessInformation), ] kernel32.CreateProcessW.restype = wintypes.BOOL kernel32.ResumeThread.argtypes = [wintypes.HANDLE] kernel32.ResumeThread.restype = wintypes.DWORD kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] kernel32.WaitForSingleObject.restype = wintypes.DWORD kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] kernel32.GetExitCodeProcess.restype = wintypes.BOOL kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT] kernel32.TerminateProcess.restype = wintypes.BOOL kernel32.SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD] kernel32.SetHandleInformation.restype = wintypes.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") CREATE_SUSPENDED = 0x00000004 STARTF_USESTDHANDLES = 0x00000100 HANDLE_FLAG_INHERIT = 0x00000001 WAIT_OBJECT_0 = 0x00000000 WAIT_TIMEOUT = 0x00000102 INFINITE = 0xFFFFFFFF stdout_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None stderr_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None stdin_file = open(os.devnull, "rb") if capture_output else None inherited_handles: list[int] = [] startup = _StartupInfoW() startup.cb = ctypes.sizeof(startup) if capture_output: import msvcrt startup.dwFlags = STARTF_USESTDHANDLES startup.hStdInput = wintypes.HANDLE(msvcrt.get_osfhandle(stdin_file.fileno())) startup.hStdOutput = wintypes.HANDLE(msvcrt.get_osfhandle(stdout_file.fileno())) startup.hStdError = wintypes.HANDLE(msvcrt.get_osfhandle(stderr_file.fileno())) inherited_handles = [ int(startup.hStdInput), int(startup.hStdOutput), int(startup.hStdError), ] for handle in inherited_handles: if not kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT): raise OSError(ctypes.get_last_error(), "SetHandleInformation failed") process_info = _ProcessInformation() command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline(command)) created = False try: if not kernel32.CreateProcessW( str(command[0]), command_line, None, None, bool(capture_output), CREATE_SUSPENDED, None, cwd, ctypes.byref(startup), ctypes.byref(process_info), ): raise OSError(ctypes.get_last_error(), "CreateProcessW failed") created = True if not kernel32.AssignProcessToJobObject(job, process_info.hProcess): error = ctypes.get_last_error() kernel32.TerminateProcess(process_info.hProcess, 1) kernel32.WaitForSingleObject(process_info.hProcess, INFINITE) raise OSError(error, "AssignProcessToJobObject failed") if kernel32.ResumeThread(process_info.hThread) == 0xFFFFFFFF: error = ctypes.get_last_error() kernel32.TerminateJobObject(job, 1) kernel32.WaitForSingleObject(process_info.hProcess, INFINITE) raise OSError(error, "ResumeThread failed") wait_milliseconds = max(0, min(int(timeout * 1000), 0xFFFFFFFE)) wait_result = kernel32.WaitForSingleObject(process_info.hProcess, wait_milliseconds) timed_out = wait_result == WAIT_TIMEOUT if timed_out: kernel32.TerminateJobObject(job, 1) kernel32.WaitForSingleObject(process_info.hProcess, INFINITE) elif wait_result != WAIT_OBJECT_0: raise OSError(ctypes.get_last_error(), "WaitForSingleObject failed") exit_code = wintypes.DWORD() if not kernel32.GetExitCodeProcess(process_info.hProcess, ctypes.byref(exit_code)): raise OSError(ctypes.get_last_error(), "GetExitCodeProcess failed") encoding = locale.getpreferredencoding(False) stdout: str | bytes | None = None stderr: str | bytes | None = None if capture_output: stdout_file.seek(0) stderr_file.seek(0) stdout_bytes = stdout_file.read() stderr_bytes = stderr_file.read() stdout = stdout_bytes.decode(encoding, errors="replace") if text else stdout_bytes stderr = stderr_bytes.decode(encoding, errors="replace") if text else stderr_bytes if timed_out: raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr) result = subprocess.CompletedProcess(command, int(exit_code.value), stdout, stderr) if check and result.returncode != 0: raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr) return result finally: for handle in inherited_handles: kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, 0) if created: kernel32.CloseHandle(process_info.hThread) kernel32.CloseHandle(process_info.hProcess) if stdin_file is not None: stdin_file.close() if stdout_file is not None: stdout_file.close() if stderr_file is not None: stderr_file.close() 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[..., dict[str, Any]] = close_td_processes, residual_audit_runner: Callable[..., dict[str, Any]] = audit_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" tcl_cli_path = tcl_path.absolute().as_posix() command = [str(bw_exe), tcl_cli_path] ownership_policy = build_process_ownership_policy(executable=bw_exe, command=command) started_at = utc_now() start_monotonic = time.monotonic() with mutex_factory(): cleanup = cleanup_runner(td_root, ownership_policy=ownership_policy) 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: completed = process_runner( command, 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) residual_audit = residual_audit_runner(td_root, ownership_policy=ownership_policy) for field in ( "post_action_audit_completed", "post_action_discovered_processes", "post_action_harness_owned_processes", "post_action_blocking_processes", "residual_processes", "post_action_errors", ): cleanup[field] = residual_audit.get(field) cleanup["status"] = "pass" if residual_audit.get("status") == "pass" else "fail" 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 residual_audit.get("status") != "pass": receipt["parser"]["failures"].append("post_action_process_audit_failed") 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 "" 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, or real PTC/FAN load behavior; " "Normal v3 has no local closed-loop control." ), } 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())