Files
nvdriver/tools/summarize_native_hello.py
morebrackets 4b119cc5ca Address Greptile findings on #258
- tools/summarize_native_hello.py (4777570792): validate stdout 'text' and
  ioctl 'synchronous_api' field types via require_capture() before joining or
  counting so malformed captures exit cleanly with Rejected capture.
- tools/capture_original_init_kernel.py & tests/offline/test_mmiotrace_vm_and_summary_tools.py
  (4777570793): add regression tests covering malformed stdout/synchronous_api
  captures and trace-read + single-probe disable failures verifying every probe
  is disabled before removal.
2026-12-02 17:14:10 -08:00

127 lines
6.5 KiB
Python

#!/usr/bin/env python3
"""Check a retained REA acceptance-workload capture and summarize observed setup.
Observed commands include discovery/optional probes; this is not a requirement
minimizer or a replay implementation. It does not execute any target.
"""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import struct
def require_capture(condition, message):
if not condition:
raise SystemExit(f"Rejected capture: {message}")
def word(data, offset):
if not isinstance(data, str):
raise SystemExit("Rejected capture: missing hex payload in ioctl record")
try:
raw = bytes.fromhex(data)
except ValueError as error:
raise SystemExit(f"Rejected capture: invalid hex payload: {error}")
if len(raw) < offset + 4:
raise SystemExit(
f"Rejected capture: payload shorter than required offset {offset + 4} (got {len(raw)})"
)
return struct.unpack_from("<I", raw, offset)[0]
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("capture", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args(argv)
try:
capture_bytes = args.capture.read_bytes()
except OSError as error:
raise SystemExit(f"Rejected capture: cannot read {args.capture}: {error}")
try:
evidence = json.loads(capture_bytes.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise SystemExit(f"Rejected capture: unreadable JSON: {error}")
require_capture(isinstance(evidence, dict) and isinstance(evidence.get("normalized_result"), dict),
"missing normalized_result object")
result = evidence["normalized_result"]
require_capture(result.get("state") == "detached" and result.get("cleanup_error") is None,
"capture did not detach cleanly")
require_capture(result.get("messages_truncated") is False, "messages were truncated")
raw_messages = result.get("messages")
require_capture(isinstance(raw_messages, list), "missing messages list")
require_capture(all(isinstance(m, dict) and m.get("type") == "send" and isinstance(m.get("payload"), dict)
for m in raw_messages),
"unexpected message type")
messages = [message["payload"] for message in raw_messages]
require_capture(not any(any("error" in key for key in message) for message in messages),
"capture included an instrumentation error")
expected = ["cuInit", "cuDeviceGetByPCIBusId", "cuCtxCreate_v2", "cuModuleLoad",
"cuMemAlloc_v2", "cuMemsetD8_v2", "cuLaunchKernel", "cuCtxSynchronize",
"cuMemcpyDtoH_v2", "cuMemFree_v2", "cuModuleUnload", "cuCtxDestroy_v2"]
completed = [message for message in messages if message.get("kind") == "cuda_leave"]
require_capture([message.get("name") for message in completed] == expected,
"completed CUDA calls differ from the expected sequence")
require_capture(all(message.get("result") == 0 for message in completed),
"a CUDA call failed")
stdout_msgs = [message for message in messages if message.get("kind") == "stdout"]
require_capture(
all(isinstance(message.get("text", ""), str) for message in stdout_msgs),
"stdout message has non-string text field",
)
stdout = "".join(message.get("text", "") for message in stdout_msgs)
try:
workload = json.loads(stdout)
except json.JSONDecodeError as error:
raise SystemExit(f"Rejected capture: invalid workload stdout JSON: {error}")
require_capture(isinstance(workload, dict)
and workload.get("passed") is True and workload.get("verified_words") == 64,
"CUDA workload did not verify all 64 words")
require_capture(workload.get("context_destroyed") is True, "CUDA context was not destroyed")
calls = [message for message in messages if "request" in message]
require_capture(
all(
call.get("synchronous_api") is None or isinstance(call.get("synchronous_api"), str)
for call in calls
),
"ioctl call has non-string synchronous_api field",
)
allocations = [call for call in calls if call["request"] == 0xc030462b]
controls = [call for call in calls if call["request"] == 0xc020462a]
classes = Counter(word(call.get("before"), 12) for call in allocations)
commands = Counter(word(call.get("before"), 8) for call in controls)
summary = {
"evidence_id": evidence.get("evidence_id"),
"capture_sha256": hashlib.sha256(capture_bytes).hexdigest(),
"instrumentation_sha256": result.get("source_sha256"),
"captured_workload_passed": True, "observed_workload": workload,
"actual_cuda_module": [message for message in messages if message.get("kind") == "cuda_module"],
"cuda_calls": completed,
"device_ioctls": len(calls),
"ioctls_by_synchronous_api": dict(Counter(call.get("synchronous_api") or "unattributed" for call in calls)),
"resource_classes": [{"class": hex(key), "observed_allocations": count} for key, count in classes.items()],
"control_commands": [{"command": hex(key), "observed_calls": count} for key, count in commands.items()],
"device_allocations": [call for call in allocations if word(call.get("before"), 12) == 0x80],
"full_replacement_parity_proven": False,
"limits": [
"This capture runs the original proprietary driver; it is not replacement execution.",
"Observed probes include other boards and optional operations, even with CUDA visibility restricted.",
"Synchronous API labels identify intercepted calls on the same thread, not arbitrary worker causality.",
"Only libc ioctl is intercepted; zero observed ioctls does not rule out direct syscalls.",
"No GPU pushbuffer, MMIO or doorbell writes were captured by this instrumentation.",
"NV0080/NV2080 zero-size wire parameters use exact580 metadata-inferred56/4-byte capture lengths.",
"Other zero-size implicit payloads remain uncaptured; payloads are capped at4096 bytes.",
],
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(summary, indent=2) + "\n")
print(json.dumps({"device_ioctls": len(calls), "cuda_calls_passed": len(completed),
"capture_evidence_id": evidence.get("evidence_id")}))
return 0
if __name__ == "__main__":
raise SystemExit(main())