|
|
@@ -5,14 +5,18 @@ from __future__ import annotations
|
|
|
|
|
|
import argparse
|
|
|
import ctypes
|
|
|
+import getpass
|
|
|
import hashlib
|
|
|
import json
|
|
|
+import locale
|
|
|
import ntpath
|
|
|
import os
|
|
|
import re
|
|
|
import shutil
|
|
|
import subprocess
|
|
|
+import tempfile
|
|
|
import time
|
|
|
+from ctypes import wintypes
|
|
|
from datetime import datetime, timezone
|
|
|
from pathlib import Path
|
|
|
from typing import Any, Callable
|
|
|
@@ -61,6 +65,13 @@ PROGRAM_RE = re.compile(
|
|
|
PROGRAM_TIMEOUT_SECONDS = 60
|
|
|
PROCESS_CLEANUP_WAIT_SECONDS = 5.0
|
|
|
MUTEX_NAME = r"Global\Prod2UProgramSram"
|
|
|
+TD_PROCESS_EXECUTABLES = (
|
|
|
+ "td.exe",
|
|
|
+ "td_commands_prompt.exe",
|
|
|
+ "bw.exe",
|
|
|
+ "bw_commands_prompt.exe",
|
|
|
+ "hwserver.exe",
|
|
|
+)
|
|
|
|
|
|
|
|
|
def utc_now() -> str:
|
|
|
@@ -156,84 +167,429 @@ class WindowsNamedMutex:
|
|
|
return False
|
|
|
|
|
|
|
|
|
-def close_td_processes(td_root: Path) -> dict[str, Any]:
|
|
|
- """Gracefully close, then bound-force-close, TD processes from one install root."""
|
|
|
- root = str(td_root.resolve())
|
|
|
- script = r'''
|
|
|
+class WindowsTdProcessAdapter:
|
|
|
+ """Read and control qualified Anlogic processes with PID-reuse checks."""
|
|
|
+
|
|
|
+ def __init__(self, runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> None:
|
|
|
+ self.runner = runner
|
|
|
+
|
|
|
+ def _run_json(self, script: str, *, env: dict[str, str] | None = None) -> Any:
|
|
|
+ command_env = os.environ.copy()
|
|
|
+ if env:
|
|
|
+ command_env.update(env)
|
|
|
+ result = self.runner(
|
|
|
+ ["powershell.exe", "-NoProfile", "-Command", script],
|
|
|
+ capture_output=True,
|
|
|
+ text=True,
|
|
|
+ check=False,
|
|
|
+ timeout=15,
|
|
|
+ env=command_env,
|
|
|
+ )
|
|
|
+ if result.returncode != 0:
|
|
|
+ detail = result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}"
|
|
|
+ raise RuntimeError(detail)
|
|
|
+ try:
|
|
|
+ return json.loads(result.stdout)
|
|
|
+ except json.JSONDecodeError as exc:
|
|
|
+ raise RuntimeError(f"invalid process audit JSON: {exc}") from exc
|
|
|
+
|
|
|
+ def discover(self) -> list[dict[str, Any]]:
|
|
|
+ candidate_names = ", ".join(f"'{name}'" for name in TD_PROCESS_EXECUTABLES)
|
|
|
+ script = rf'''
|
|
|
+$ErrorActionPreference = 'Stop'
|
|
|
+$candidateNames = @({candidate_names})
|
|
|
+$records = @()
|
|
|
+$candidates = @(Get-CimInstance Win32_Process | Where-Object {{
|
|
|
+ $candidateNames -contains ([string]$_.Name).ToLowerInvariant()
|
|
|
+}} | Sort-Object ProcessId)
|
|
|
+foreach ($process in $candidates) {{
|
|
|
+ $record = [ordered]@{{
|
|
|
+ pid = [int]$process.ProcessId
|
|
|
+ name = [string]$process.Name
|
|
|
+ path = $null
|
|
|
+ user = $null
|
|
|
+ session_id = $null
|
|
|
+ parent_pid = $null
|
|
|
+ command_line = $null
|
|
|
+ start_time = $null
|
|
|
+ exe_sha256 = $null
|
|
|
+ }}
|
|
|
+ try {{
|
|
|
+ if ([string]::IsNullOrWhiteSpace([string]$process.ExecutablePath)) {{ throw 'path unavailable' }}
|
|
|
+ $record.path = [System.IO.Path]::GetFullPath([string]$process.ExecutablePath)
|
|
|
+ $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwner
|
|
|
+ if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{
|
|
|
+ throw ('owner unavailable: return={0}' -f $owner.ReturnValue)
|
|
|
+ }}
|
|
|
+ $record.user = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{
|
|
|
+ [string]$owner.User
|
|
|
+ }} else {{
|
|
|
+ '{0}\{1}' -f $owner.Domain, $owner.User
|
|
|
+ }})
|
|
|
+ $record.session_id = [int]$process.SessionId
|
|
|
+ $record.parent_pid = [int]$process.ParentProcessId
|
|
|
+ if ([string]::IsNullOrWhiteSpace([string]$process.CommandLine)) {{ throw 'command line unavailable' }}
|
|
|
+ $record.command_line = [string]$process.CommandLine
|
|
|
+ if ($null -eq $process.CreationDate) {{ throw 'start time unavailable' }}
|
|
|
+ $record.start_time = ([DateTime]$process.CreationDate).ToUniversalTime().ToString('o')
|
|
|
+ $record.exe_sha256 = (Get-FileHash -LiteralPath $record.path -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
|
+ }} catch {{
|
|
|
+ $record.identity_error = $_.Exception.Message
|
|
|
+ }}
|
|
|
+ $records += [pscustomobject]$record
|
|
|
+}}
|
|
|
+[ordered]@{{ processes = @($records) }} | ConvertTo-Json -Compress -Depth 4
|
|
|
+'''
|
|
|
+ payload = self._run_json(script)
|
|
|
+ processes = payload.get("processes") if isinstance(payload, dict) else None
|
|
|
+ if not isinstance(processes, list):
|
|
|
+ raise RuntimeError("process discovery did not return an array")
|
|
|
+ return processes
|
|
|
+
|
|
|
+ def _identity_action(self, process: dict[str, Any], action: str) -> dict[str, Any]:
|
|
|
+ if action == "close":
|
|
|
+ action_script = "$native = Get-Process -Id $pidValue -ErrorAction Stop; $null = $native.CloseMainWindow()"
|
|
|
+ elif action == "probe":
|
|
|
+ action_script = ""
|
|
|
+ elif action == "force":
|
|
|
+ action_script = "Stop-Process -Id $pidValue -Force -ErrorAction Stop"
|
|
|
+ else:
|
|
|
+ raise ValueError(f"unknown process action: {action}")
|
|
|
+ script = rf'''
|
|
|
$ErrorActionPreference = 'Stop'
|
|
|
-if ([string]::IsNullOrWhiteSpace($env:PROD2U_TD_ROOT)) { throw 'PROD2U_TD_ROOT is required' }
|
|
|
-$root = [System.IO.Path]::GetFullPath($env:PROD2U_TD_ROOT).TrimEnd('\')
|
|
|
-$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar
|
|
|
-$allowed = @('td','bw','bitwriter','chipwatcher','bw_commands_prompt')
|
|
|
-function Find-TdProcesses {
|
|
|
- @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
|
|
|
- try {
|
|
|
- $path = $_.Path
|
|
|
- $fullPath = [System.IO.Path]::GetFullPath($path)
|
|
|
- $path -and
|
|
|
- ($fullPath.Equals($root, [System.StringComparison]::OrdinalIgnoreCase) -or
|
|
|
- $fullPath.StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)) -and
|
|
|
- ($allowed -contains $_.ProcessName.ToLowerInvariant())
|
|
|
- } catch { $false }
|
|
|
- })
|
|
|
-}
|
|
|
-$initial = Find-TdProcesses
|
|
|
-$graceful = @()
|
|
|
-foreach ($process in $initial) {
|
|
|
- $null = $process.CloseMainWindow()
|
|
|
- $graceful += ('{0}:{1}' -f $process.ProcessName, $process.Id)
|
|
|
-}
|
|
|
-Start-Sleep -Seconds 5
|
|
|
-$survivors = Find-TdProcesses
|
|
|
-$forced = @()
|
|
|
-foreach ($process in $survivors) {
|
|
|
- Stop-Process -Id $process.Id -Force -ErrorAction Stop
|
|
|
- $forced += ('{0}:{1}' -f $process.ProcessName, $process.Id)
|
|
|
-}
|
|
|
-Start-Sleep -Milliseconds 250
|
|
|
-$remaining = @(Find-TdProcesses | ForEach-Object { '{0}:{1}' -f $_.ProcessName, $_.Id })
|
|
|
-[ordered]@{
|
|
|
- status = $(if ($remaining.Count -eq 0) { 'pass' } else { 'fail' })
|
|
|
- td_root = $root
|
|
|
- graceful_close_requested = $graceful
|
|
|
- forced_terminated = $forced
|
|
|
- wait_seconds = 5.0
|
|
|
- remaining = $remaining
|
|
|
-} | ConvertTo-Json -Compress
|
|
|
+$pidValue = [int]$env:PROD2U_PROCESS_PID
|
|
|
+$expectedPath = [System.IO.Path]::GetFullPath($env:PROD2U_PROCESS_PATH)
|
|
|
+$expectedStart = $env:PROD2U_PROCESS_START
|
|
|
+$expectedOwner = $env:PROD2U_PROCESS_OWNER
|
|
|
+$expectedSession = [int]$env:PROD2U_PROCESS_SESSION
|
|
|
+$expectedParent = [int]$env:PROD2U_PROCESS_PARENT
|
|
|
+$expectedCommandLine = $env:PROD2U_PROCESS_COMMAND_LINE
|
|
|
+$expectedSha256 = $env:PROD2U_PROCESS_SHA256
|
|
|
+$current = Get-CimInstance Win32_Process -Filter ("ProcessId = {{0}}" -f $pidValue)
|
|
|
+if ($null -eq $current) {{
|
|
|
+ [ordered]@{{ status = 'not_running'; running = $false }} | ConvertTo-Json -Compress
|
|
|
+ exit 0
|
|
|
+}}
|
|
|
+if ([string]::IsNullOrWhiteSpace([string]$current.ExecutablePath)) {{ throw 'current process path unavailable' }}
|
|
|
+$currentPath = [System.IO.Path]::GetFullPath([string]$current.ExecutablePath)
|
|
|
+$currentStart = ([DateTime]$current.CreationDate).ToUniversalTime().ToString('o')
|
|
|
+$owner = Invoke-CimMethod -InputObject $current -MethodName GetOwner
|
|
|
+if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{
|
|
|
+ throw 'current process owner unavailable'
|
|
|
+}}
|
|
|
+$currentOwner = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{
|
|
|
+ [string]$owner.User
|
|
|
+}} else {{
|
|
|
+ '{{0}}\{{1}}' -f $owner.Domain, $owner.User
|
|
|
+}})
|
|
|
+$currentSha256 = (Get-FileHash -LiteralPath $currentPath -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
|
+if (-not $currentPath.Equals($expectedPath, [System.StringComparison]::OrdinalIgnoreCase) -or
|
|
|
+ -not $currentStart.Equals($expectedStart, [System.StringComparison]::Ordinal) -or
|
|
|
+ -not $currentOwner.Equals($expectedOwner, [System.StringComparison]::OrdinalIgnoreCase) -or
|
|
|
+ [int]$current.SessionId -ne $expectedSession -or
|
|
|
+ [int]$current.ParentProcessId -ne $expectedParent -or
|
|
|
+ -not ([string]$current.CommandLine).Equals($expectedCommandLine, [System.StringComparison]::Ordinal) -or
|
|
|
+ -not $currentSha256.Equals($expectedSha256, [System.StringComparison]::OrdinalIgnoreCase)) {{
|
|
|
+ throw 'process identity changed before action'
|
|
|
+}}
|
|
|
+{action_script}
|
|
|
+[ordered]@{{ status = 'ok'; running = $true }} | ConvertTo-Json -Compress
|
|
|
'''
|
|
|
- env = os.environ.copy()
|
|
|
- env["PROD2U_TD_ROOT"] = root
|
|
|
- result = subprocess.run(
|
|
|
- ["powershell.exe", "-NoProfile", "-Command", script],
|
|
|
- capture_output=True,
|
|
|
- text=True,
|
|
|
- check=False,
|
|
|
- timeout=15,
|
|
|
- env=env,
|
|
|
+ return self._run_json(
|
|
|
+ script,
|
|
|
+ env={
|
|
|
+ "PROD2U_PROCESS_PID": str(process["pid"]),
|
|
|
+ "PROD2U_PROCESS_PATH": str(process["path"]),
|
|
|
+ "PROD2U_PROCESS_START": str(process["start_time"]),
|
|
|
+ "PROD2U_PROCESS_OWNER": str(process["user"]),
|
|
|
+ "PROD2U_PROCESS_SESSION": str(process["session_id"]),
|
|
|
+ "PROD2U_PROCESS_PARENT": str(process["parent_pid"]),
|
|
|
+ "PROD2U_PROCESS_COMMAND_LINE": str(process["command_line"]),
|
|
|
+ "PROD2U_PROCESS_SHA256": str(process["exe_sha256"]),
|
|
|
+ },
|
|
|
+ )
|
|
|
+
|
|
|
+ def request_close(self, process: dict[str, Any]) -> None:
|
|
|
+ self._identity_action(process, "close")
|
|
|
+
|
|
|
+ def is_running(self, process: dict[str, Any]) -> bool:
|
|
|
+ return bool(self._identity_action(process, "probe").get("running"))
|
|
|
+
|
|
|
+ def force_stop(self, process: dict[str, Any]) -> None:
|
|
|
+ self._identity_action(process, "force")
|
|
|
+
|
|
|
+
|
|
|
+def _process_identity_errors(process: Any, *, td_root: str) -> tuple[dict[str, Any] | None, list[str]]:
|
|
|
+ if not isinstance(process, dict):
|
|
|
+ return None, ["identity_unreadable:unknown:record"]
|
|
|
+ pid = process.get("pid")
|
|
|
+ pid_label = str(pid) if isinstance(pid, int) and not isinstance(pid, bool) else "unknown"
|
|
|
+ errors: list[str] = []
|
|
|
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
|
|
|
+ errors.append("identity_unreadable:unknown:pid")
|
|
|
+ name = process.get("name")
|
|
|
+ if not isinstance(name, str) or not name.strip():
|
|
|
+ errors.append(f"identity_unreadable:{pid_label}:name")
|
|
|
+ elif name.casefold() not in {candidate.casefold() for candidate in TD_PROCESS_EXECUTABLES}:
|
|
|
+ errors.append(f"unexpected_process_name:{pid_label}")
|
|
|
+ for field in ("path", "user", "command_line", "start_time", "exe_sha256"):
|
|
|
+ value = process.get(field)
|
|
|
+ if not isinstance(value, str) or not value.strip():
|
|
|
+ errors.append(f"identity_unreadable:{pid_label}:{field}")
|
|
|
+ identity_error = process.get("identity_error")
|
|
|
+ if identity_error:
|
|
|
+ errors.append(f"identity_unreadable:{pid_label}:adapter:{identity_error}")
|
|
|
+ path = process.get("path")
|
|
|
+ if isinstance(path, str) and path.strip():
|
|
|
+ canonical_path = ntpath.normcase(ntpath.normpath(path))
|
|
|
+ canonical_root = ntpath.normcase(ntpath.normpath(td_root)).rstrip("\\/")
|
|
|
+ root_prefix = canonical_root + "\\"
|
|
|
+ if not ntpath.isabs(path) or not canonical_path.startswith(root_prefix):
|
|
|
+ errors.append(f"unknown_process_path:{pid_label}")
|
|
|
+ if isinstance(name, str) and name.strip() and ntpath.basename(canonical_path) != name.casefold():
|
|
|
+ errors.append(f"process_name_path_mismatch:{pid_label}")
|
|
|
+ exe_sha256 = process.get("exe_sha256")
|
|
|
+ if isinstance(exe_sha256, str) and exe_sha256.strip() and not re.fullmatch(r"[0-9a-f]{64}", exe_sha256):
|
|
|
+ errors.append(f"identity_unreadable:{pid_label}:exe_sha256")
|
|
|
+ for field in ("session_id", "parent_pid"):
|
|
|
+ value = process.get(field)
|
|
|
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
|
|
+ errors.append(f"identity_unreadable:{pid_label}:{field}")
|
|
|
+ if errors:
|
|
|
+ return None, errors
|
|
|
+ return {
|
|
|
+ "pid": int(pid),
|
|
|
+ "name": str(name),
|
|
|
+ "path": str(process["path"]),
|
|
|
+ "user": str(process["user"]),
|
|
|
+ "session_id": int(process["session_id"]),
|
|
|
+ "parent_pid": int(process["parent_pid"]),
|
|
|
+ "command_line": str(process["command_line"]),
|
|
|
+ "start_time": str(process["start_time"]),
|
|
|
+ "exe_sha256": str(process["exe_sha256"]),
|
|
|
+ }, []
|
|
|
+
|
|
|
+
|
|
|
+def _canonical_command_line(value: str) -> str:
|
|
|
+ return value.strip()
|
|
|
+
|
|
|
+
|
|
|
+def _validate_ownership_policy(policy: Any) -> list[str]:
|
|
|
+ if not isinstance(policy, dict):
|
|
|
+ return ["ownership_policy_missing"]
|
|
|
+ errors: list[str] = []
|
|
|
+ for field in ("owner", "command_line"):
|
|
|
+ if not isinstance(policy.get(field), str) or not policy[field].strip():
|
|
|
+ errors.append(f"ownership_policy_invalid:{field}")
|
|
|
+ for field in ("session_id", "parent_pid"):
|
|
|
+ value = policy.get(field)
|
|
|
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
|
|
+ errors.append(f"ownership_policy_invalid:{field}")
|
|
|
+ binaries = policy.get("approved_binaries")
|
|
|
+ if not isinstance(binaries, list) or not binaries:
|
|
|
+ errors.append("ownership_policy_invalid:approved_binaries")
|
|
|
+ else:
|
|
|
+ for binary in binaries:
|
|
|
+ if not isinstance(binary, dict):
|
|
|
+ errors.append("ownership_policy_invalid:approved_binary")
|
|
|
+ continue
|
|
|
+ if not all(isinstance(binary.get(field), str) and binary[field].strip() for field in ("name", "path")):
|
|
|
+ errors.append("ownership_policy_invalid:approved_binary_identity")
|
|
|
+ if not isinstance(binary.get("exe_sha256"), str) or not SHA256_RE.fullmatch(binary["exe_sha256"]):
|
|
|
+ errors.append("ownership_policy_invalid:approved_binary_hash")
|
|
|
+ return list(dict.fromkeys(errors))
|
|
|
+
|
|
|
+
|
|
|
+def _is_harness_owned(process: dict[str, Any], policy: dict[str, Any]) -> bool:
|
|
|
+ binary_matches = any(
|
|
|
+ str(process["name"]).casefold() == str(binary["name"]).casefold()
|
|
|
+ and ntpath.normcase(ntpath.normpath(str(process["path"])))
|
|
|
+ == ntpath.normcase(ntpath.normpath(str(binary["path"])))
|
|
|
+ and str(process["exe_sha256"]).casefold() == str(binary["exe_sha256"]).casefold()
|
|
|
+ for binary in policy["approved_binaries"]
|
|
|
+ )
|
|
|
+ return (
|
|
|
+ binary_matches
|
|
|
+ and str(process["user"]).casefold() == str(policy["owner"]).casefold()
|
|
|
+ and process["session_id"] == policy["session_id"]
|
|
|
+ and process["parent_pid"] == policy["parent_pid"]
|
|
|
+ and _canonical_command_line(str(process["command_line"]))
|
|
|
+ == _canonical_command_line(str(policy["command_line"]))
|
|
|
)
|
|
|
- if result.returncode != 0:
|
|
|
+
|
|
|
+
|
|
|
+def build_process_ownership_policy(*, executable: Path, command: list[str]) -> dict[str, Any]:
|
|
|
+ """Build the exact identity policy for a process launched by this harness."""
|
|
|
+ executable = executable.resolve()
|
|
|
+ if os.name == "nt":
|
|
|
+ session_id = ctypes.c_uint32()
|
|
|
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
+ kernel32.ProcessIdToSessionId.argtypes = [ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32)]
|
|
|
+ kernel32.ProcessIdToSessionId.restype = ctypes.c_bool
|
|
|
+ if not kernel32.ProcessIdToSessionId(os.getpid(), ctypes.byref(session_id)):
|
|
|
+ raise OSError(ctypes.get_last_error(), "ProcessIdToSessionId failed")
|
|
|
+ domain = os.environ.get("USERDOMAIN", "").strip()
|
|
|
+ username = os.environ.get("USERNAME", "").strip() or getpass.getuser()
|
|
|
+ owner = f"{domain}\\{username}" if domain else username
|
|
|
+ current_session = int(session_id.value)
|
|
|
+ else:
|
|
|
+ owner = getpass.getuser()
|
|
|
+ current_session = 0
|
|
|
+ return {
|
|
|
+ "owner": owner,
|
|
|
+ "session_id": current_session,
|
|
|
+ "parent_pid": os.getpid(),
|
|
|
+ "approved_binaries": [
|
|
|
+ {
|
|
|
+ "name": executable.name.casefold(),
|
|
|
+ "path": str(executable),
|
|
|
+ "exe_sha256": sha256_file(executable),
|
|
|
+ }
|
|
|
+ ],
|
|
|
+ "command_line": subprocess.list2cmdline(command),
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def close_td_processes(
|
|
|
+ td_root: Path,
|
|
|
+ *,
|
|
|
+ ownership_policy: dict[str, Any] | None = None,
|
|
|
+ process_adapter: Any | None = None,
|
|
|
+ sleeper: Callable[[float], None] = time.sleep,
|
|
|
+) -> dict[str, Any]:
|
|
|
+ """Terminate only processes proven to be owned by this harness invocation."""
|
|
|
+ root = str(td_root.resolve())
|
|
|
+ adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter()
|
|
|
+ discovered: list[dict[str, Any]] = []
|
|
|
+ harness_owned: list[dict[str, Any]] = []
|
|
|
+ blocking: list[dict[str, Any]] = []
|
|
|
+ graceful: list[dict[str, Any]] = []
|
|
|
+ forced: list[dict[str, Any]] = []
|
|
|
+ errors = _validate_ownership_policy(ownership_policy)
|
|
|
+
|
|
|
+ def result(status: str, *, remaining: list[dict[str, Any]] | None = None, audited: bool) -> dict[str, Any]:
|
|
|
return {
|
|
|
- "status": "fail",
|
|
|
+ "status": status,
|
|
|
"td_root": root,
|
|
|
- "graceful_close_requested": [],
|
|
|
- "forced_terminated": [],
|
|
|
+ "identity_audit_completed_before_action": audited,
|
|
|
+ "ownership_policy": ownership_policy,
|
|
|
+ "discovered_processes": discovered,
|
|
|
+ "harness_owned_processes": harness_owned,
|
|
|
+ "blocking_processes": blocking,
|
|
|
+ "graceful_close_requested": graceful,
|
|
|
+ "forced_terminated": forced,
|
|
|
"wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
|
|
|
- "remaining": [],
|
|
|
- "error": result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}",
|
|
|
+ "remaining": remaining or [],
|
|
|
+ "post_action_audit_completed": False,
|
|
|
+ "post_action_discovered_processes": [],
|
|
|
+ "post_action_harness_owned_processes": [],
|
|
|
+ "post_action_blocking_processes": [],
|
|
|
+ "residual_processes": [],
|
|
|
+ "post_action_errors": [],
|
|
|
+ "errors": list(dict.fromkeys(errors)),
|
|
|
}
|
|
|
+
|
|
|
+ if errors:
|
|
|
+ return result("fail", audited=False)
|
|
|
try:
|
|
|
- payload = json.loads(result.stdout)
|
|
|
- except json.JSONDecodeError as exc:
|
|
|
- return {
|
|
|
- "status": "fail",
|
|
|
- "td_root": root,
|
|
|
- "graceful_close_requested": [],
|
|
|
- "forced_terminated": [],
|
|
|
- "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
|
|
|
- "remaining": [],
|
|
|
- "error": f"invalid process cleanup JSON: {exc}",
|
|
|
- }
|
|
|
- return payload
|
|
|
+ raw_processes = adapter.discover()
|
|
|
+ except Exception as exc:
|
|
|
+ errors.append(f"process_discovery_failed:{exc}")
|
|
|
+ return result("fail", audited=False)
|
|
|
+ if not isinstance(raw_processes, list):
|
|
|
+ errors.append("process_discovery_failed:not_an_array")
|
|
|
+ return result("fail", audited=False)
|
|
|
+ for raw_process in raw_processes:
|
|
|
+ process, process_errors = _process_identity_errors(raw_process, td_root=root)
|
|
|
+ errors.extend(process_errors)
|
|
|
+ if process is not None:
|
|
|
+ discovered.append(process)
|
|
|
+ if errors:
|
|
|
+ return result("fail", audited=False)
|
|
|
+ for process in discovered:
|
|
|
+ if _is_harness_owned(process, ownership_policy):
|
|
|
+ harness_owned.append(process)
|
|
|
+ else:
|
|
|
+ blocking.append(process)
|
|
|
+ if blocking:
|
|
|
+ errors.append("blocking_td_processes_present")
|
|
|
+ return result("fail", remaining=discovered, audited=True)
|
|
|
+
|
|
|
+ try:
|
|
|
+ for process in harness_owned:
|
|
|
+ adapter.request_close(process)
|
|
|
+ graceful.append(process)
|
|
|
+ if harness_owned:
|
|
|
+ sleeper(PROCESS_CLEANUP_WAIT_SECONDS)
|
|
|
+ for process in harness_owned:
|
|
|
+ if adapter.is_running(process):
|
|
|
+ adapter.force_stop(process)
|
|
|
+ forced.append(process)
|
|
|
+ raw_remaining = adapter.discover()
|
|
|
+ except Exception as exc:
|
|
|
+ errors.append(f"process_control_failed:{exc}")
|
|
|
+ return result("fail", audited=True)
|
|
|
+
|
|
|
+ remaining: list[dict[str, Any]] = []
|
|
|
+ if not isinstance(raw_remaining, list):
|
|
|
+ errors.append("final_process_discovery_failed:not_an_array")
|
|
|
+ else:
|
|
|
+ for raw_process in raw_remaining:
|
|
|
+ process, process_errors = _process_identity_errors(raw_process, td_root=root)
|
|
|
+ errors.extend(process_errors)
|
|
|
+ if process is not None:
|
|
|
+ remaining.append(process)
|
|
|
+ if remaining:
|
|
|
+ errors.append("qualified_processes_remaining")
|
|
|
+ return result("pass" if not errors else "fail", remaining=remaining, audited=True)
|
|
|
+
|
|
|
+
|
|
|
+def audit_td_processes(
|
|
|
+ td_root: Path,
|
|
|
+ *,
|
|
|
+ ownership_policy: dict[str, Any],
|
|
|
+ process_adapter: Any | None = None,
|
|
|
+) -> dict[str, Any]:
|
|
|
+ """Perform a non-destructive post-action audit of all TD candidates."""
|
|
|
+ root = str(td_root.resolve())
|
|
|
+ adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter()
|
|
|
+ errors = _validate_ownership_policy(ownership_policy)
|
|
|
+ discovered: list[dict[str, Any]] = []
|
|
|
+ harness_owned: list[dict[str, Any]] = []
|
|
|
+ blocking: list[dict[str, Any]] = []
|
|
|
+ audit_completed = False
|
|
|
+ if not errors:
|
|
|
+ try:
|
|
|
+ raw_processes = adapter.discover()
|
|
|
+ except Exception as exc:
|
|
|
+ errors.append(f"post_action_process_discovery_failed:{exc}")
|
|
|
+ raw_processes = []
|
|
|
+ if not isinstance(raw_processes, list):
|
|
|
+ errors.append("post_action_process_discovery_failed:not_an_array")
|
|
|
+ else:
|
|
|
+ for raw_process in raw_processes:
|
|
|
+ process, process_errors = _process_identity_errors(raw_process, td_root=root)
|
|
|
+ errors.extend(process_errors)
|
|
|
+ if process is not None:
|
|
|
+ discovered.append(process)
|
|
|
+ audit_completed = not errors
|
|
|
+ if not errors:
|
|
|
+ for process in discovered:
|
|
|
+ if _is_harness_owned(process, ownership_policy):
|
|
|
+ harness_owned.append(process)
|
|
|
+ else:
|
|
|
+ blocking.append(process)
|
|
|
+ if discovered:
|
|
|
+ errors.append("post_action_td_processes_remaining")
|
|
|
+ return {
|
|
|
+ "status": "pass" if not errors else "fail",
|
|
|
+ "post_action_audit_completed": audit_completed,
|
|
|
+ "post_action_discovered_processes": discovered,
|
|
|
+ "post_action_harness_owned_processes": harness_owned,
|
|
|
+ "post_action_blocking_processes": blocking,
|
|
|
+ "residual_processes": discovered,
|
|
|
+ "post_action_errors": list(dict.fromkeys(errors)),
|
|
|
+ }
|
|
|
|
|
|
|
|
|
def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
|
|
|
@@ -331,6 +687,38 @@ class _JobExtendedLimitInformation(ctypes.Structure):
|
|
|
]
|
|
|
|
|
|
|
|
|
+class _StartupInfoW(ctypes.Structure):
|
|
|
+ _fields_ = [
|
|
|
+ ("cb", wintypes.DWORD),
|
|
|
+ ("lpReserved", wintypes.LPWSTR),
|
|
|
+ ("lpDesktop", wintypes.LPWSTR),
|
|
|
+ ("lpTitle", wintypes.LPWSTR),
|
|
|
+ ("dwX", wintypes.DWORD),
|
|
|
+ ("dwY", wintypes.DWORD),
|
|
|
+ ("dwXSize", wintypes.DWORD),
|
|
|
+ ("dwYSize", wintypes.DWORD),
|
|
|
+ ("dwXCountChars", wintypes.DWORD),
|
|
|
+ ("dwYCountChars", wintypes.DWORD),
|
|
|
+ ("dwFillAttribute", wintypes.DWORD),
|
|
|
+ ("dwFlags", wintypes.DWORD),
|
|
|
+ ("wShowWindow", wintypes.WORD),
|
|
|
+ ("cbReserved2", wintypes.WORD),
|
|
|
+ ("lpReserved2", ctypes.POINTER(wintypes.BYTE)),
|
|
|
+ ("hStdInput", wintypes.HANDLE),
|
|
|
+ ("hStdOutput", wintypes.HANDLE),
|
|
|
+ ("hStdError", wintypes.HANDLE),
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
+class _ProcessInformation(ctypes.Structure):
|
|
|
+ _fields_ = [
|
|
|
+ ("hProcess", wintypes.HANDLE),
|
|
|
+ ("hThread", wintypes.HANDLE),
|
|
|
+ ("dwProcessId", wintypes.DWORD),
|
|
|
+ ("dwThreadId", wintypes.DWORD),
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
def windows_process_is_running(pid: int) -> bool:
|
|
|
if os.name != "nt":
|
|
|
return False
|
|
|
@@ -376,6 +764,29 @@ def run_process_in_job(
|
|
|
kernel32.SetInformationJobObject.restype = ctypes.c_bool
|
|
|
kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
|
|
|
kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
|
|
|
+ kernel32.CreateProcessW.argtypes = [
|
|
|
+ wintypes.LPCWSTR,
|
|
|
+ wintypes.LPWSTR,
|
|
|
+ ctypes.c_void_p,
|
|
|
+ ctypes.c_void_p,
|
|
|
+ wintypes.BOOL,
|
|
|
+ wintypes.DWORD,
|
|
|
+ ctypes.c_void_p,
|
|
|
+ wintypes.LPCWSTR,
|
|
|
+ ctypes.POINTER(_StartupInfoW),
|
|
|
+ ctypes.POINTER(_ProcessInformation),
|
|
|
+ ]
|
|
|
+ kernel32.CreateProcessW.restype = wintypes.BOOL
|
|
|
+ kernel32.ResumeThread.argtypes = [wintypes.HANDLE]
|
|
|
+ kernel32.ResumeThread.restype = wintypes.DWORD
|
|
|
+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
|
|
|
+ kernel32.WaitForSingleObject.restype = wintypes.DWORD
|
|
|
+ kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
|
|
|
+ kernel32.GetExitCodeProcess.restype = wintypes.BOOL
|
|
|
+ kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
|
|
|
+ kernel32.TerminateProcess.restype = wintypes.BOOL
|
|
|
+ kernel32.SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD]
|
|
|
+ kernel32.SetHandleInformation.restype = wintypes.BOOL
|
|
|
kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
|
|
kernel32.TerminateJobObject.restype = ctypes.c_bool
|
|
|
kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
|
@@ -389,31 +800,100 @@ def run_process_in_job(
|
|
|
error = ctypes.get_last_error()
|
|
|
kernel32.CloseHandle(job)
|
|
|
raise OSError(error, "SetInformationJobObject failed")
|
|
|
- stdout_pipe = subprocess.PIPE if capture_output else None
|
|
|
- stderr_pipe = subprocess.PIPE if capture_output else None
|
|
|
- process = subprocess.Popen(
|
|
|
- command,
|
|
|
- cwd=cwd,
|
|
|
- stdout=stdout_pipe,
|
|
|
- stderr=stderr_pipe,
|
|
|
- text=text,
|
|
|
- )
|
|
|
+ CREATE_SUSPENDED = 0x00000004
|
|
|
+ STARTF_USESTDHANDLES = 0x00000100
|
|
|
+ HANDLE_FLAG_INHERIT = 0x00000001
|
|
|
+ WAIT_OBJECT_0 = 0x00000000
|
|
|
+ WAIT_TIMEOUT = 0x00000102
|
|
|
+ INFINITE = 0xFFFFFFFF
|
|
|
+ stdout_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None
|
|
|
+ stderr_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None
|
|
|
+ stdin_file = open(os.devnull, "rb") if capture_output else None
|
|
|
+ inherited_handles: list[int] = []
|
|
|
+ startup = _StartupInfoW()
|
|
|
+ startup.cb = ctypes.sizeof(startup)
|
|
|
+ if capture_output:
|
|
|
+ import msvcrt
|
|
|
+
|
|
|
+ startup.dwFlags = STARTF_USESTDHANDLES
|
|
|
+ startup.hStdInput = wintypes.HANDLE(msvcrt.get_osfhandle(stdin_file.fileno()))
|
|
|
+ startup.hStdOutput = wintypes.HANDLE(msvcrt.get_osfhandle(stdout_file.fileno()))
|
|
|
+ startup.hStdError = wintypes.HANDLE(msvcrt.get_osfhandle(stderr_file.fileno()))
|
|
|
+ inherited_handles = [
|
|
|
+ int(startup.hStdInput),
|
|
|
+ int(startup.hStdOutput),
|
|
|
+ int(startup.hStdError),
|
|
|
+ ]
|
|
|
+ for handle in inherited_handles:
|
|
|
+ if not kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT):
|
|
|
+ raise OSError(ctypes.get_last_error(), "SetHandleInformation failed")
|
|
|
+ process_info = _ProcessInformation()
|
|
|
+ command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline(command))
|
|
|
+ created = False
|
|
|
try:
|
|
|
- if not kernel32.AssignProcessToJobObject(job, ctypes.c_void_p(int(process._handle))):
|
|
|
- process.kill()
|
|
|
- process.wait()
|
|
|
- raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
|
|
|
- try:
|
|
|
- stdout, stderr = process.communicate(timeout=timeout)
|
|
|
- except subprocess.TimeoutExpired as exc:
|
|
|
+ if not kernel32.CreateProcessW(
|
|
|
+ str(command[0]),
|
|
|
+ command_line,
|
|
|
+ None,
|
|
|
+ None,
|
|
|
+ bool(capture_output),
|
|
|
+ CREATE_SUSPENDED,
|
|
|
+ None,
|
|
|
+ cwd,
|
|
|
+ ctypes.byref(startup),
|
|
|
+ ctypes.byref(process_info),
|
|
|
+ ):
|
|
|
+ raise OSError(ctypes.get_last_error(), "CreateProcessW failed")
|
|
|
+ created = True
|
|
|
+ if not kernel32.AssignProcessToJobObject(job, process_info.hProcess):
|
|
|
+ error = ctypes.get_last_error()
|
|
|
+ kernel32.TerminateProcess(process_info.hProcess, 1)
|
|
|
+ kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
|
|
|
+ raise OSError(error, "AssignProcessToJobObject failed")
|
|
|
+ if kernel32.ResumeThread(process_info.hThread) == 0xFFFFFFFF:
|
|
|
+ error = ctypes.get_last_error()
|
|
|
+ kernel32.TerminateJobObject(job, 1)
|
|
|
+ kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
|
|
|
+ raise OSError(error, "ResumeThread failed")
|
|
|
+ wait_milliseconds = max(0, min(int(timeout * 1000), 0xFFFFFFFE))
|
|
|
+ wait_result = kernel32.WaitForSingleObject(process_info.hProcess, wait_milliseconds)
|
|
|
+ timed_out = wait_result == WAIT_TIMEOUT
|
|
|
+ if timed_out:
|
|
|
kernel32.TerminateJobObject(job, 1)
|
|
|
- stdout, stderr = process.communicate()
|
|
|
- raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr) from exc
|
|
|
- result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
|
|
|
+ kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
|
|
|
+ elif wait_result != WAIT_OBJECT_0:
|
|
|
+ raise OSError(ctypes.get_last_error(), "WaitForSingleObject failed")
|
|
|
+ exit_code = wintypes.DWORD()
|
|
|
+ if not kernel32.GetExitCodeProcess(process_info.hProcess, ctypes.byref(exit_code)):
|
|
|
+ raise OSError(ctypes.get_last_error(), "GetExitCodeProcess failed")
|
|
|
+ encoding = locale.getpreferredencoding(False)
|
|
|
+ stdout: str | bytes | None = None
|
|
|
+ stderr: str | bytes | None = None
|
|
|
+ if capture_output:
|
|
|
+ stdout_file.seek(0)
|
|
|
+ stderr_file.seek(0)
|
|
|
+ stdout_bytes = stdout_file.read()
|
|
|
+ stderr_bytes = stderr_file.read()
|
|
|
+ stdout = stdout_bytes.decode(encoding, errors="replace") if text else stdout_bytes
|
|
|
+ stderr = stderr_bytes.decode(encoding, errors="replace") if text else stderr_bytes
|
|
|
+ if timed_out:
|
|
|
+ raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr)
|
|
|
+ result = subprocess.CompletedProcess(command, int(exit_code.value), stdout, stderr)
|
|
|
if check and result.returncode != 0:
|
|
|
raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
|
|
|
return result
|
|
|
finally:
|
|
|
+ for handle in inherited_handles:
|
|
|
+ kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, 0)
|
|
|
+ if created:
|
|
|
+ kernel32.CloseHandle(process_info.hThread)
|
|
|
+ kernel32.CloseHandle(process_info.hProcess)
|
|
|
+ if stdin_file is not None:
|
|
|
+ stdin_file.close()
|
|
|
+ if stdout_file is not None:
|
|
|
+ stdout_file.close()
|
|
|
+ if stderr_file is not None:
|
|
|
+ stderr_file.close()
|
|
|
kernel32.CloseHandle(job)
|
|
|
|
|
|
|
|
|
@@ -440,7 +920,8 @@ def execute_program_sram(
|
|
|
td_root: Path,
|
|
|
run_id: str,
|
|
|
process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
|
|
|
- cleanup_runner: Callable[[Path], dict[str, Any]] = close_td_processes,
|
|
|
+ cleanup_runner: Callable[..., dict[str, Any]] = close_td_processes,
|
|
|
+ residual_audit_runner: Callable[..., dict[str, Any]] = audit_td_processes,
|
|
|
mutex_factory: Callable[[], Any] = WindowsNamedMutex,
|
|
|
) -> dict[str, Any]:
|
|
|
"""Execute exactly one SRAM download and return a strict transaction receipt."""
|
|
|
@@ -466,11 +947,14 @@ def execute_program_sram(
|
|
|
stdout_path = output_dir / "bitwriter-stdout.log"
|
|
|
stderr_path = output_dir / "bitwriter-stderr.log"
|
|
|
delta_path = output_dir / "bitwriter-log-delta.log"
|
|
|
+ tcl_cli_path = tcl_path.absolute().as_posix()
|
|
|
+ command = [str(bw_exe), tcl_cli_path]
|
|
|
+ ownership_policy = build_process_ownership_policy(executable=bw_exe, command=command)
|
|
|
started_at = utc_now()
|
|
|
start_monotonic = time.monotonic()
|
|
|
|
|
|
with mutex_factory():
|
|
|
- cleanup = cleanup_runner(td_root)
|
|
|
+ cleanup = cleanup_runner(td_root, ownership_policy=ownership_policy)
|
|
|
if cleanup.get("status") != "pass":
|
|
|
raise RuntimeError(f"TD process cleanup failed: {cleanup}")
|
|
|
|
|
|
@@ -497,9 +981,8 @@ def execute_program_sram(
|
|
|
before = _snapshot_bitwriter_logs(log_dir)
|
|
|
timed_out = False
|
|
|
try:
|
|
|
- tcl_cli_path = tcl_path.absolute().as_posix()
|
|
|
completed = process_runner(
|
|
|
- [str(bw_exe), tcl_cli_path],
|
|
|
+ command,
|
|
|
cwd=str(td_root / "bin"),
|
|
|
timeout=PROGRAM_TIMEOUT_SECONDS,
|
|
|
capture_output=True,
|
|
|
@@ -515,6 +998,18 @@ def execute_program_sram(
|
|
|
stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
|
|
|
stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
|
|
|
delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
|
|
|
+ residual_audit = residual_audit_runner(td_root, ownership_policy=ownership_policy)
|
|
|
+
|
|
|
+ for field in (
|
|
|
+ "post_action_audit_completed",
|
|
|
+ "post_action_discovered_processes",
|
|
|
+ "post_action_harness_owned_processes",
|
|
|
+ "post_action_blocking_processes",
|
|
|
+ "residual_processes",
|
|
|
+ "post_action_errors",
|
|
|
+ ):
|
|
|
+ cleanup[field] = residual_audit.get(field)
|
|
|
+ cleanup["status"] = "pass" if residual_audit.get("status") == "pass" else "fail"
|
|
|
|
|
|
stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
|
|
|
stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
|
|
|
@@ -533,6 +1028,8 @@ def execute_program_sram(
|
|
|
td_bin=str(td_root / "bin"),
|
|
|
)
|
|
|
authoritative_marker_signature = _marker_signature(parser_text)
|
|
|
+ if residual_audit.get("status") != "pass":
|
|
|
+ receipt["parser"]["failures"].append("post_action_process_audit_failed")
|
|
|
if not delta_bytes:
|
|
|
receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
|
|
|
receipt["parser"]["ordered_markers_complete"] = False
|