Files
nvdriver/tools/summarize_original_live_init.py
morebrackets 87ed88f76e Address Greptile review findings on #276
- tools/summarize_original_live_init.py (4777565678): require an explicit
  boolean messages_truncated field in the frida_session_status record instead
  of defaulting missing values to False.
- tests/offline/test_live_control_and_summary_tools.py (4777565697): add
  mocked main() tests covering first-fd cleanup when second os.open fails,
  failed report emission when rmmod raises OSError or TimeoutExpired, and
  rejection of missing/non-bool messages_truncated.
2026-12-02 16:50:05 -08:00

128 lines
6.0 KiB
Python

#!/usr/bin/env python3
import json,re,collections,pathlib,argparse
def api_outcome(events, truncated):
"""Return false for an observed API failure, or null for incomplete evidence."""
pending = collections.Counter()
complete = not truncated
saw_return = False
for event in events:
kind = event.get("kind")
if kind not in ("cuda_enter", "cuda_leave"):
continue
call = event.get("tid"), event.get("name")
if kind == "cuda_enter":
pending[call] += 1
continue
result = event.get("result")
if type(result) is int and result != 0:
return False
saw_return = True
pending[call] -= 1
if type(result) is not int or pending[call] < 0 or None in call:
complete = False
return True if complete and saw_return and not any(pending.values()) else None
def main(argv=None):
parser = argparse.ArgumentParser(description="Summarize REA Frida phases and bounded original-driver PT observations")
parser.add_argument("report_directory", type=pathlib.Path)
args = parser.parse_args(argv)
p = args.report_directory
bundle_path = p / 'rea-evidence-bundle.json'
calls_path = p / 'overflow-aware-init-calls.txt'
for required in (bundle_path, calls_path):
if not required.is_file():
raise SystemExit(f"missing required input file: {required}")
try:
b = json.loads(bundle_path.read_text(encoding='utf-8'))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise SystemExit(f"invalid evidence bundle {bundle_path}: {error}") from error
records = b.get('records') if isinstance(b, dict) else None
if not isinstance(records, list):
raise SystemExit(f"evidence bundle missing records list: {bundle_path}")
r = next((rec for rec in records if isinstance(rec, dict) and rec.get('operation') == 'frida_session_status'), None)
if r is None:
raise SystemExit(f"evidence bundle has no frida_session_status record: {bundle_path}")
norm = r.get('normalized_result', {})
payloads = [x.get('payload', {}) for x in norm.get('messages', []) if isinstance(x, dict)]
api = [x for x in payloads if isinstance(x, dict) and x.get('kind') in ('cuda_enter', 'cuda_leave', 'stdout')]
labels = {
'_nv000790rm': 'GPU initialization parent',
'_nv030241rm': 'engine object creation parent',
'_nv043609rm': 'MC domain-4 reset',
'_nv033663rm': 'GR StateInit',
'_nv033300rm': 'GR normal-netlist decode',
'_nv033231rm': 'GR netlist consumers',
'_nv043236rm': 'LSFM client placement/WPR request registration',
'_nv043182rm': 'LSF header construction',
'_nv027605rm': 'FECS LS image construction',
'_nv029864rm': 'GPCCS LS image construction',
'_nv016741rm': 'ACR HS selection/package/WPR gather and SEC2 launch parent',
'_nv016753rm': 'ACR WPR metadata gather and shadow-copy selection',
'_nv028309rm': 'OBJFIFO StateLoad wrapper',
'_nv028308rm': 'OBJFIFO StateLoad implementation',
'_nv028470rm': 'SEC2 HS reset/VM/DMEM/IMEM/start/wait parent',
'_nv033665rm': 'GR StateLoad',
'_nv055403rm': 'FECS mailbox poll',
}
first = {}
counts = collections.Counter()
errors = collections.Counter()
events = []
barrier = 0
with calls_path.open(encoding='utf-8') as handle:
for ln, line in enumerate(handle, 1):
if 'instruction trace error' in line:
barrier += 1
k = re.search(r'code (\d+): (.*)', line)
errors[k.group(0) if k else 'unknown'] += 1
continue
m = re.search(r'(\d+\.\d+):.*? ([0-9a-f]+) (_nv\d+rm)\+[^ ]+ .*?=> ([0-9a-f]+) ([^ +]+)\+([^ ]+)', line)
if not m:
continue
t, ip, sym, addr, dest, off = m.groups()
ns = int(t.replace('.', ''))
phase = None # Recorder did not request CLOCK_MONOTONIC; do not join clock domains.
e = {
'time_perf_ns': ns,
'source_symbol': sym,
'source_ip': ip,
'destination_symbol': dest,
'destination_ip': addr,
'destination_offset': off,
'phase': phase,
'overflow_barriers_before': barrier,
'line': ln,
}
events.append(e)
counts[sym] += 1
first.setdefault(sym, e)
truncated = norm.get('messages_truncated')
if type(truncated) is not bool:
raise SystemExit('evidence bundle missing boolean messages_truncated')
result = {
'scope': 'Observed source-body callsite markers, not complete function entry list or lossless call chain. Labels are prior static interpretations, execution/timing are live observations. No GPU object/register arguments captured by PT. cuInit enumerates all eight boards; markers cannot identify a particular GPU. Driver already PCI-bound; not boot/cold-probe capture.',
'rea_evidence': [r.get('evidence_id'), 'ev_d9f5b3999e69f43b9cccb62d8a723c6c7feafe021dd09245f1ebb935c18ab963'],
'clock_correlation': 'Unverified: perf record did not explicitly select CLOCK_MONOTONIC; no timestamp join to Frida CLOCK_MONOTONIC was performed.',
'api_events': api,
'api_success': api_outcome(api, truncated),
'messages_truncated': truncated,
'markers': [dict(e, label=labels.get(sym), observed_source_callsites=counts[sym]) for sym, e in first.items()],
'errors': dict(errors),
'capture_size_limited': True,
'decoded_to_source_eof': True,
'decode_report': 'overflow-aware-init-calls.json',
'events': events,
}
(p / 'live-initialization-timeline.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
for x in result['markers']:
print(x['time_perf_ns'], x['source_symbol'], x['label'], x['phase'])
print('errors', dict(errors), 'events', len(events))
return 0
if __name__ == '__main__':
raise SystemExit(main())