prod2u_programmer.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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 getpass
  7. import hashlib
  8. import json
  9. import locale
  10. import ntpath
  11. import os
  12. import re
  13. import shutil
  14. import subprocess
  15. import tempfile
  16. import time
  17. from ctypes import wintypes
  18. from datetime import datetime, timezone
  19. from pathlib import Path
  20. from typing import Any, Callable
  21. SCHEMA_NAME = "prod2u-program-sram-receipt-v1"
  22. TARGET_CHIP = "EF2L45"
  23. JTAG_SPEED_CODE = 2
  24. JTAG_SPEED_HZ = 200000
  25. BIT_TO_VEC_FREQUENCY = "0.200000"
  26. EXPECTED_MARKERS = (
  27. "download_start",
  28. "chip_validation",
  29. "bit_to_vec_start",
  30. "bit_to_vec_finish",
  31. "program_start",
  32. "program_finish",
  33. "download_finish",
  34. )
  35. SETUP_MARKERS = ("connect_cable_start", "connect_cable_finish")
  36. BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
  37. SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
  38. ERROR_RE = re.compile(
  39. r"\b(?:PRG-8\d{3}|ERROR|FATAL|failed|couldn't read file|invalid command name)\b",
  40. re.IGNORECASE,
  41. )
  42. FORBIDDEN_RE = re.compile(
  43. r"(?<![A-Za-z0-9])(?:flash|erase|spi(?:bin)?|nonvolatile)(?![A-Za-z0-9])",
  44. re.IGNORECASE,
  45. )
  46. START_COMMAND_RE = re.compile(r'^RUN-1002\s*:\s*start command "(?P<command>.+)"\s*$')
  47. FINISH_COMMAND_RE = re.compile(r'^RUN-1003\s*:\s*finish command "(?P<command>.+)"(?:\s+in\s+.+)?$')
  48. CHIP_RE = re.compile(r"^PRG-2014\s*:\s*Chip validation success:\s*(?P<chip>\S+)\s*$")
  49. DOWNLOAD_RE = re.compile(
  50. r"^download\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s+"
  51. r"-mode\s+(?P<mode>\S+)\s+-spd\s+(?P<speed>\d+)\s+-cable\s+(?P<cable>\d+)\s*$"
  52. )
  53. BIT_TO_VEC_RE = re.compile(
  54. r"^bit_to_vec\s+-chip\s+(?P<chip>\S+)\s+-m\s+(?P<mode>\S+)\s+"
  55. r"-freq\s+(?P<freq>\S+)\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s*$"
  56. )
  57. PROGRAM_RE = re.compile(
  58. r"^program\s+-cable\s+(?P<cable>\d+)\s+-mode\s+(?P<mode>\S+)\s+"
  59. r"-spd\s+(?P<speed>\d+)\s+-p\s*$"
  60. )
  61. PROGRAM_TIMEOUT_SECONDS = 60
  62. PROCESS_CLEANUP_WAIT_SECONDS = 5.0
  63. MUTEX_NAME = r"Global\Prod2UProgramSram"
  64. TD_PROCESS_EXECUTABLES = (
  65. "td.exe",
  66. "td_commands_prompt.exe",
  67. "bw.exe",
  68. "bw_commands_prompt.exe",
  69. "hwserver.exe",
  70. )
  71. def utc_now() -> str:
  72. return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  73. def sha256_bytes(data: bytes) -> str:
  74. return hashlib.sha256(data).hexdigest()
  75. def sha256_file(path: Path) -> str:
  76. digest = hashlib.sha256()
  77. with path.open("rb") as stream:
  78. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  79. digest.update(chunk)
  80. return digest.hexdigest()
  81. def staged_bitstream_path(build_id: str) -> str:
  82. """Return the only accepted Windows staging path for a build identity."""
  83. if not BUILD_ID_RE.fullmatch(build_id):
  84. raise ValueError("build_id must be eight uppercase hexadecimal characters")
  85. return f"C:\\P2U\\{build_id}\\fw.bit"
  86. def _strip_path_token(value: str) -> str:
  87. if value.startswith("{") and value.endswith("}"):
  88. return value[1:-1]
  89. if value.startswith('"') and value.endswith('"'):
  90. return value[1:-1]
  91. return value
  92. def _canonical_windows_path(value: str, *, td_bin: str) -> str:
  93. normalized = _strip_path_token(value).replace("/", "\\")
  94. if not ntpath.isabs(normalized):
  95. normalized = ntpath.join(td_bin, normalized)
  96. return ntpath.normcase(ntpath.normpath(normalized))
  97. def build_program_tcl(bitstream_path: str) -> str:
  98. """Generate the fixed one-attempt SRAM-only BitWriter Tcl program."""
  99. canonical = ntpath.normpath(bitstream_path)
  100. match = re.fullmatch(r"C:\\P2U\\([0-9A-F]{8})\\fw\.bit", canonical, re.IGNORECASE)
  101. if match is None:
  102. raise ValueError("bitstream_path must be C:\\P2U\\<BUILD_ID>\\fw.bit")
  103. build_id = match.group(1).upper()
  104. expected = staged_bitstream_path(build_id).replace("\\", "/")
  105. return (
  106. "connect_cable -allink\n"
  107. f"download -bit {{{expected}}} -mode jtag -spd 2 -cable 0\n"
  108. "exit\n"
  109. )
  110. class WindowsNamedMutex:
  111. """Non-waiting process-wide PROGRAM_SRAM lock backed by a Windows mutex."""
  112. def __init__(self, name: str = MUTEX_NAME) -> None:
  113. self.name = name
  114. self.handle: int | None = None
  115. def __enter__(self) -> "WindowsNamedMutex":
  116. if os.name != "nt":
  117. raise RuntimeError("Prod2U PROGRAM_SRAM is supported only on Windows")
  118. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  119. kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
  120. kernel32.CreateMutexW.restype = ctypes.c_void_p
  121. kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
  122. kernel32.WaitForSingleObject.restype = ctypes.c_uint32
  123. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  124. kernel32.CloseHandle.restype = ctypes.c_bool
  125. handle = kernel32.CreateMutexW(None, False, self.name)
  126. if not handle:
  127. raise OSError(ctypes.get_last_error(), "CreateMutexW failed")
  128. result = kernel32.WaitForSingleObject(handle, 0)
  129. if result not in (0x00000000, 0x00000080):
  130. kernel32.CloseHandle(handle)
  131. raise TimeoutError("Prod2U PROGRAM_SRAM mutex busy")
  132. self.handle = int(handle)
  133. return self
  134. def __exit__(self, exc_type, exc, tb) -> bool:
  135. if self.handle is not None:
  136. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  137. kernel32.ReleaseMutex.argtypes = [ctypes.c_void_p]
  138. kernel32.ReleaseMutex.restype = ctypes.c_bool
  139. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  140. kernel32.CloseHandle.restype = ctypes.c_bool
  141. kernel32.ReleaseMutex(ctypes.c_void_p(self.handle))
  142. kernel32.CloseHandle(ctypes.c_void_p(self.handle))
  143. self.handle = None
  144. return False
  145. class WindowsTdProcessAdapter:
  146. """Read and control qualified Anlogic processes with PID-reuse checks."""
  147. def __init__(self, runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> None:
  148. self.runner = runner
  149. def _run_json(self, script: str, *, env: dict[str, str] | None = None) -> Any:
  150. command_env = os.environ.copy()
  151. if env:
  152. command_env.update(env)
  153. result = self.runner(
  154. ["powershell.exe", "-NoProfile", "-Command", script],
  155. capture_output=True,
  156. text=True,
  157. check=False,
  158. timeout=15,
  159. env=command_env,
  160. )
  161. if result.returncode != 0:
  162. detail = result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}"
  163. raise RuntimeError(detail)
  164. try:
  165. return json.loads(result.stdout)
  166. except json.JSONDecodeError as exc:
  167. raise RuntimeError(f"invalid process audit JSON: {exc}") from exc
  168. def discover(self) -> list[dict[str, Any]]:
  169. candidate_names = ", ".join(f"'{name}'" for name in TD_PROCESS_EXECUTABLES)
  170. script = rf'''
  171. $ErrorActionPreference = 'Stop'
  172. $candidateNames = @({candidate_names})
  173. $records = @()
  174. $candidates = @(Get-CimInstance Win32_Process | Where-Object {{
  175. $candidateNames -contains ([string]$_.Name).ToLowerInvariant()
  176. }} | Sort-Object ProcessId)
  177. foreach ($process in $candidates) {{
  178. $record = [ordered]@{{
  179. pid = [int]$process.ProcessId
  180. name = [string]$process.Name
  181. path = $null
  182. user = $null
  183. session_id = $null
  184. parent_pid = $null
  185. command_line = $null
  186. start_time = $null
  187. exe_sha256 = $null
  188. }}
  189. try {{
  190. if ([string]::IsNullOrWhiteSpace([string]$process.ExecutablePath)) {{ throw 'path unavailable' }}
  191. $record.path = [System.IO.Path]::GetFullPath([string]$process.ExecutablePath)
  192. $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwner
  193. if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{
  194. throw ('owner unavailable: return={0}' -f $owner.ReturnValue)
  195. }}
  196. $record.user = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{
  197. [string]$owner.User
  198. }} else {{
  199. '{0}\{1}' -f $owner.Domain, $owner.User
  200. }})
  201. $record.session_id = [int]$process.SessionId
  202. $record.parent_pid = [int]$process.ParentProcessId
  203. if ([string]::IsNullOrWhiteSpace([string]$process.CommandLine)) {{ throw 'command line unavailable' }}
  204. $record.command_line = [string]$process.CommandLine
  205. if ($null -eq $process.CreationDate) {{ throw 'start time unavailable' }}
  206. $record.start_time = ([DateTime]$process.CreationDate).ToUniversalTime().ToString('o')
  207. $record.exe_sha256 = (Get-FileHash -LiteralPath $record.path -Algorithm SHA256).Hash.ToLowerInvariant()
  208. }} catch {{
  209. $record.identity_error = $_.Exception.Message
  210. }}
  211. $records += [pscustomobject]$record
  212. }}
  213. [ordered]@{{ processes = @($records) }} | ConvertTo-Json -Compress -Depth 4
  214. '''
  215. payload = self._run_json(script)
  216. processes = payload.get("processes") if isinstance(payload, dict) else None
  217. if not isinstance(processes, list):
  218. raise RuntimeError("process discovery did not return an array")
  219. return processes
  220. def _identity_action(self, process: dict[str, Any], action: str) -> dict[str, Any]:
  221. if action == "close":
  222. action_script = "$native = Get-Process -Id $pidValue -ErrorAction Stop; $null = $native.CloseMainWindow()"
  223. elif action == "probe":
  224. action_script = ""
  225. elif action == "force":
  226. action_script = "Stop-Process -Id $pidValue -Force -ErrorAction Stop"
  227. else:
  228. raise ValueError(f"unknown process action: {action}")
  229. script = rf'''
  230. $ErrorActionPreference = 'Stop'
  231. $pidValue = [int]$env:PROD2U_PROCESS_PID
  232. $expectedPath = [System.IO.Path]::GetFullPath($env:PROD2U_PROCESS_PATH)
  233. $expectedStart = $env:PROD2U_PROCESS_START
  234. $expectedOwner = $env:PROD2U_PROCESS_OWNER
  235. $expectedSession = [int]$env:PROD2U_PROCESS_SESSION
  236. $expectedParent = [int]$env:PROD2U_PROCESS_PARENT
  237. $expectedCommandLine = $env:PROD2U_PROCESS_COMMAND_LINE
  238. $expectedSha256 = $env:PROD2U_PROCESS_SHA256
  239. $current = Get-CimInstance Win32_Process -Filter ("ProcessId = {{0}}" -f $pidValue)
  240. if ($null -eq $current) {{
  241. [ordered]@{{ status = 'not_running'; running = $false }} | ConvertTo-Json -Compress
  242. exit 0
  243. }}
  244. if ([string]::IsNullOrWhiteSpace([string]$current.ExecutablePath)) {{ throw 'current process path unavailable' }}
  245. $currentPath = [System.IO.Path]::GetFullPath([string]$current.ExecutablePath)
  246. $currentStart = ([DateTime]$current.CreationDate).ToUniversalTime().ToString('o')
  247. $owner = Invoke-CimMethod -InputObject $current -MethodName GetOwner
  248. if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{
  249. throw 'current process owner unavailable'
  250. }}
  251. $currentOwner = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{
  252. [string]$owner.User
  253. }} else {{
  254. '{{0}}\{{1}}' -f $owner.Domain, $owner.User
  255. }})
  256. $currentSha256 = (Get-FileHash -LiteralPath $currentPath -Algorithm SHA256).Hash.ToLowerInvariant()
  257. if (-not $currentPath.Equals($expectedPath, [System.StringComparison]::OrdinalIgnoreCase) -or
  258. -not $currentStart.Equals($expectedStart, [System.StringComparison]::Ordinal) -or
  259. -not $currentOwner.Equals($expectedOwner, [System.StringComparison]::OrdinalIgnoreCase) -or
  260. [int]$current.SessionId -ne $expectedSession -or
  261. [int]$current.ParentProcessId -ne $expectedParent -or
  262. -not ([string]$current.CommandLine).Equals($expectedCommandLine, [System.StringComparison]::Ordinal) -or
  263. -not $currentSha256.Equals($expectedSha256, [System.StringComparison]::OrdinalIgnoreCase)) {{
  264. throw 'process identity changed before action'
  265. }}
  266. {action_script}
  267. [ordered]@{{ status = 'ok'; running = $true }} | ConvertTo-Json -Compress
  268. '''
  269. return self._run_json(
  270. script,
  271. env={
  272. "PROD2U_PROCESS_PID": str(process["pid"]),
  273. "PROD2U_PROCESS_PATH": str(process["path"]),
  274. "PROD2U_PROCESS_START": str(process["start_time"]),
  275. "PROD2U_PROCESS_OWNER": str(process["user"]),
  276. "PROD2U_PROCESS_SESSION": str(process["session_id"]),
  277. "PROD2U_PROCESS_PARENT": str(process["parent_pid"]),
  278. "PROD2U_PROCESS_COMMAND_LINE": str(process["command_line"]),
  279. "PROD2U_PROCESS_SHA256": str(process["exe_sha256"]),
  280. },
  281. )
  282. def request_close(self, process: dict[str, Any]) -> None:
  283. self._identity_action(process, "close")
  284. def is_running(self, process: dict[str, Any]) -> bool:
  285. return bool(self._identity_action(process, "probe").get("running"))
  286. def force_stop(self, process: dict[str, Any]) -> None:
  287. self._identity_action(process, "force")
  288. def _process_identity_errors(process: Any, *, td_root: str) -> tuple[dict[str, Any] | None, list[str]]:
  289. if not isinstance(process, dict):
  290. return None, ["identity_unreadable:unknown:record"]
  291. pid = process.get("pid")
  292. pid_label = str(pid) if isinstance(pid, int) and not isinstance(pid, bool) else "unknown"
  293. errors: list[str] = []
  294. if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
  295. errors.append("identity_unreadable:unknown:pid")
  296. name = process.get("name")
  297. if not isinstance(name, str) or not name.strip():
  298. errors.append(f"identity_unreadable:{pid_label}:name")
  299. elif name.casefold() not in {candidate.casefold() for candidate in TD_PROCESS_EXECUTABLES}:
  300. errors.append(f"unexpected_process_name:{pid_label}")
  301. for field in ("path", "user", "command_line", "start_time", "exe_sha256"):
  302. value = process.get(field)
  303. if not isinstance(value, str) or not value.strip():
  304. errors.append(f"identity_unreadable:{pid_label}:{field}")
  305. identity_error = process.get("identity_error")
  306. if identity_error:
  307. errors.append(f"identity_unreadable:{pid_label}:adapter:{identity_error}")
  308. path = process.get("path")
  309. if isinstance(path, str) and path.strip():
  310. canonical_path = ntpath.normcase(ntpath.normpath(path))
  311. canonical_root = ntpath.normcase(ntpath.normpath(td_root)).rstrip("\\/")
  312. root_prefix = canonical_root + "\\"
  313. if not ntpath.isabs(path) or not canonical_path.startswith(root_prefix):
  314. errors.append(f"unknown_process_path:{pid_label}")
  315. if isinstance(name, str) and name.strip() and ntpath.basename(canonical_path) != name.casefold():
  316. errors.append(f"process_name_path_mismatch:{pid_label}")
  317. exe_sha256 = process.get("exe_sha256")
  318. if isinstance(exe_sha256, str) and exe_sha256.strip() and not re.fullmatch(r"[0-9a-f]{64}", exe_sha256):
  319. errors.append(f"identity_unreadable:{pid_label}:exe_sha256")
  320. for field in ("session_id", "parent_pid"):
  321. value = process.get(field)
  322. if not isinstance(value, int) or isinstance(value, bool) or value < 0:
  323. errors.append(f"identity_unreadable:{pid_label}:{field}")
  324. if errors:
  325. return None, errors
  326. return {
  327. "pid": int(pid),
  328. "name": str(name),
  329. "path": str(process["path"]),
  330. "user": str(process["user"]),
  331. "session_id": int(process["session_id"]),
  332. "parent_pid": int(process["parent_pid"]),
  333. "command_line": str(process["command_line"]),
  334. "start_time": str(process["start_time"]),
  335. "exe_sha256": str(process["exe_sha256"]),
  336. }, []
  337. def _canonical_command_line(value: str) -> str:
  338. return value.strip()
  339. def _validate_ownership_policy(policy: Any) -> list[str]:
  340. if not isinstance(policy, dict):
  341. return ["ownership_policy_missing"]
  342. errors: list[str] = []
  343. for field in ("owner", "command_line"):
  344. if not isinstance(policy.get(field), str) or not policy[field].strip():
  345. errors.append(f"ownership_policy_invalid:{field}")
  346. for field in ("session_id", "parent_pid"):
  347. value = policy.get(field)
  348. if not isinstance(value, int) or isinstance(value, bool) or value < 0:
  349. errors.append(f"ownership_policy_invalid:{field}")
  350. binaries = policy.get("approved_binaries")
  351. if not isinstance(binaries, list) or not binaries:
  352. errors.append("ownership_policy_invalid:approved_binaries")
  353. else:
  354. for binary in binaries:
  355. if not isinstance(binary, dict):
  356. errors.append("ownership_policy_invalid:approved_binary")
  357. continue
  358. if not all(isinstance(binary.get(field), str) and binary[field].strip() for field in ("name", "path")):
  359. errors.append("ownership_policy_invalid:approved_binary_identity")
  360. if not isinstance(binary.get("exe_sha256"), str) or not SHA256_RE.fullmatch(binary["exe_sha256"]):
  361. errors.append("ownership_policy_invalid:approved_binary_hash")
  362. return list(dict.fromkeys(errors))
  363. def _is_harness_owned(process: dict[str, Any], policy: dict[str, Any]) -> bool:
  364. binary_matches = any(
  365. str(process["name"]).casefold() == str(binary["name"]).casefold()
  366. and ntpath.normcase(ntpath.normpath(str(process["path"])))
  367. == ntpath.normcase(ntpath.normpath(str(binary["path"])))
  368. and str(process["exe_sha256"]).casefold() == str(binary["exe_sha256"]).casefold()
  369. for binary in policy["approved_binaries"]
  370. )
  371. return (
  372. binary_matches
  373. and str(process["user"]).casefold() == str(policy["owner"]).casefold()
  374. and process["session_id"] == policy["session_id"]
  375. and process["parent_pid"] == policy["parent_pid"]
  376. and _canonical_command_line(str(process["command_line"]))
  377. == _canonical_command_line(str(policy["command_line"]))
  378. )
  379. def build_process_ownership_policy(*, executable: Path, command: list[str]) -> dict[str, Any]:
  380. """Build the exact identity policy for a process launched by this harness."""
  381. executable = executable.resolve()
  382. if os.name == "nt":
  383. session_id = ctypes.c_uint32()
  384. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  385. kernel32.ProcessIdToSessionId.argtypes = [ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32)]
  386. kernel32.ProcessIdToSessionId.restype = ctypes.c_bool
  387. if not kernel32.ProcessIdToSessionId(os.getpid(), ctypes.byref(session_id)):
  388. raise OSError(ctypes.get_last_error(), "ProcessIdToSessionId failed")
  389. domain = os.environ.get("USERDOMAIN", "").strip()
  390. username = os.environ.get("USERNAME", "").strip() or getpass.getuser()
  391. owner = f"{domain}\\{username}" if domain else username
  392. current_session = int(session_id.value)
  393. else:
  394. owner = getpass.getuser()
  395. current_session = 0
  396. return {
  397. "owner": owner,
  398. "session_id": current_session,
  399. "parent_pid": os.getpid(),
  400. "approved_binaries": [
  401. {
  402. "name": executable.name.casefold(),
  403. "path": str(executable),
  404. "exe_sha256": sha256_file(executable),
  405. }
  406. ],
  407. "command_line": subprocess.list2cmdline(command),
  408. }
  409. def close_td_processes(
  410. td_root: Path,
  411. *,
  412. ownership_policy: dict[str, Any] | None = None,
  413. process_adapter: Any | None = None,
  414. sleeper: Callable[[float], None] = time.sleep,
  415. ) -> dict[str, Any]:
  416. """Terminate only processes proven to be owned by this harness invocation."""
  417. root = str(td_root.resolve())
  418. adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter()
  419. discovered: list[dict[str, Any]] = []
  420. harness_owned: list[dict[str, Any]] = []
  421. blocking: list[dict[str, Any]] = []
  422. graceful: list[dict[str, Any]] = []
  423. forced: list[dict[str, Any]] = []
  424. errors = _validate_ownership_policy(ownership_policy)
  425. def result(status: str, *, remaining: list[dict[str, Any]] | None = None, audited: bool) -> dict[str, Any]:
  426. return {
  427. "status": status,
  428. "td_root": root,
  429. "identity_audit_completed_before_action": audited,
  430. "ownership_policy": ownership_policy,
  431. "discovered_processes": discovered,
  432. "harness_owned_processes": harness_owned,
  433. "blocking_processes": blocking,
  434. "graceful_close_requested": graceful,
  435. "forced_terminated": forced,
  436. "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
  437. "remaining": remaining or [],
  438. "post_action_audit_completed": False,
  439. "post_action_discovered_processes": [],
  440. "post_action_harness_owned_processes": [],
  441. "post_action_blocking_processes": [],
  442. "residual_processes": [],
  443. "post_action_errors": [],
  444. "errors": list(dict.fromkeys(errors)),
  445. }
  446. if errors:
  447. return result("fail", audited=False)
  448. try:
  449. raw_processes = adapter.discover()
  450. except Exception as exc:
  451. errors.append(f"process_discovery_failed:{exc}")
  452. return result("fail", audited=False)
  453. if not isinstance(raw_processes, list):
  454. errors.append("process_discovery_failed:not_an_array")
  455. return result("fail", audited=False)
  456. for raw_process in raw_processes:
  457. process, process_errors = _process_identity_errors(raw_process, td_root=root)
  458. errors.extend(process_errors)
  459. if process is not None:
  460. discovered.append(process)
  461. if errors:
  462. return result("fail", audited=False)
  463. for process in discovered:
  464. if _is_harness_owned(process, ownership_policy):
  465. harness_owned.append(process)
  466. else:
  467. blocking.append(process)
  468. if blocking:
  469. errors.append("blocking_td_processes_present")
  470. return result("fail", remaining=discovered, audited=True)
  471. try:
  472. for process in harness_owned:
  473. adapter.request_close(process)
  474. graceful.append(process)
  475. if harness_owned:
  476. sleeper(PROCESS_CLEANUP_WAIT_SECONDS)
  477. for process in harness_owned:
  478. if adapter.is_running(process):
  479. adapter.force_stop(process)
  480. forced.append(process)
  481. raw_remaining = adapter.discover()
  482. except Exception as exc:
  483. errors.append(f"process_control_failed:{exc}")
  484. return result("fail", audited=True)
  485. remaining: list[dict[str, Any]] = []
  486. if not isinstance(raw_remaining, list):
  487. errors.append("final_process_discovery_failed:not_an_array")
  488. else:
  489. for raw_process in raw_remaining:
  490. process, process_errors = _process_identity_errors(raw_process, td_root=root)
  491. errors.extend(process_errors)
  492. if process is not None:
  493. remaining.append(process)
  494. if remaining:
  495. errors.append("qualified_processes_remaining")
  496. return result("pass" if not errors else "fail", remaining=remaining, audited=True)
  497. def audit_td_processes(
  498. td_root: Path,
  499. *,
  500. ownership_policy: dict[str, Any],
  501. process_adapter: Any | None = None,
  502. ) -> dict[str, Any]:
  503. """Perform a non-destructive post-action audit of all TD candidates."""
  504. root = str(td_root.resolve())
  505. adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter()
  506. errors = _validate_ownership_policy(ownership_policy)
  507. discovered: list[dict[str, Any]] = []
  508. harness_owned: list[dict[str, Any]] = []
  509. blocking: list[dict[str, Any]] = []
  510. audit_completed = False
  511. if not errors:
  512. try:
  513. raw_processes = adapter.discover()
  514. except Exception as exc:
  515. errors.append(f"post_action_process_discovery_failed:{exc}")
  516. raw_processes = []
  517. if not isinstance(raw_processes, list):
  518. errors.append("post_action_process_discovery_failed:not_an_array")
  519. else:
  520. for raw_process in raw_processes:
  521. process, process_errors = _process_identity_errors(raw_process, td_root=root)
  522. errors.extend(process_errors)
  523. if process is not None:
  524. discovered.append(process)
  525. audit_completed = not errors
  526. if not errors:
  527. for process in discovered:
  528. if _is_harness_owned(process, ownership_policy):
  529. harness_owned.append(process)
  530. else:
  531. blocking.append(process)
  532. if discovered:
  533. errors.append("post_action_td_processes_remaining")
  534. return {
  535. "status": "pass" if not errors else "fail",
  536. "post_action_audit_completed": audit_completed,
  537. "post_action_discovered_processes": discovered,
  538. "post_action_harness_owned_processes": harness_owned,
  539. "post_action_blocking_processes": blocking,
  540. "residual_processes": discovered,
  541. "post_action_errors": list(dict.fromkeys(errors)),
  542. }
  543. def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
  544. if not log_dir.is_dir():
  545. return {}
  546. snapshot: dict[str, dict[str, int]] = {}
  547. for path in log_dir.glob("bw_*.log"):
  548. if not path.is_file():
  549. continue
  550. stat = path.stat()
  551. snapshot[str(path.resolve())] = {
  552. "size": stat.st_size,
  553. "file_id": stat.st_ino,
  554. "created_ns": stat.st_ctime_ns,
  555. }
  556. return snapshot
  557. def _read_bitwriter_log_deltas(
  558. log_dir: Path,
  559. before: dict[str, dict[str, int]],
  560. ) -> tuple[bytes, list[dict[str, Any]], list[str]]:
  561. chunks: list[bytes] = []
  562. sources: list[dict[str, Any]] = []
  563. issues: list[str] = []
  564. if not log_dir.is_dir():
  565. return b"", sources, issues
  566. for path in sorted(log_dir.glob("bw_*.log"), key=lambda candidate: candidate.name.casefold()):
  567. if not path.is_file():
  568. continue
  569. resolved = str(path.resolve())
  570. previous = before.get(resolved)
  571. stat = path.stat()
  572. size = stat.st_size
  573. start = int(previous["size"]) if previous is not None else 0
  574. if previous is not None and (
  575. stat.st_ino != int(previous["file_id"])
  576. or stat.st_ctime_ns != int(previous["created_ns"])
  577. or size < start
  578. ):
  579. issues.append("bitwriter_log_replaced_or_truncated")
  580. continue
  581. if size == start:
  582. continue
  583. with path.open("rb") as stream:
  584. stream.seek(start)
  585. data = stream.read()
  586. if not data:
  587. continue
  588. chunks.append(data)
  589. sources.append(
  590. {
  591. "path": resolved,
  592. "start_offset": start,
  593. "byte_count": len(data),
  594. "sha256": sha256_bytes(data),
  595. }
  596. )
  597. return b"\n".join(chunks), sources, list(dict.fromkeys(issues))
  598. class _IoCounters(ctypes.Structure):
  599. _fields_ = [
  600. ("ReadOperationCount", ctypes.c_uint64),
  601. ("WriteOperationCount", ctypes.c_uint64),
  602. ("OtherOperationCount", ctypes.c_uint64),
  603. ("ReadTransferCount", ctypes.c_uint64),
  604. ("WriteTransferCount", ctypes.c_uint64),
  605. ("OtherTransferCount", ctypes.c_uint64),
  606. ]
  607. class _JobBasicLimitInformation(ctypes.Structure):
  608. _fields_ = [
  609. ("PerProcessUserTimeLimit", ctypes.c_int64),
  610. ("PerJobUserTimeLimit", ctypes.c_int64),
  611. ("LimitFlags", ctypes.c_uint32),
  612. ("MinimumWorkingSetSize", ctypes.c_size_t),
  613. ("MaximumWorkingSetSize", ctypes.c_size_t),
  614. ("ActiveProcessLimit", ctypes.c_uint32),
  615. ("Affinity", ctypes.c_size_t),
  616. ("PriorityClass", ctypes.c_uint32),
  617. ("SchedulingClass", ctypes.c_uint32),
  618. ]
  619. class _JobExtendedLimitInformation(ctypes.Structure):
  620. _fields_ = [
  621. ("BasicLimitInformation", _JobBasicLimitInformation),
  622. ("IoInfo", _IoCounters),
  623. ("ProcessMemoryLimit", ctypes.c_size_t),
  624. ("JobMemoryLimit", ctypes.c_size_t),
  625. ("PeakProcessMemoryUsed", ctypes.c_size_t),
  626. ("PeakJobMemoryUsed", ctypes.c_size_t),
  627. ]
  628. class _StartupInfoW(ctypes.Structure):
  629. _fields_ = [
  630. ("cb", wintypes.DWORD),
  631. ("lpReserved", wintypes.LPWSTR),
  632. ("lpDesktop", wintypes.LPWSTR),
  633. ("lpTitle", wintypes.LPWSTR),
  634. ("dwX", wintypes.DWORD),
  635. ("dwY", wintypes.DWORD),
  636. ("dwXSize", wintypes.DWORD),
  637. ("dwYSize", wintypes.DWORD),
  638. ("dwXCountChars", wintypes.DWORD),
  639. ("dwYCountChars", wintypes.DWORD),
  640. ("dwFillAttribute", wintypes.DWORD),
  641. ("dwFlags", wintypes.DWORD),
  642. ("wShowWindow", wintypes.WORD),
  643. ("cbReserved2", wintypes.WORD),
  644. ("lpReserved2", ctypes.POINTER(wintypes.BYTE)),
  645. ("hStdInput", wintypes.HANDLE),
  646. ("hStdOutput", wintypes.HANDLE),
  647. ("hStdError", wintypes.HANDLE),
  648. ]
  649. class _ProcessInformation(ctypes.Structure):
  650. _fields_ = [
  651. ("hProcess", wintypes.HANDLE),
  652. ("hThread", wintypes.HANDLE),
  653. ("dwProcessId", wintypes.DWORD),
  654. ("dwThreadId", wintypes.DWORD),
  655. ]
  656. def windows_process_is_running(pid: int) -> bool:
  657. if os.name != "nt":
  658. return False
  659. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  660. kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_bool, ctypes.c_uint32]
  661. kernel32.OpenProcess.restype = ctypes.c_void_p
  662. kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
  663. kernel32.WaitForSingleObject.restype = ctypes.c_uint32
  664. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  665. kernel32.CloseHandle.restype = ctypes.c_bool
  666. handle = kernel32.OpenProcess(0x00100000, False, int(pid))
  667. if not handle:
  668. return False
  669. try:
  670. return kernel32.WaitForSingleObject(handle, 0) == 0x00000102
  671. finally:
  672. kernel32.CloseHandle(handle)
  673. def run_process_in_job(
  674. command: list[str],
  675. *,
  676. cwd: str,
  677. timeout: float,
  678. capture_output: bool,
  679. text: bool,
  680. check: bool,
  681. ) -> subprocess.CompletedProcess[str]:
  682. """Run one process in a kill-on-close Windows Job Object."""
  683. if os.name != "nt":
  684. return subprocess.run(
  685. command,
  686. cwd=cwd,
  687. timeout=timeout,
  688. capture_output=capture_output,
  689. text=text,
  690. check=check,
  691. )
  692. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  693. kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
  694. kernel32.CreateJobObjectW.restype = ctypes.c_void_p
  695. kernel32.SetInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
  696. kernel32.SetInformationJobObject.restype = ctypes.c_bool
  697. kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
  698. kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
  699. kernel32.CreateProcessW.argtypes = [
  700. wintypes.LPCWSTR,
  701. wintypes.LPWSTR,
  702. ctypes.c_void_p,
  703. ctypes.c_void_p,
  704. wintypes.BOOL,
  705. wintypes.DWORD,
  706. ctypes.c_void_p,
  707. wintypes.LPCWSTR,
  708. ctypes.POINTER(_StartupInfoW),
  709. ctypes.POINTER(_ProcessInformation),
  710. ]
  711. kernel32.CreateProcessW.restype = wintypes.BOOL
  712. kernel32.ResumeThread.argtypes = [wintypes.HANDLE]
  713. kernel32.ResumeThread.restype = wintypes.DWORD
  714. kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
  715. kernel32.WaitForSingleObject.restype = wintypes.DWORD
  716. kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
  717. kernel32.GetExitCodeProcess.restype = wintypes.BOOL
  718. kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
  719. kernel32.TerminateProcess.restype = wintypes.BOOL
  720. kernel32.SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD]
  721. kernel32.SetHandleInformation.restype = wintypes.BOOL
  722. kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
  723. kernel32.TerminateJobObject.restype = ctypes.c_bool
  724. kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
  725. kernel32.CloseHandle.restype = ctypes.c_bool
  726. job = kernel32.CreateJobObjectW(None, None)
  727. if not job:
  728. raise OSError(ctypes.get_last_error(), "CreateJobObjectW failed")
  729. info = _JobExtendedLimitInformation()
  730. info.BasicLimitInformation.LimitFlags = 0x00002000
  731. if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
  732. error = ctypes.get_last_error()
  733. kernel32.CloseHandle(job)
  734. raise OSError(error, "SetInformationJobObject failed")
  735. CREATE_SUSPENDED = 0x00000004
  736. STARTF_USESTDHANDLES = 0x00000100
  737. HANDLE_FLAG_INHERIT = 0x00000001
  738. WAIT_OBJECT_0 = 0x00000000
  739. WAIT_TIMEOUT = 0x00000102
  740. INFINITE = 0xFFFFFFFF
  741. stdout_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None
  742. stderr_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None
  743. stdin_file = open(os.devnull, "rb") if capture_output else None
  744. inherited_handles: list[int] = []
  745. startup = _StartupInfoW()
  746. startup.cb = ctypes.sizeof(startup)
  747. if capture_output:
  748. import msvcrt
  749. startup.dwFlags = STARTF_USESTDHANDLES
  750. startup.hStdInput = wintypes.HANDLE(msvcrt.get_osfhandle(stdin_file.fileno()))
  751. startup.hStdOutput = wintypes.HANDLE(msvcrt.get_osfhandle(stdout_file.fileno()))
  752. startup.hStdError = wintypes.HANDLE(msvcrt.get_osfhandle(stderr_file.fileno()))
  753. inherited_handles = [
  754. int(startup.hStdInput),
  755. int(startup.hStdOutput),
  756. int(startup.hStdError),
  757. ]
  758. for handle in inherited_handles:
  759. if not kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT):
  760. raise OSError(ctypes.get_last_error(), "SetHandleInformation failed")
  761. process_info = _ProcessInformation()
  762. command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline(command))
  763. created = False
  764. try:
  765. if not kernel32.CreateProcessW(
  766. str(command[0]),
  767. command_line,
  768. None,
  769. None,
  770. bool(capture_output),
  771. CREATE_SUSPENDED,
  772. None,
  773. cwd,
  774. ctypes.byref(startup),
  775. ctypes.byref(process_info),
  776. ):
  777. raise OSError(ctypes.get_last_error(), "CreateProcessW failed")
  778. created = True
  779. if not kernel32.AssignProcessToJobObject(job, process_info.hProcess):
  780. error = ctypes.get_last_error()
  781. kernel32.TerminateProcess(process_info.hProcess, 1)
  782. kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
  783. raise OSError(error, "AssignProcessToJobObject failed")
  784. if kernel32.ResumeThread(process_info.hThread) == 0xFFFFFFFF:
  785. error = ctypes.get_last_error()
  786. kernel32.TerminateJobObject(job, 1)
  787. kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
  788. raise OSError(error, "ResumeThread failed")
  789. wait_milliseconds = max(0, min(int(timeout * 1000), 0xFFFFFFFE))
  790. wait_result = kernel32.WaitForSingleObject(process_info.hProcess, wait_milliseconds)
  791. timed_out = wait_result == WAIT_TIMEOUT
  792. if timed_out:
  793. kernel32.TerminateJobObject(job, 1)
  794. kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
  795. elif wait_result != WAIT_OBJECT_0:
  796. raise OSError(ctypes.get_last_error(), "WaitForSingleObject failed")
  797. exit_code = wintypes.DWORD()
  798. if not kernel32.GetExitCodeProcess(process_info.hProcess, ctypes.byref(exit_code)):
  799. raise OSError(ctypes.get_last_error(), "GetExitCodeProcess failed")
  800. encoding = locale.getpreferredencoding(False)
  801. stdout: str | bytes | None = None
  802. stderr: str | bytes | None = None
  803. if capture_output:
  804. stdout_file.seek(0)
  805. stderr_file.seek(0)
  806. stdout_bytes = stdout_file.read()
  807. stderr_bytes = stderr_file.read()
  808. stdout = stdout_bytes.decode(encoding, errors="replace") if text else stdout_bytes
  809. stderr = stderr_bytes.decode(encoding, errors="replace") if text else stderr_bytes
  810. if timed_out:
  811. raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr)
  812. result = subprocess.CompletedProcess(command, int(exit_code.value), stdout, stderr)
  813. if check and result.returncode != 0:
  814. raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
  815. return result
  816. finally:
  817. for handle in inherited_handles:
  818. kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, 0)
  819. if created:
  820. kernel32.CloseHandle(process_info.hThread)
  821. kernel32.CloseHandle(process_info.hProcess)
  822. if stdin_file is not None:
  823. stdin_file.close()
  824. if stdout_file is not None:
  825. stdout_file.close()
  826. if stderr_file is not None:
  827. stderr_file.close()
  828. kernel32.CloseHandle(job)
  829. def _artifact(path: Path) -> dict[str, Any]:
  830. return {"path": str(path), "size": path.stat().st_size, "sha256": sha256_file(path)}
  831. def _recompute_receipt_status(receipt: dict[str, Any]) -> None:
  832. failures = list(dict.fromkeys(receipt["parser"]["failures"]))
  833. receipt["parser"]["failures"] = failures
  834. receipt["parser"]["status"] = "pass" if not failures else "fail"
  835. if any(failure.startswith("forbidden_action:") for failure in failures):
  836. receipt["status"] = "fail_forbidden_action"
  837. else:
  838. receipt["status"] = receipt["parser"]["status"]
  839. def execute_program_sram(
  840. *,
  841. source_bitstream: Path,
  842. expected_bitstream_sha256: str,
  843. build_id: str,
  844. output_dir: Path,
  845. td_root: Path,
  846. run_id: str,
  847. process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
  848. cleanup_runner: Callable[..., dict[str, Any]] = close_td_processes,
  849. residual_audit_runner: Callable[..., dict[str, Any]] = audit_td_processes,
  850. mutex_factory: Callable[[], Any] = WindowsNamedMutex,
  851. ) -> dict[str, Any]:
  852. """Execute exactly one SRAM download and return a strict transaction receipt."""
  853. source_bitstream = Path(source_bitstream)
  854. output_dir = Path(output_dir)
  855. td_root = Path(td_root)
  856. if output_dir.exists() and any(output_dir.iterdir()):
  857. raise FileExistsError(f"output directory is not empty: {output_dir}")
  858. if not source_bitstream.is_file():
  859. raise FileNotFoundError(source_bitstream)
  860. if not SHA256_RE.fullmatch(expected_bitstream_sha256):
  861. raise ValueError("expected bitstream SHA256 must be 64 hexadecimal characters")
  862. source_sha256 = sha256_file(source_bitstream)
  863. if source_sha256.casefold() != expected_bitstream_sha256.casefold():
  864. raise ValueError("bitstream SHA256 mismatch before staging")
  865. staged = Path(staged_bitstream_path(build_id))
  866. bw_exe = td_root / "bin" / "bw_commands_prompt.exe"
  867. if not bw_exe.is_file():
  868. raise FileNotFoundError(bw_exe)
  869. output_dir.mkdir(parents=True, exist_ok=True)
  870. tcl_path = output_dir / "program-sram.tcl"
  871. stdout_path = output_dir / "bitwriter-stdout.log"
  872. stderr_path = output_dir / "bitwriter-stderr.log"
  873. delta_path = output_dir / "bitwriter-log-delta.log"
  874. tcl_cli_path = tcl_path.absolute().as_posix()
  875. command = [str(bw_exe), tcl_cli_path]
  876. ownership_policy = build_process_ownership_policy(executable=bw_exe, command=command)
  877. started_at = utc_now()
  878. start_monotonic = time.monotonic()
  879. with mutex_factory():
  880. cleanup = cleanup_runner(td_root, ownership_policy=ownership_policy)
  881. if cleanup.get("status") != "pass":
  882. raise RuntimeError(f"TD process cleanup failed: {cleanup}")
  883. stage_root = staged.parent.parent
  884. stage_root.mkdir(parents=True, exist_ok=True)
  885. staged.parent.mkdir(parents=True, exist_ok=True)
  886. if ntpath.normcase(str(staged.parent.resolve().parent)) != ntpath.normcase(str(stage_root.resolve())):
  887. raise ValueError("staging build directory resolves outside C:\\P2U")
  888. staged_temp = staged.parent / f".{staged.name}.{os.getpid()}.{time.time_ns()}.tmp"
  889. try:
  890. shutil.copy2(source_bitstream, staged_temp)
  891. if sha256_file(staged_temp).casefold() != expected_bitstream_sha256.casefold():
  892. raise ValueError("bitstream SHA256 mismatch in staging temporary file")
  893. os.replace(staged_temp, staged)
  894. finally:
  895. if staged_temp.exists():
  896. staged_temp.unlink()
  897. staged_sha256 = sha256_file(staged)
  898. if staged_sha256.casefold() != expected_bitstream_sha256.casefold():
  899. raise ValueError("bitstream SHA256 mismatch after staging")
  900. tcl_path.write_text(build_program_tcl(str(staged)), encoding="ascii", newline="\n")
  901. log_dir = td_root / "bin" / "log"
  902. before = _snapshot_bitwriter_logs(log_dir)
  903. timed_out = False
  904. try:
  905. completed = process_runner(
  906. command,
  907. cwd=str(td_root / "bin"),
  908. timeout=PROGRAM_TIMEOUT_SECONDS,
  909. capture_output=True,
  910. text=True,
  911. check=False,
  912. )
  913. exit_code = int(completed.returncode)
  914. stdout = completed.stdout or ""
  915. stderr = completed.stderr or ""
  916. except subprocess.TimeoutExpired as exc:
  917. timed_out = True
  918. exit_code = -1
  919. stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
  920. stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
  921. delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
  922. residual_audit = residual_audit_runner(td_root, ownership_policy=ownership_policy)
  923. for field in (
  924. "post_action_audit_completed",
  925. "post_action_discovered_processes",
  926. "post_action_harness_owned_processes",
  927. "post_action_blocking_processes",
  928. "residual_processes",
  929. "post_action_errors",
  930. ):
  931. cleanup[field] = residual_audit.get(field)
  932. cleanup["status"] = "pass" if residual_audit.get("status") == "pass" else "fail"
  933. stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
  934. stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
  935. delta_path.write_bytes(delta_bytes)
  936. parser_text = delta_bytes.decode("utf-8", errors="replace") if len(delta_sources) == 1 and not delta_issues else ""
  937. receipt = build_program_sram_receipt(
  938. transcript=parser_text,
  939. build_id=build_id,
  940. bitstream_path=str(staged),
  941. bitstream_bytes=staged.read_bytes(),
  942. expected_bitstream_sha256=expected_bitstream_sha256,
  943. exit_code=exit_code,
  944. run_id=run_id,
  945. command_execution_attempted=True,
  946. timed_out=timed_out,
  947. td_bin=str(td_root / "bin"),
  948. )
  949. authoritative_marker_signature = _marker_signature(parser_text)
  950. if residual_audit.get("status") != "pass":
  951. receipt["parser"]["failures"].append("post_action_process_audit_failed")
  952. if not delta_bytes:
  953. receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
  954. receipt["parser"]["ordered_markers_complete"] = False
  955. if len(delta_sources) > 1:
  956. receipt["parser"]["failures"].append("ambiguous_bitwriter_log_sources")
  957. receipt["parser"]["ordered_markers_complete"] = False
  958. receipt["parser"]["failures"].extend(delta_issues)
  959. for stream_name, output in (("stdout", stdout), ("stderr", stderr)):
  960. output_failures, output_error_markers, output_forbidden = _transcript_failures(output)
  961. receipt["parser"]["failures"].extend(output_failures)
  962. receipt["parser"]["error_markers"] = list(
  963. dict.fromkeys(receipt["parser"]["error_markers"] + output_error_markers)
  964. )
  965. if _contains_transaction_marker(output):
  966. output_signature = _marker_signature(output)
  967. if (
  968. stream_name == "stdout"
  969. and authoritative_marker_signature
  970. and output_signature == authoritative_marker_signature
  971. ):
  972. receipt["parser"]["stdout_transaction_mirror"] = True
  973. else:
  974. receipt["parser"]["failures"].append(f"transaction_marker_mismatch:{stream_name}")
  975. if output_forbidden:
  976. receipt["safety"]["flash_attempted"] = True
  977. receipt["safety"]["programs_nonvolatile"] = True
  978. receipt["execution"].update(
  979. {
  980. "timeout_seconds": PROGRAM_TIMEOUT_SECONDS,
  981. "started_at": started_at,
  982. "finished_at": utc_now(),
  983. "duration_seconds": round(time.monotonic() - start_monotonic, 6),
  984. }
  985. )
  986. receipt["tool"] = {
  987. "path": str(bw_exe),
  988. "td_root": str(td_root),
  989. "td_bin": str(td_root / "bin"),
  990. }
  991. receipt["mutex"] = {"name": MUTEX_NAME, "acquired": True}
  992. receipt["process_cleanup"] = cleanup
  993. receipt["artifacts"] = {
  994. "tcl": _artifact(tcl_path),
  995. "stdout": _artifact(stdout_path),
  996. "stderr": _artifact(stderr_path),
  997. "log_delta": _artifact(delta_path),
  998. "log_delta_sources": delta_sources,
  999. }
  1000. _recompute_receipt_status(receipt)
  1001. receipt_path = output_dir / "program-sram-receipt.json"
  1002. receipt_temp = output_dir / ".program-sram-receipt.json.tmp"
  1003. receipt_temp.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8", newline="\n")
  1004. os.replace(receipt_temp, receipt_path)
  1005. return receipt
  1006. def _contains_transaction_marker(transcript: str) -> bool:
  1007. return any(
  1008. START_COMMAND_RE.match(line.strip())
  1009. or FINISH_COMMAND_RE.match(line.strip())
  1010. or CHIP_RE.match(line.strip())
  1011. for line in transcript.splitlines()
  1012. )
  1013. def _marker_records(transcript: str) -> list[dict[str, Any]]:
  1014. records: list[dict[str, Any]] = []
  1015. for line_number, raw_line in enumerate(transcript.splitlines(), start=1):
  1016. line = raw_line.strip()
  1017. start = START_COMMAND_RE.match(line)
  1018. finish = FINISH_COMMAND_RE.match(line)
  1019. chip = CHIP_RE.match(line)
  1020. if start:
  1021. command = start.group("command")
  1022. if command == "connect_cable -allink":
  1023. records.append({"marker": "connect_cable_start", "command": command, "line": line_number})
  1024. elif command.startswith("download "):
  1025. records.append({"marker": "download_start", "command": command, "line": line_number})
  1026. elif command.startswith("bit_to_vec "):
  1027. records.append({"marker": "bit_to_vec_start", "command": command, "line": line_number})
  1028. elif command.startswith("program "):
  1029. records.append({"marker": "program_start", "command": command, "line": line_number})
  1030. else:
  1031. records.append(
  1032. {
  1033. "marker": "unrecognized_run_operation",
  1034. "operation": _operation_name(command),
  1035. "line": line_number,
  1036. }
  1037. )
  1038. elif finish:
  1039. command = finish.group("command")
  1040. if command == "connect_cable -allink":
  1041. records.append({"marker": "connect_cable_finish", "command": command, "line": line_number})
  1042. elif command.startswith("bit_to_vec "):
  1043. records.append({"marker": "bit_to_vec_finish", "command": command, "line": line_number})
  1044. elif command.startswith("program "):
  1045. records.append({"marker": "program_finish", "command": command, "line": line_number})
  1046. elif command.startswith("download "):
  1047. records.append({"marker": "download_finish", "command": command, "line": line_number})
  1048. else:
  1049. records.append(
  1050. {
  1051. "marker": "unrecognized_run_operation",
  1052. "operation": _operation_name(command),
  1053. "line": line_number,
  1054. }
  1055. )
  1056. elif chip:
  1057. records.append(
  1058. {
  1059. "marker": "chip_validation",
  1060. "chip": chip.group("chip"),
  1061. "line": line_number,
  1062. }
  1063. )
  1064. return records
  1065. def _operation_name(command: str) -> str:
  1066. parts = command.split(maxsplit=1)
  1067. return parts[0].casefold() if parts else "<empty>"
  1068. def _marker_failures(records: list[dict[str, Any]]) -> list[str]:
  1069. failures: list[str] = []
  1070. observed_all = [str(record["marker"]) for record in records]
  1071. observed = [marker for marker in observed_all if marker in EXPECTED_MARKERS]
  1072. setup_observed = [marker for marker in observed_all if marker in SETUP_MARKERS]
  1073. for record in records:
  1074. if record["marker"] == "unrecognized_run_operation":
  1075. failures.append(f"unrecognized_run_operation:{record['operation']}")
  1076. if setup_observed and (
  1077. setup_observed != list(SETUP_MARKERS)
  1078. or observed_all[: len(SETUP_MARKERS)] != list(SETUP_MARKERS)
  1079. ):
  1080. failures.append("connect_cable_marker_mismatch")
  1081. if any(observed.count(expected) != 1 for expected in EXPECTED_MARKERS) or any(
  1082. marker == "unrecognized_run_operation" for marker in observed_all
  1083. ):
  1084. failures.append("transaction_count_not_one")
  1085. for index, expected in enumerate(EXPECTED_MARKERS):
  1086. if expected not in observed:
  1087. failures.append(f"missing_marker:{expected}")
  1088. elif index >= len(observed) or observed[index] != expected:
  1089. failures.append(f"out_of_order_marker:{expected}")
  1090. if len(observed) != len(EXPECTED_MARKERS) and not any(
  1091. failure == "transaction_count_not_one" for failure in failures
  1092. ):
  1093. failures.append("marker_count_mismatch")
  1094. return failures
  1095. def _marker_signature(transcript: str) -> list[tuple[str, str]]:
  1096. signature: list[tuple[str, str]] = []
  1097. for record in _marker_records(transcript):
  1098. detail = str(record.get("command") or record.get("chip") or record.get("operation") or "")
  1099. signature.append((str(record["marker"]), detail))
  1100. return signature
  1101. def _record(records: list[dict[str, Any]], marker: str) -> dict[str, Any] | None:
  1102. matches = [record for record in records if record["marker"] == marker]
  1103. return matches[0] if len(matches) == 1 else None
  1104. def _command_failures(
  1105. records: list[dict[str, Any]], *, expected_staging_path: str, td_bin: str
  1106. ) -> tuple[list[str], dict[str, Any]]:
  1107. failures: list[str] = []
  1108. details: dict[str, Any] = {}
  1109. expected_path = _canonical_windows_path(expected_staging_path, td_bin=td_bin)
  1110. chip = _record(records, "chip_validation")
  1111. if chip is not None and chip.get("chip") != TARGET_CHIP:
  1112. failures.append("chip_mismatch")
  1113. observed_paths: list[str] = []
  1114. for marker in ("download_start", "download_finish"):
  1115. record = _record(records, marker)
  1116. if record is None:
  1117. continue
  1118. command = str(record["command"])
  1119. parsed = DOWNLOAD_RE.match(command)
  1120. if parsed is None:
  1121. failures.append("download_command_mismatch")
  1122. continue
  1123. if parsed.group("mode") != "jtag" or parsed.group("cable") != "0":
  1124. failures.append("download_command_mismatch")
  1125. if parsed.group("speed") != str(JTAG_SPEED_CODE):
  1126. failures.append("jtag_speed_mismatch")
  1127. observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
  1128. for marker in ("bit_to_vec_start", "bit_to_vec_finish"):
  1129. record = _record(records, marker)
  1130. if record is None:
  1131. continue
  1132. command = str(record["command"])
  1133. parsed = BIT_TO_VEC_RE.match(command)
  1134. if parsed is None:
  1135. failures.append("bit_to_vec_command_mismatch")
  1136. continue
  1137. if parsed.group("chip") != TARGET_CHIP:
  1138. failures.append("chip_mismatch")
  1139. if parsed.group("mode") != "jtag_burst":
  1140. failures.append("bit_to_vec_mode_mismatch")
  1141. if parsed.group("freq") != BIT_TO_VEC_FREQUENCY:
  1142. failures.append("bit_to_vec_frequency_mismatch")
  1143. observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
  1144. for marker in ("program_start", "program_finish"):
  1145. record = _record(records, marker)
  1146. if record is None:
  1147. continue
  1148. command = str(record["command"])
  1149. parsed = PROGRAM_RE.match(command)
  1150. if parsed is None:
  1151. failures.append("program_command_mismatch")
  1152. continue
  1153. if parsed.group("cable") != "0" or parsed.group("mode") != "svf":
  1154. failures.append("program_command_mismatch")
  1155. if parsed.group("speed") != str(JTAG_SPEED_CODE):
  1156. failures.append("jtag_speed_mismatch")
  1157. if observed_paths and any(path != expected_path for path in observed_paths):
  1158. failures.append("staging_path_mismatch")
  1159. if len(set(observed_paths)) > 1:
  1160. failures.append("transaction_bitstream_path_mismatch")
  1161. details["expected_staging_path"] = expected_path
  1162. details["observed_bitstream_paths"] = sorted(set(observed_paths))
  1163. return failures, details
  1164. def _transcript_failures(transcript: str) -> tuple[list[str], list[str], bool]:
  1165. failures: list[str] = []
  1166. error_markers: list[str] = []
  1167. forbidden = False
  1168. for raw_line in transcript.splitlines():
  1169. for match in ERROR_RE.finditer(raw_line):
  1170. marker = match.group(0)
  1171. if marker.casefold() not in {item.casefold() for item in error_markers}:
  1172. error_markers.append(marker)
  1173. failures.append(f"error_marker:{marker}")
  1174. for match in FORBIDDEN_RE.finditer(raw_line):
  1175. forbidden = True
  1176. action = match.group(0).lower()
  1177. failure = f"forbidden_action:{action}"
  1178. if failure not in failures:
  1179. failures.append(failure)
  1180. return failures, error_markers, forbidden
  1181. def build_program_sram_receipt(
  1182. *,
  1183. transcript: str,
  1184. build_id: str,
  1185. bitstream_path: str,
  1186. bitstream_bytes: bytes,
  1187. expected_bitstream_sha256: str,
  1188. exit_code: int,
  1189. run_id: str,
  1190. command_execution_attempted: bool = False,
  1191. timed_out: bool = False,
  1192. td_bin: str = "",
  1193. ) -> dict[str, Any]:
  1194. """Build a strict receipt from the exact BitWriter log increment."""
  1195. failures: list[str] = []
  1196. try:
  1197. expected_staging_path = staged_bitstream_path(build_id)
  1198. except ValueError:
  1199. expected_staging_path = ""
  1200. failures.append("build_id_invalid")
  1201. records = _marker_records(transcript)
  1202. failures.extend(_marker_failures(records))
  1203. command_failures, command_details = _command_failures(
  1204. records,
  1205. expected_staging_path=expected_staging_path,
  1206. td_bin=td_bin,
  1207. )
  1208. failures.extend(command_failures)
  1209. transcript_failures, error_markers, forbidden = _transcript_failures(transcript)
  1210. failures.extend(transcript_failures)
  1211. actual_sha256 = hashlib.sha256(bitstream_bytes).hexdigest()
  1212. if not SHA256_RE.fullmatch(expected_bitstream_sha256):
  1213. failures.append("bitstream_sha256_invalid")
  1214. elif actual_sha256.casefold() != expected_bitstream_sha256.casefold():
  1215. failures.append("bitstream_sha256_mismatch")
  1216. staging_matches = (
  1217. bool(expected_staging_path)
  1218. and _canonical_windows_path(bitstream_path, td_bin=td_bin)
  1219. == _canonical_windows_path(expected_staging_path, td_bin=td_bin)
  1220. )
  1221. if not staging_matches:
  1222. failures.append("staging_path_mismatch")
  1223. if exit_code != 0:
  1224. failures.append("exit_code_nonzero")
  1225. if not command_execution_attempted:
  1226. failures.append("program_command_not_executed")
  1227. if timed_out:
  1228. failures.append("program_timeout")
  1229. failures = list(dict.fromkeys(failures))
  1230. transaction_records = [record for record in records if record["marker"] in EXPECTED_MARKERS]
  1231. setup_records = [record for record in records if record["marker"] in SETUP_MARKERS]
  1232. ordered_markers_complete = (
  1233. [record["marker"] for record in transaction_records] == list(EXPECTED_MARKERS)
  1234. and not any(failure.startswith(("missing_marker:", "out_of_order_marker:")) for failure in failures)
  1235. and "connect_cable_marker_mismatch" not in failures
  1236. )
  1237. parser_status = "pass" if not failures else "fail"
  1238. status = "fail_forbidden_action" if forbidden else parser_status
  1239. return {
  1240. "schema": SCHEMA_NAME,
  1241. "status": status,
  1242. "run_id": run_id,
  1243. "request": {
  1244. "operation": "PROGRAM_SRAM",
  1245. "target_chip": TARGET_CHIP,
  1246. "cable_index": 0,
  1247. "speed_code": JTAG_SPEED_CODE,
  1248. "speed_hz": JTAG_SPEED_HZ,
  1249. "attempt_limit": 1,
  1250. "power_cycle_allowed": False,
  1251. },
  1252. "bitstream": {
  1253. "path": bitstream_path,
  1254. "sha256": actual_sha256,
  1255. "build_id": build_id,
  1256. },
  1257. "staging": {
  1258. "expected_path": expected_staging_path,
  1259. "observed_path": bitstream_path,
  1260. "matches_expected_path": staging_matches,
  1261. },
  1262. "execution": {
  1263. "exit_code": exit_code,
  1264. "timed_out": timed_out,
  1265. "attempt_count": 1,
  1266. "retry_count": 0,
  1267. "power_cycle_count": 0,
  1268. "command_execution_attempted": command_execution_attempted,
  1269. },
  1270. "parser": {
  1271. "status": parser_status,
  1272. "exit_code_trusted": False,
  1273. "ordered_markers": list(EXPECTED_MARKERS),
  1274. "ordered_markers_complete": ordered_markers_complete,
  1275. "observed_markers": [record["marker"] for record in transaction_records],
  1276. "observed_marker_lines": [record["line"] for record in transaction_records],
  1277. "setup_markers": [record["marker"] for record in setup_records],
  1278. "setup_marker_lines": [record["line"] for record in setup_records],
  1279. "stdout_transaction_mirror": False,
  1280. "error_markers": error_markers,
  1281. "failures": failures,
  1282. "transcript_sha256": hashlib.sha256(transcript.encode("utf-8")).hexdigest(),
  1283. **command_details,
  1284. },
  1285. "safety": {
  1286. "flash_attempted": forbidden,
  1287. "programs_nonvolatile": forbidden,
  1288. "power_cycle_attempted": False,
  1289. "driver_install_attempted": False,
  1290. "toggles_dtr_rts": False,
  1291. "real_ptc_fan_action_attempted": False,
  1292. "external_programming_command_executed": command_execution_attempted,
  1293. },
  1294. "authority_boundary": (
  1295. "This receipt proves only one parsed PROGRAM_SRAM transaction against the staged bitstream. "
  1296. "It does not certify flash, thermal performance, or real PTC/FAN load behavior; "
  1297. "Normal v3 has no local closed-loop control."
  1298. ),
  1299. }
  1300. def build_parser() -> argparse.ArgumentParser:
  1301. parser = argparse.ArgumentParser(description=__doc__)
  1302. parser.add_argument("--transcript", type=Path, required=True, help="captured BitWriter log increment")
  1303. parser.add_argument("--bitstream", type=Path, required=True, help="staged bitstream to hash")
  1304. parser.add_argument("--build-id", required=True)
  1305. parser.add_argument("--sha256", required=True, dest="expected_bitstream_sha256")
  1306. parser.add_argument("--exit-code", type=int, default=0, help="observed tool exit code")
  1307. parser.add_argument("--run-id", required=True)
  1308. parser.add_argument("--td-bin", default="")
  1309. parser.add_argument("--receipt", type=Path, help="optional JSON receipt output path")
  1310. return parser
  1311. def main(argv: list[str] | None = None) -> int:
  1312. args = build_parser().parse_args(argv)
  1313. receipt = build_program_sram_receipt(
  1314. transcript=args.transcript.read_text(encoding="utf-8", errors="replace"),
  1315. build_id=args.build_id,
  1316. bitstream_path=str(args.bitstream),
  1317. bitstream_bytes=args.bitstream.read_bytes(),
  1318. expected_bitstream_sha256=args.expected_bitstream_sha256,
  1319. exit_code=args.exit_code,
  1320. run_id=args.run_id,
  1321. command_execution_attempted=False,
  1322. timed_out=False,
  1323. td_bin=args.td_bin,
  1324. )
  1325. encoded = json.dumps(receipt, indent=2) + "\n"
  1326. if args.receipt is not None:
  1327. args.receipt.parent.mkdir(parents=True, exist_ok=True)
  1328. args.receipt.write_text(encoded, encoding="utf-8", newline="\n")
  1329. print(encoded, end="")
  1330. return 0 if receipt["status"] == "pass" else 1
  1331. if __name__ == "__main__":
  1332. raise SystemExit(main())