prod2u_programmer.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. #!/usr/bin/env python3
  2. """Strict Prod2U PROGRAM_SRAM transaction parser and Tcl generator."""
  3. from __future__ import annotations
  4. import argparse
  5. import ctypes
  6. import hashlib
  7. import json
  8. import ntpath
  9. import os
  10. import re
  11. import shutil
  12. import subprocess
  13. import time
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. from typing import Any, Callable
  17. SCHEMA_NAME = "prod2u-program-sram-receipt-v1"
  18. TARGET_CHIP = "EF2L45"
  19. JTAG_SPEED_CODE = 2
  20. JTAG_SPEED_HZ = 200000
  21. BIT_TO_VEC_FREQUENCY = "0.200000"
  22. EXPECTED_MARKERS = (
  23. "download_start",
  24. "chip_validation",
  25. "bit_to_vec_start",
  26. "bit_to_vec_finish",
  27. "program_start",
  28. "program_finish",
  29. "download_finish",
  30. )
  31. SETUP_MARKERS = ("connect_cable_start", "connect_cable_finish")
  32. BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
  33. SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
  34. ERROR_RE = re.compile(
  35. r"\b(?:PRG-8\d{3}|ERROR|FATAL|failed|couldn't read file|invalid command name)\b",
  36. re.IGNORECASE,
  37. )
  38. FORBIDDEN_RE = re.compile(
  39. r"(?<![A-Za-z0-9])(?:flash|erase|spi(?:bin)?|nonvolatile)(?![A-Za-z0-9])",
  40. re.IGNORECASE,
  41. )
  42. START_COMMAND_RE = re.compile(r'^RUN-1002\s*:\s*start command "(?P<command>.+)"\s*$')
  43. FINISH_COMMAND_RE = re.compile(r'^RUN-1003\s*:\s*finish command "(?P<command>.+)"(?:\s+in\s+.+)?$')
  44. CHIP_RE = re.compile(r"^PRG-2014\s*:\s*Chip validation success:\s*(?P<chip>\S+)\s*$")
  45. DOWNLOAD_RE = re.compile(
  46. r"^download\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s+"
  47. r"-mode\s+(?P<mode>\S+)\s+-spd\s+(?P<speed>\d+)\s+-cable\s+(?P<cable>\d+)\s*$"
  48. )
  49. BIT_TO_VEC_RE = re.compile(
  50. r"^bit_to_vec\s+-chip\s+(?P<chip>\S+)\s+-m\s+(?P<mode>\S+)\s+"
  51. r"-freq\s+(?P<freq>\S+)\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s*$"
  52. )
  53. PROGRAM_RE = re.compile(
  54. r"^program\s+-cable\s+(?P<cable>\d+)\s+-mode\s+(?P<mode>\S+)\s+"
  55. r"-spd\s+(?P<speed>\d+)\s+-p\s*$"
  56. )
  57. PROGRAM_TIMEOUT_SECONDS = 60
  58. PROCESS_CLEANUP_WAIT_SECONDS = 5.0
  59. MUTEX_NAME = r"Global\Prod2UProgramSram"
  60. def utc_now() -> str:
  61. return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  62. def sha256_bytes(data: bytes) -> str:
  63. return hashlib.sha256(data).hexdigest()
  64. def sha256_file(path: Path) -> str:
  65. digest = hashlib.sha256()
  66. with path.open("rb") as stream:
  67. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  68. digest.update(chunk)
  69. return digest.hexdigest()
  70. def staged_bitstream_path(build_id: str) -> str:
  71. """Return the only accepted Windows staging path for a build identity."""
  72. if not BUILD_ID_RE.fullmatch(build_id):
  73. raise ValueError("build_id must be eight uppercase hexadecimal characters")
  74. return f"C:\\P2U\\{build_id}\\fw.bit"
  75. def _strip_path_token(value: str) -> str:
  76. if value.startswith("{") and value.endswith("}"):
  77. return value[1:-1]
  78. if value.startswith('"') and value.endswith('"'):
  79. return value[1:-1]
  80. return value
  81. def _canonical_windows_path(value: str, *, td_bin: str) -> str:
  82. normalized = _strip_path_token(value).replace("/", "\\")
  83. if not ntpath.isabs(normalized):
  84. normalized = ntpath.join(td_bin, normalized)
  85. return ntpath.normcase(ntpath.normpath(normalized))
  86. def build_program_tcl(bitstream_path: str) -> str:
  87. """Generate the fixed one-attempt SRAM-only BitWriter Tcl program."""
  88. canonical = ntpath.normpath(bitstream_path)
  89. match = re.fullmatch(r"C:\\P2U\\([0-9A-F]{8})\\fw\.bit", canonical, re.IGNORECASE)
  90. if match is None:
  91. raise ValueError("bitstream_path must be C:\\P2U\\<BUILD_ID>\\fw.bit")
  92. build_id = match.group(1).upper()
  93. expected = staged_bitstream_path(build_id).replace("\\", "/")
  94. return (
  95. "connect_cable -allink\n"
  96. f"download -bit {{{expected}}} -mode jtag -spd 2 -cable 0\n"
  97. "exit\n"
  98. )
  99. class WindowsNamedMutex:
  100. """Non-waiting process-wide PROGRAM_SRAM lock backed by a Windows mutex."""
  101. def __init__(self, name: str = MUTEX_NAME) -> None:
  102. self.name = name
  103. self.handle: int | None = None
  104. def __enter__(self) -> "WindowsNamedMutex":
  105. if os.name != "nt":
  106. raise RuntimeError("Prod2U PROGRAM_SRAM is supported only on Windows")
  107. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  108. kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
  109. kernel32.CreateMutexW.restype = ctypes.c_void_p
  110. kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
  111. kernel32.WaitForSingleObject.restype = ctypes.c_uint32
  112. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  113. kernel32.CloseHandle.restype = ctypes.c_bool
  114. handle = kernel32.CreateMutexW(None, False, self.name)
  115. if not handle:
  116. raise OSError(ctypes.get_last_error(), "CreateMutexW failed")
  117. result = kernel32.WaitForSingleObject(handle, 0)
  118. if result not in (0x00000000, 0x00000080):
  119. kernel32.CloseHandle(handle)
  120. raise TimeoutError("Prod2U PROGRAM_SRAM mutex busy")
  121. self.handle = int(handle)
  122. return self
  123. def __exit__(self, exc_type, exc, tb) -> bool:
  124. if self.handle is not None:
  125. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  126. kernel32.ReleaseMutex.argtypes = [ctypes.c_void_p]
  127. kernel32.ReleaseMutex.restype = ctypes.c_bool
  128. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  129. kernel32.CloseHandle.restype = ctypes.c_bool
  130. kernel32.ReleaseMutex(ctypes.c_void_p(self.handle))
  131. kernel32.CloseHandle(ctypes.c_void_p(self.handle))
  132. self.handle = None
  133. return False
  134. def close_td_processes(td_root: Path) -> dict[str, Any]:
  135. """Gracefully close, then bound-force-close, TD processes from one install root."""
  136. root = str(td_root.resolve())
  137. script = r'''
  138. $ErrorActionPreference = 'Stop'
  139. if ([string]::IsNullOrWhiteSpace($env:PROD2U_TD_ROOT)) { throw 'PROD2U_TD_ROOT is required' }
  140. $root = [System.IO.Path]::GetFullPath($env:PROD2U_TD_ROOT).TrimEnd('\')
  141. $rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar
  142. $allowed = @('td','bw','bitwriter','chipwatcher','bw_commands_prompt')
  143. function Find-TdProcesses {
  144. @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
  145. try {
  146. $path = $_.Path
  147. $fullPath = [System.IO.Path]::GetFullPath($path)
  148. $path -and
  149. ($fullPath.Equals($root, [System.StringComparison]::OrdinalIgnoreCase) -or
  150. $fullPath.StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)) -and
  151. ($allowed -contains $_.ProcessName.ToLowerInvariant())
  152. } catch { $false }
  153. })
  154. }
  155. $initial = Find-TdProcesses
  156. $graceful = @()
  157. foreach ($process in $initial) {
  158. $null = $process.CloseMainWindow()
  159. $graceful += ('{0}:{1}' -f $process.ProcessName, $process.Id)
  160. }
  161. Start-Sleep -Seconds 5
  162. $survivors = Find-TdProcesses
  163. $forced = @()
  164. foreach ($process in $survivors) {
  165. Stop-Process -Id $process.Id -Force -ErrorAction Stop
  166. $forced += ('{0}:{1}' -f $process.ProcessName, $process.Id)
  167. }
  168. Start-Sleep -Milliseconds 250
  169. $remaining = @(Find-TdProcesses | ForEach-Object { '{0}:{1}' -f $_.ProcessName, $_.Id })
  170. [ordered]@{
  171. status = $(if ($remaining.Count -eq 0) { 'pass' } else { 'fail' })
  172. td_root = $root
  173. graceful_close_requested = $graceful
  174. forced_terminated = $forced
  175. wait_seconds = 5.0
  176. remaining = $remaining
  177. } | ConvertTo-Json -Compress
  178. '''
  179. env = os.environ.copy()
  180. env["PROD2U_TD_ROOT"] = root
  181. result = subprocess.run(
  182. ["powershell.exe", "-NoProfile", "-Command", script],
  183. capture_output=True,
  184. text=True,
  185. check=False,
  186. timeout=15,
  187. env=env,
  188. )
  189. if result.returncode != 0:
  190. return {
  191. "status": "fail",
  192. "td_root": root,
  193. "graceful_close_requested": [],
  194. "forced_terminated": [],
  195. "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
  196. "remaining": [],
  197. "error": result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}",
  198. }
  199. try:
  200. payload = json.loads(result.stdout)
  201. except json.JSONDecodeError as exc:
  202. return {
  203. "status": "fail",
  204. "td_root": root,
  205. "graceful_close_requested": [],
  206. "forced_terminated": [],
  207. "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
  208. "remaining": [],
  209. "error": f"invalid process cleanup JSON: {exc}",
  210. }
  211. return payload
  212. def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
  213. if not log_dir.is_dir():
  214. return {}
  215. snapshot: dict[str, dict[str, int]] = {}
  216. for path in log_dir.glob("bw_*.log"):
  217. if not path.is_file():
  218. continue
  219. stat = path.stat()
  220. snapshot[str(path.resolve())] = {
  221. "size": stat.st_size,
  222. "file_id": stat.st_ino,
  223. "created_ns": stat.st_ctime_ns,
  224. }
  225. return snapshot
  226. def _read_bitwriter_log_deltas(
  227. log_dir: Path,
  228. before: dict[str, dict[str, int]],
  229. ) -> tuple[bytes, list[dict[str, Any]], list[str]]:
  230. chunks: list[bytes] = []
  231. sources: list[dict[str, Any]] = []
  232. issues: list[str] = []
  233. if not log_dir.is_dir():
  234. return b"", sources, issues
  235. for path in sorted(log_dir.glob("bw_*.log"), key=lambda candidate: candidate.name.casefold()):
  236. if not path.is_file():
  237. continue
  238. resolved = str(path.resolve())
  239. previous = before.get(resolved)
  240. stat = path.stat()
  241. size = stat.st_size
  242. start = int(previous["size"]) if previous is not None else 0
  243. if previous is not None and (
  244. stat.st_ino != int(previous["file_id"])
  245. or stat.st_ctime_ns != int(previous["created_ns"])
  246. or size < start
  247. ):
  248. issues.append("bitwriter_log_replaced_or_truncated")
  249. continue
  250. if size == start:
  251. continue
  252. with path.open("rb") as stream:
  253. stream.seek(start)
  254. data = stream.read()
  255. if not data:
  256. continue
  257. chunks.append(data)
  258. sources.append(
  259. {
  260. "path": resolved,
  261. "start_offset": start,
  262. "byte_count": len(data),
  263. "sha256": sha256_bytes(data),
  264. }
  265. )
  266. return b"\n".join(chunks), sources, list(dict.fromkeys(issues))
  267. class _IoCounters(ctypes.Structure):
  268. _fields_ = [
  269. ("ReadOperationCount", ctypes.c_uint64),
  270. ("WriteOperationCount", ctypes.c_uint64),
  271. ("OtherOperationCount", ctypes.c_uint64),
  272. ("ReadTransferCount", ctypes.c_uint64),
  273. ("WriteTransferCount", ctypes.c_uint64),
  274. ("OtherTransferCount", ctypes.c_uint64),
  275. ]
  276. class _JobBasicLimitInformation(ctypes.Structure):
  277. _fields_ = [
  278. ("PerProcessUserTimeLimit", ctypes.c_int64),
  279. ("PerJobUserTimeLimit", ctypes.c_int64),
  280. ("LimitFlags", ctypes.c_uint32),
  281. ("MinimumWorkingSetSize", ctypes.c_size_t),
  282. ("MaximumWorkingSetSize", ctypes.c_size_t),
  283. ("ActiveProcessLimit", ctypes.c_uint32),
  284. ("Affinity", ctypes.c_size_t),
  285. ("PriorityClass", ctypes.c_uint32),
  286. ("SchedulingClass", ctypes.c_uint32),
  287. ]
  288. class _JobExtendedLimitInformation(ctypes.Structure):
  289. _fields_ = [
  290. ("BasicLimitInformation", _JobBasicLimitInformation),
  291. ("IoInfo", _IoCounters),
  292. ("ProcessMemoryLimit", ctypes.c_size_t),
  293. ("JobMemoryLimit", ctypes.c_size_t),
  294. ("PeakProcessMemoryUsed", ctypes.c_size_t),
  295. ("PeakJobMemoryUsed", ctypes.c_size_t),
  296. ]
  297. def windows_process_is_running(pid: int) -> bool:
  298. if os.name != "nt":
  299. return False
  300. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  301. kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_bool, ctypes.c_uint32]
  302. kernel32.OpenProcess.restype = ctypes.c_void_p
  303. kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
  304. kernel32.WaitForSingleObject.restype = ctypes.c_uint32
  305. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  306. kernel32.CloseHandle.restype = ctypes.c_bool
  307. handle = kernel32.OpenProcess(0x00100000, False, int(pid))
  308. if not handle:
  309. return False
  310. try:
  311. return kernel32.WaitForSingleObject(handle, 0) == 0x00000102
  312. finally:
  313. kernel32.CloseHandle(handle)
  314. def run_process_in_job(
  315. command: list[str],
  316. *,
  317. cwd: str,
  318. timeout: float,
  319. capture_output: bool,
  320. text: bool,
  321. check: bool,
  322. ) -> subprocess.CompletedProcess[str]:
  323. """Run one process in a kill-on-close Windows Job Object."""
  324. if os.name != "nt":
  325. return subprocess.run(
  326. command,
  327. cwd=cwd,
  328. timeout=timeout,
  329. capture_output=capture_output,
  330. text=text,
  331. check=check,
  332. )
  333. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  334. kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
  335. kernel32.CreateJobObjectW.restype = ctypes.c_void_p
  336. kernel32.SetInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
  337. kernel32.SetInformationJobObject.restype = ctypes.c_bool
  338. kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
  339. kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
  340. kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
  341. kernel32.TerminateJobObject.restype = ctypes.c_bool
  342. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  343. kernel32.CloseHandle.restype = ctypes.c_bool
  344. job = kernel32.CreateJobObjectW(None, None)
  345. if not job:
  346. raise OSError(ctypes.get_last_error(), "CreateJobObjectW failed")
  347. info = _JobExtendedLimitInformation()
  348. info.BasicLimitInformation.LimitFlags = 0x00002000
  349. if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
  350. error = ctypes.get_last_error()
  351. kernel32.CloseHandle(job)
  352. raise OSError(error, "SetInformationJobObject failed")
  353. stdout_pipe = subprocess.PIPE if capture_output else None
  354. stderr_pipe = subprocess.PIPE if capture_output else None
  355. process = subprocess.Popen(
  356. command,
  357. cwd=cwd,
  358. stdout=stdout_pipe,
  359. stderr=stderr_pipe,
  360. text=text,
  361. )
  362. try:
  363. if not kernel32.AssignProcessToJobObject(job, ctypes.c_void_p(int(process._handle))):
  364. process.kill()
  365. process.wait()
  366. raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
  367. try:
  368. stdout, stderr = process.communicate(timeout=timeout)
  369. except subprocess.TimeoutExpired as exc:
  370. kernel32.TerminateJobObject(job, 1)
  371. stdout, stderr = process.communicate()
  372. raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr) from exc
  373. result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
  374. if check and result.returncode != 0:
  375. raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
  376. return result
  377. finally:
  378. kernel32.CloseHandle(job)
  379. def _artifact(path: Path) -> dict[str, Any]:
  380. return {"path": str(path), "size": path.stat().st_size, "sha256": sha256_file(path)}
  381. def _recompute_receipt_status(receipt: dict[str, Any]) -> None:
  382. failures = list(dict.fromkeys(receipt["parser"]["failures"]))
  383. receipt["parser"]["failures"] = failures
  384. receipt["parser"]["status"] = "pass" if not failures else "fail"
  385. if any(failure.startswith("forbidden_action:") for failure in failures):
  386. receipt["status"] = "fail_forbidden_action"
  387. else:
  388. receipt["status"] = receipt["parser"]["status"]
  389. def execute_program_sram(
  390. *,
  391. source_bitstream: Path,
  392. expected_bitstream_sha256: str,
  393. build_id: str,
  394. output_dir: Path,
  395. td_root: Path,
  396. run_id: str,
  397. process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
  398. cleanup_runner: Callable[[Path], dict[str, Any]] = close_td_processes,
  399. mutex_factory: Callable[[], Any] = WindowsNamedMutex,
  400. ) -> dict[str, Any]:
  401. """Execute exactly one SRAM download and return a strict transaction receipt."""
  402. source_bitstream = Path(source_bitstream)
  403. output_dir = Path(output_dir)
  404. td_root = Path(td_root)
  405. if output_dir.exists() and any(output_dir.iterdir()):
  406. raise FileExistsError(f"output directory is not empty: {output_dir}")
  407. if not source_bitstream.is_file():
  408. raise FileNotFoundError(source_bitstream)
  409. if not SHA256_RE.fullmatch(expected_bitstream_sha256):
  410. raise ValueError("expected bitstream SHA256 must be 64 hexadecimal characters")
  411. source_sha256 = sha256_file(source_bitstream)
  412. if source_sha256.casefold() != expected_bitstream_sha256.casefold():
  413. raise ValueError("bitstream SHA256 mismatch before staging")
  414. staged = Path(staged_bitstream_path(build_id))
  415. bw_exe = td_root / "bin" / "bw_commands_prompt.exe"
  416. if not bw_exe.is_file():
  417. raise FileNotFoundError(bw_exe)
  418. output_dir.mkdir(parents=True, exist_ok=True)
  419. tcl_path = output_dir / "program-sram.tcl"
  420. stdout_path = output_dir / "bitwriter-stdout.log"
  421. stderr_path = output_dir / "bitwriter-stderr.log"
  422. delta_path = output_dir / "bitwriter-log-delta.log"
  423. started_at = utc_now()
  424. start_monotonic = time.monotonic()
  425. with mutex_factory():
  426. cleanup = cleanup_runner(td_root)
  427. if cleanup.get("status") != "pass":
  428. raise RuntimeError(f"TD process cleanup failed: {cleanup}")
  429. stage_root = staged.parent.parent
  430. stage_root.mkdir(parents=True, exist_ok=True)
  431. staged.parent.mkdir(parents=True, exist_ok=True)
  432. if ntpath.normcase(str(staged.parent.resolve().parent)) != ntpath.normcase(str(stage_root.resolve())):
  433. raise ValueError("staging build directory resolves outside C:\\P2U")
  434. staged_temp = staged.parent / f".{staged.name}.{os.getpid()}.{time.time_ns()}.tmp"
  435. try:
  436. shutil.copy2(source_bitstream, staged_temp)
  437. if sha256_file(staged_temp).casefold() != expected_bitstream_sha256.casefold():
  438. raise ValueError("bitstream SHA256 mismatch in staging temporary file")
  439. os.replace(staged_temp, staged)
  440. finally:
  441. if staged_temp.exists():
  442. staged_temp.unlink()
  443. staged_sha256 = sha256_file(staged)
  444. if staged_sha256.casefold() != expected_bitstream_sha256.casefold():
  445. raise ValueError("bitstream SHA256 mismatch after staging")
  446. tcl_path.write_text(build_program_tcl(str(staged)), encoding="ascii", newline="\n")
  447. log_dir = td_root / "bin" / "log"
  448. before = _snapshot_bitwriter_logs(log_dir)
  449. timed_out = False
  450. try:
  451. tcl_cli_path = tcl_path.absolute().as_posix()
  452. completed = process_runner(
  453. [str(bw_exe), tcl_cli_path],
  454. cwd=str(td_root / "bin"),
  455. timeout=PROGRAM_TIMEOUT_SECONDS,
  456. capture_output=True,
  457. text=True,
  458. check=False,
  459. )
  460. exit_code = int(completed.returncode)
  461. stdout = completed.stdout or ""
  462. stderr = completed.stderr or ""
  463. except subprocess.TimeoutExpired as exc:
  464. timed_out = True
  465. exit_code = -1
  466. stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
  467. stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
  468. delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
  469. stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
  470. stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
  471. delta_path.write_bytes(delta_bytes)
  472. parser_text = delta_bytes.decode("utf-8", errors="replace") if len(delta_sources) == 1 and not delta_issues else ""
  473. receipt = build_program_sram_receipt(
  474. transcript=parser_text,
  475. build_id=build_id,
  476. bitstream_path=str(staged),
  477. bitstream_bytes=staged.read_bytes(),
  478. expected_bitstream_sha256=expected_bitstream_sha256,
  479. exit_code=exit_code,
  480. run_id=run_id,
  481. command_execution_attempted=True,
  482. timed_out=timed_out,
  483. td_bin=str(td_root / "bin"),
  484. )
  485. authoritative_marker_signature = _marker_signature(parser_text)
  486. if not delta_bytes:
  487. receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
  488. receipt["parser"]["ordered_markers_complete"] = False
  489. if len(delta_sources) > 1:
  490. receipt["parser"]["failures"].append("ambiguous_bitwriter_log_sources")
  491. receipt["parser"]["ordered_markers_complete"] = False
  492. receipt["parser"]["failures"].extend(delta_issues)
  493. for stream_name, output in (("stdout", stdout), ("stderr", stderr)):
  494. output_failures, output_error_markers, output_forbidden = _transcript_failures(output)
  495. receipt["parser"]["failures"].extend(output_failures)
  496. receipt["parser"]["error_markers"] = list(
  497. dict.fromkeys(receipt["parser"]["error_markers"] + output_error_markers)
  498. )
  499. if _contains_transaction_marker(output):
  500. output_signature = _marker_signature(output)
  501. if (
  502. stream_name == "stdout"
  503. and authoritative_marker_signature
  504. and output_signature == authoritative_marker_signature
  505. ):
  506. receipt["parser"]["stdout_transaction_mirror"] = True
  507. else:
  508. receipt["parser"]["failures"].append(f"transaction_marker_mismatch:{stream_name}")
  509. if output_forbidden:
  510. receipt["safety"]["flash_attempted"] = True
  511. receipt["safety"]["programs_nonvolatile"] = True
  512. receipt["execution"].update(
  513. {
  514. "timeout_seconds": PROGRAM_TIMEOUT_SECONDS,
  515. "started_at": started_at,
  516. "finished_at": utc_now(),
  517. "duration_seconds": round(time.monotonic() - start_monotonic, 6),
  518. }
  519. )
  520. receipt["tool"] = {
  521. "path": str(bw_exe),
  522. "td_root": str(td_root),
  523. "td_bin": str(td_root / "bin"),
  524. }
  525. receipt["mutex"] = {"name": MUTEX_NAME, "acquired": True}
  526. receipt["process_cleanup"] = cleanup
  527. receipt["artifacts"] = {
  528. "tcl": _artifact(tcl_path),
  529. "stdout": _artifact(stdout_path),
  530. "stderr": _artifact(stderr_path),
  531. "log_delta": _artifact(delta_path),
  532. "log_delta_sources": delta_sources,
  533. }
  534. _recompute_receipt_status(receipt)
  535. receipt_path = output_dir / "program-sram-receipt.json"
  536. receipt_temp = output_dir / ".program-sram-receipt.json.tmp"
  537. receipt_temp.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8", newline="\n")
  538. os.replace(receipt_temp, receipt_path)
  539. return receipt
  540. def _contains_transaction_marker(transcript: str) -> bool:
  541. return any(
  542. START_COMMAND_RE.match(line.strip())
  543. or FINISH_COMMAND_RE.match(line.strip())
  544. or CHIP_RE.match(line.strip())
  545. for line in transcript.splitlines()
  546. )
  547. def _marker_records(transcript: str) -> list[dict[str, Any]]:
  548. records: list[dict[str, Any]] = []
  549. for line_number, raw_line in enumerate(transcript.splitlines(), start=1):
  550. line = raw_line.strip()
  551. start = START_COMMAND_RE.match(line)
  552. finish = FINISH_COMMAND_RE.match(line)
  553. chip = CHIP_RE.match(line)
  554. if start:
  555. command = start.group("command")
  556. if command == "connect_cable -allink":
  557. records.append({"marker": "connect_cable_start", "command": command, "line": line_number})
  558. elif command.startswith("download "):
  559. records.append({"marker": "download_start", "command": command, "line": line_number})
  560. elif command.startswith("bit_to_vec "):
  561. records.append({"marker": "bit_to_vec_start", "command": command, "line": line_number})
  562. elif command.startswith("program "):
  563. records.append({"marker": "program_start", "command": command, "line": line_number})
  564. else:
  565. records.append(
  566. {
  567. "marker": "unrecognized_run_operation",
  568. "operation": _operation_name(command),
  569. "line": line_number,
  570. }
  571. )
  572. elif finish:
  573. command = finish.group("command")
  574. if command == "connect_cable -allink":
  575. records.append({"marker": "connect_cable_finish", "command": command, "line": line_number})
  576. elif command.startswith("bit_to_vec "):
  577. records.append({"marker": "bit_to_vec_finish", "command": command, "line": line_number})
  578. elif command.startswith("program "):
  579. records.append({"marker": "program_finish", "command": command, "line": line_number})
  580. elif command.startswith("download "):
  581. records.append({"marker": "download_finish", "command": command, "line": line_number})
  582. else:
  583. records.append(
  584. {
  585. "marker": "unrecognized_run_operation",
  586. "operation": _operation_name(command),
  587. "line": line_number,
  588. }
  589. )
  590. elif chip:
  591. records.append(
  592. {
  593. "marker": "chip_validation",
  594. "chip": chip.group("chip"),
  595. "line": line_number,
  596. }
  597. )
  598. return records
  599. def _operation_name(command: str) -> str:
  600. parts = command.split(maxsplit=1)
  601. return parts[0].casefold() if parts else "<empty>"
  602. def _marker_failures(records: list[dict[str, Any]]) -> list[str]:
  603. failures: list[str] = []
  604. observed_all = [str(record["marker"]) for record in records]
  605. observed = [marker for marker in observed_all if marker in EXPECTED_MARKERS]
  606. setup_observed = [marker for marker in observed_all if marker in SETUP_MARKERS]
  607. for record in records:
  608. if record["marker"] == "unrecognized_run_operation":
  609. failures.append(f"unrecognized_run_operation:{record['operation']}")
  610. if setup_observed and (
  611. setup_observed != list(SETUP_MARKERS)
  612. or observed_all[: len(SETUP_MARKERS)] != list(SETUP_MARKERS)
  613. ):
  614. failures.append("connect_cable_marker_mismatch")
  615. if any(observed.count(expected) != 1 for expected in EXPECTED_MARKERS) or any(
  616. marker == "unrecognized_run_operation" for marker in observed_all
  617. ):
  618. failures.append("transaction_count_not_one")
  619. for index, expected in enumerate(EXPECTED_MARKERS):
  620. if expected not in observed:
  621. failures.append(f"missing_marker:{expected}")
  622. elif index >= len(observed) or observed[index] != expected:
  623. failures.append(f"out_of_order_marker:{expected}")
  624. if len(observed) != len(EXPECTED_MARKERS) and not any(
  625. failure == "transaction_count_not_one" for failure in failures
  626. ):
  627. failures.append("marker_count_mismatch")
  628. return failures
  629. def _marker_signature(transcript: str) -> list[tuple[str, str]]:
  630. signature: list[tuple[str, str]] = []
  631. for record in _marker_records(transcript):
  632. detail = str(record.get("command") or record.get("chip") or record.get("operation") or "")
  633. signature.append((str(record["marker"]), detail))
  634. return signature
  635. def _record(records: list[dict[str, Any]], marker: str) -> dict[str, Any] | None:
  636. matches = [record for record in records if record["marker"] == marker]
  637. return matches[0] if len(matches) == 1 else None
  638. def _command_failures(
  639. records: list[dict[str, Any]], *, expected_staging_path: str, td_bin: str
  640. ) -> tuple[list[str], dict[str, Any]]:
  641. failures: list[str] = []
  642. details: dict[str, Any] = {}
  643. expected_path = _canonical_windows_path(expected_staging_path, td_bin=td_bin)
  644. chip = _record(records, "chip_validation")
  645. if chip is not None and chip.get("chip") != TARGET_CHIP:
  646. failures.append("chip_mismatch")
  647. observed_paths: list[str] = []
  648. for marker in ("download_start", "download_finish"):
  649. record = _record(records, marker)
  650. if record is None:
  651. continue
  652. command = str(record["command"])
  653. parsed = DOWNLOAD_RE.match(command)
  654. if parsed is None:
  655. failures.append("download_command_mismatch")
  656. continue
  657. if parsed.group("mode") != "jtag" or parsed.group("cable") != "0":
  658. failures.append("download_command_mismatch")
  659. if parsed.group("speed") != str(JTAG_SPEED_CODE):
  660. failures.append("jtag_speed_mismatch")
  661. observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
  662. for marker in ("bit_to_vec_start", "bit_to_vec_finish"):
  663. record = _record(records, marker)
  664. if record is None:
  665. continue
  666. command = str(record["command"])
  667. parsed = BIT_TO_VEC_RE.match(command)
  668. if parsed is None:
  669. failures.append("bit_to_vec_command_mismatch")
  670. continue
  671. if parsed.group("chip") != TARGET_CHIP:
  672. failures.append("chip_mismatch")
  673. if parsed.group("mode") != "jtag_burst":
  674. failures.append("bit_to_vec_mode_mismatch")
  675. if parsed.group("freq") != BIT_TO_VEC_FREQUENCY:
  676. failures.append("bit_to_vec_frequency_mismatch")
  677. observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
  678. for marker in ("program_start", "program_finish"):
  679. record = _record(records, marker)
  680. if record is None:
  681. continue
  682. command = str(record["command"])
  683. parsed = PROGRAM_RE.match(command)
  684. if parsed is None:
  685. failures.append("program_command_mismatch")
  686. continue
  687. if parsed.group("cable") != "0" or parsed.group("mode") != "svf":
  688. failures.append("program_command_mismatch")
  689. if parsed.group("speed") != str(JTAG_SPEED_CODE):
  690. failures.append("jtag_speed_mismatch")
  691. if observed_paths and any(path != expected_path for path in observed_paths):
  692. failures.append("staging_path_mismatch")
  693. if len(set(observed_paths)) > 1:
  694. failures.append("transaction_bitstream_path_mismatch")
  695. details["expected_staging_path"] = expected_path
  696. details["observed_bitstream_paths"] = sorted(set(observed_paths))
  697. return failures, details
  698. def _transcript_failures(transcript: str) -> tuple[list[str], list[str], bool]:
  699. failures: list[str] = []
  700. error_markers: list[str] = []
  701. forbidden = False
  702. for raw_line in transcript.splitlines():
  703. for match in ERROR_RE.finditer(raw_line):
  704. marker = match.group(0)
  705. if marker.casefold() not in {item.casefold() for item in error_markers}:
  706. error_markers.append(marker)
  707. failures.append(f"error_marker:{marker}")
  708. for match in FORBIDDEN_RE.finditer(raw_line):
  709. forbidden = True
  710. action = match.group(0).lower()
  711. failure = f"forbidden_action:{action}"
  712. if failure not in failures:
  713. failures.append(failure)
  714. return failures, error_markers, forbidden
  715. def build_program_sram_receipt(
  716. *,
  717. transcript: str,
  718. build_id: str,
  719. bitstream_path: str,
  720. bitstream_bytes: bytes,
  721. expected_bitstream_sha256: str,
  722. exit_code: int,
  723. run_id: str,
  724. command_execution_attempted: bool = False,
  725. timed_out: bool = False,
  726. td_bin: str = "",
  727. ) -> dict[str, Any]:
  728. """Build a strict receipt from the exact BitWriter log increment."""
  729. failures: list[str] = []
  730. try:
  731. expected_staging_path = staged_bitstream_path(build_id)
  732. except ValueError:
  733. expected_staging_path = ""
  734. failures.append("build_id_invalid")
  735. records = _marker_records(transcript)
  736. failures.extend(_marker_failures(records))
  737. command_failures, command_details = _command_failures(
  738. records,
  739. expected_staging_path=expected_staging_path,
  740. td_bin=td_bin,
  741. )
  742. failures.extend(command_failures)
  743. transcript_failures, error_markers, forbidden = _transcript_failures(transcript)
  744. failures.extend(transcript_failures)
  745. actual_sha256 = hashlib.sha256(bitstream_bytes).hexdigest()
  746. if not SHA256_RE.fullmatch(expected_bitstream_sha256):
  747. failures.append("bitstream_sha256_invalid")
  748. elif actual_sha256.casefold() != expected_bitstream_sha256.casefold():
  749. failures.append("bitstream_sha256_mismatch")
  750. staging_matches = (
  751. bool(expected_staging_path)
  752. and _canonical_windows_path(bitstream_path, td_bin=td_bin)
  753. == _canonical_windows_path(expected_staging_path, td_bin=td_bin)
  754. )
  755. if not staging_matches:
  756. failures.append("staging_path_mismatch")
  757. if exit_code != 0:
  758. failures.append("exit_code_nonzero")
  759. if not command_execution_attempted:
  760. failures.append("program_command_not_executed")
  761. if timed_out:
  762. failures.append("program_timeout")
  763. failures = list(dict.fromkeys(failures))
  764. transaction_records = [record for record in records if record["marker"] in EXPECTED_MARKERS]
  765. setup_records = [record for record in records if record["marker"] in SETUP_MARKERS]
  766. ordered_markers_complete = (
  767. [record["marker"] for record in transaction_records] == list(EXPECTED_MARKERS)
  768. and not any(failure.startswith(("missing_marker:", "out_of_order_marker:")) for failure in failures)
  769. and "connect_cable_marker_mismatch" not in failures
  770. )
  771. parser_status = "pass" if not failures else "fail"
  772. status = "fail_forbidden_action" if forbidden else parser_status
  773. return {
  774. "schema": SCHEMA_NAME,
  775. "status": status,
  776. "run_id": run_id,
  777. "request": {
  778. "operation": "PROGRAM_SRAM",
  779. "target_chip": TARGET_CHIP,
  780. "cable_index": 0,
  781. "speed_code": JTAG_SPEED_CODE,
  782. "speed_hz": JTAG_SPEED_HZ,
  783. "attempt_limit": 1,
  784. "power_cycle_allowed": False,
  785. },
  786. "bitstream": {
  787. "path": bitstream_path,
  788. "sha256": actual_sha256,
  789. "build_id": build_id,
  790. },
  791. "staging": {
  792. "expected_path": expected_staging_path,
  793. "observed_path": bitstream_path,
  794. "matches_expected_path": staging_matches,
  795. },
  796. "execution": {
  797. "exit_code": exit_code,
  798. "timed_out": timed_out,
  799. "attempt_count": 1,
  800. "retry_count": 0,
  801. "power_cycle_count": 0,
  802. "command_execution_attempted": command_execution_attempted,
  803. },
  804. "parser": {
  805. "status": parser_status,
  806. "exit_code_trusted": False,
  807. "ordered_markers": list(EXPECTED_MARKERS),
  808. "ordered_markers_complete": ordered_markers_complete,
  809. "observed_markers": [record["marker"] for record in transaction_records],
  810. "observed_marker_lines": [record["line"] for record in transaction_records],
  811. "setup_markers": [record["marker"] for record in setup_records],
  812. "setup_marker_lines": [record["line"] for record in setup_records],
  813. "stdout_transaction_mirror": False,
  814. "error_markers": error_markers,
  815. "failures": failures,
  816. "transcript_sha256": hashlib.sha256(transcript.encode("utf-8")).hexdigest(),
  817. **command_details,
  818. },
  819. "safety": {
  820. "flash_attempted": forbidden,
  821. "programs_nonvolatile": forbidden,
  822. "power_cycle_attempted": False,
  823. "driver_install_attempted": False,
  824. "toggles_dtr_rts": False,
  825. "real_ptc_fan_action_attempted": False,
  826. "external_programming_command_executed": command_execution_attempted,
  827. },
  828. "authority_boundary": (
  829. "This receipt proves only one parsed PROGRAM_SRAM transaction against the staged bitstream. "
  830. "It does not certify flash, thermal performance, real PTC/FAN load behavior, or PID closed-loop behavior."
  831. ),
  832. }
  833. def build_parser() -> argparse.ArgumentParser:
  834. parser = argparse.ArgumentParser(description=__doc__)
  835. parser.add_argument("--transcript", type=Path, required=True, help="captured BitWriter log increment")
  836. parser.add_argument("--bitstream", type=Path, required=True, help="staged bitstream to hash")
  837. parser.add_argument("--build-id", required=True)
  838. parser.add_argument("--sha256", required=True, dest="expected_bitstream_sha256")
  839. parser.add_argument("--exit-code", type=int, default=0, help="observed tool exit code")
  840. parser.add_argument("--run-id", required=True)
  841. parser.add_argument("--td-bin", default="")
  842. parser.add_argument("--receipt", type=Path, help="optional JSON receipt output path")
  843. return parser
  844. def main(argv: list[str] | None = None) -> int:
  845. args = build_parser().parse_args(argv)
  846. receipt = build_program_sram_receipt(
  847. transcript=args.transcript.read_text(encoding="utf-8", errors="replace"),
  848. build_id=args.build_id,
  849. bitstream_path=str(args.bitstream),
  850. bitstream_bytes=args.bitstream.read_bytes(),
  851. expected_bitstream_sha256=args.expected_bitstream_sha256,
  852. exit_code=args.exit_code,
  853. run_id=args.run_id,
  854. command_execution_attempted=False,
  855. timed_out=False,
  856. td_bin=args.td_bin,
  857. )
  858. encoded = json.dumps(receipt, indent=2) + "\n"
  859. if args.receipt is not None:
  860. args.receipt.parent.mkdir(parents=True, exist_ok=True)
  861. args.receipt.write_text(encoded, encoding="utf-8", newline="\n")
  862. print(encoded, end="")
  863. return 0 if receipt["status"] == "pass" else 1
  864. if __name__ == "__main__":
  865. raise SystemExit(main())