fix(tools): fail on unsaved trace, reject non-finite timeout, reset find window on malformed row, and mock geteuid

This commit is contained in:
morebrackets
2026-12-02 23:13:23 -08:00
parent 4b119cc5ca
commit df75b91442
3 changed files with 37 additions and 9 deletions

View File

@ -37,14 +37,25 @@ class TestAnalyzeMmiotrace(unittest.TestCase):
trace.write_text(
"MARK 1.0 init\n"
"R 4 1.1 1 0xc0000200 0x00000001 0x0 1\n"
"W badwidth 1.2 1 0xc0000200 0xfffffffe 0x0 1\n"
"W badwidth 1.2 1 0xc0000300 0x00000002 0x0 1\n"
"W 4 1.3 1 0xc0000200 0xfffffffe 0x0 1\n"
)
summary = mod.summarize(trace, "0000:01:00.0", 4, resource_file=res)
self.assertEqual(summary["phases"]["init"]["reads"]["PMC"], 1)
self.assertEqual(summary["phases"]["init"]["writes"]["PMC"], 1)
hits = mod.find(trace, "0000:01:00.0", "R:200 W:200:FFFFFFFE", resource_file=res)
# A malformed access between R:200 and W:200:fffffffe breaks consecutiveness.
self.assertEqual(mod.find(trace, "0000:01:00.0", "R:200 W:200:FFFFFFFE", resource_file=res), [])
# Truly consecutive accesses still match uppercase patterns cleanly.
trace_ok = td_path / "trace_ok.txt"
trace_ok.write_text(
"MARK 1.0 init\n"
"W badwidth 1.05 1 0xc0000300 0x00000002 0x0 1\n"
"R 4 1.1 1 0xc0000200 0x00000001 0x0 1\n"
"W 4 1.3 1 0xc0000200 0xfffffffe 0x0 1\n"
)
hits = mod.find(trace_ok, "0000:01:00.0", "R:200 W:200:FFFFFFFE", resource_file=res)
self.assertEqual(len(hits), 1)
self.assertEqual(hits[0]["values"], ["00000001", "fffffffe"])
@ -156,8 +167,9 @@ class TestCaptureOriginalInitKernel(unittest.TestCase):
self.assertIsNone(mod.live_identity(999_999_999))
with self.assertRaises(SystemExit):
mod.main(["--pid", "0", "--output", "/tmp/unused"])
with self.assertRaises(SystemExit):
mod.main(["--pid", str(os.getpid()), "--output", "/tmp/unused", "--timeout", "0"])
for bad_timeout in ("0", "nan", "inf", "-inf"):
with self.assertRaises(SystemExit):
mod.main(["--pid", str(os.getpid()), "--output", "/tmp/unused", "--timeout", bad_timeout])
def test_cleanup_disables_all_probes_before_removal_on_trace_and_disable_errors(self) -> None:
from unittest import mock
@ -197,6 +209,7 @@ class TestCaptureOriginalInitKernel(unittest.TestCase):
ops.append(("remove", cmd.split("/")[-1]))
with (
mock.patch.object(mod.os, "geteuid", return_value=0),
mock.patch.object(mod, "TRACE_ROOT", trace_root),
mock.patch.object(mod, "KALLSYMS_PATH", kallsyms),
mock.patch.object(mod, "bindings", return_value={}),
@ -204,14 +217,16 @@ class TestCaptureOriginalInitKernel(unittest.TestCase):
mock.patch.object(mod, "event_command", side_effect=fake_event_cmd),
):
# Do NOT create instance/trace so reading trace raises OSError.
mod.main(["--pid", str(os.getpid()), "--output", str(out_dir), "--timeout", "5"])
rc = mod.main(["--pid", str(os.getpid()), "--output", str(out_dir), "--timeout", "5"])
self.assertEqual(rc, 1)
# Every probe must be disabled (attempting e01 even after e00 fails) before any removal.
self.assertEqual(
ops,
[("disable", "e00"), ("disable", "e01"), ("remove", "e00"), ("remove", "e01")],
)
report = json.loads((out_dir / "kernel-capture.json").read_text())
self.assertFalse(report["trace_saved"])
cleanups = [e.get("cleanup") for e in report["errors"]]
self.assertIn("read_trace", cleanups)
self.assertIn("disable:e00", cleanups)

View File

@ -82,12 +82,16 @@ def parse(path, ranges):
if fields[0] == "MARK":
phase = " ".join(fields[2:])
yield phase, "MARK", None, None, None, None
elif fields[0] in ("R", "W") and len(fields) >= 6:
elif fields[0] in ("R", "W"):
if len(fields) < 6:
yield phase, "MALFORMED", None, None, None, None
continue
try:
width = int(fields[1])
address = int(fields[4], 16)
value = int(fields[5], 16)
except ValueError:
yield phase, "MALFORMED", None, None, None, None
continue
for index, start, end in ranges:
if start <= address <= end:
@ -99,6 +103,8 @@ def summarize(path, pci, first_writes, *, resource_file=None):
ranges = bars(pci, resource_file=resource_file)
phases = OrderedDict()
for phase, kind, bar, offset, _width, value in parse(path, ranges):
if kind == "MALFORMED":
continue
entry = phases.setdefault(phase, {"reads": Counter(), "writes": Counter(),
"write_order": [], "first_writes": OrderedDict(),
"other_bars": Counter()})
@ -136,6 +142,9 @@ def find(path, pci, pattern, *, resource_file=None):
raise SystemExit("empty --find pattern")
window, hits, position = [], [], 0
for phase, kind, bar, offset, _width, value in parse(path, bars(pci, resource_file=resource_file)):
if kind == "MALFORMED":
window.clear()
continue
if kind == "MARK" or bar != 0:
continue
window.append((kind, offset, value, phase, position))

View File

@ -3,6 +3,7 @@
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import time
@ -84,8 +85,8 @@ def main(argv=None):
a = p.parse_args(argv)
if a.pid <= 0:
p.error('--pid must be positive')
if a.timeout <= 0:
p.error('--timeout must be positive')
if not math.isfinite(a.timeout) or a.timeout <= 0:
p.error('--timeout must be a finite positive number')
if os.geteuid() != 0:
raise SystemExit('run as root')
identity = live_identity(a.pid)
@ -101,6 +102,7 @@ def main(argv=None):
errors = []
registered = []
created = False
trace_saved = False
version_path = Path('/proc/driver/nvidia/version')
try:
@ -183,6 +185,7 @@ def main(argv=None):
(out / 'kernel-trace.txt').write_bytes(trace)
report['trace_sha256'] = hashlib.sha256(trace).hexdigest()
report['trace_bytes'] = len(trace)
trace_saved = True
report['per_cpu_stats'] = {
p.parent.name: p.read_text()
for p in (instance / 'per_cpu').glob('cpu*/stats')
@ -211,12 +214,13 @@ def main(argv=None):
except OSError as e:
errors.append({'cleanup': 'verify_kprobe_events', 'error': str(e)})
report['probes_removed'] = False
report['trace_saved'] = trace_saved
report['instance_removed'] = not instance.exists()
report['bindings_after'] = bindings()
report['clock_after'] = {'monotonic_ns': time.monotonic_ns(), 'realtime_ns': time.time_ns()}
(out / 'kernel-capture.json').write_text(json.dumps(report, indent=2) + '\n')
print('CLOSED', report['probes_removed'], report['instance_removed'], flush=True)
return 0 if 'failure' not in report and report['probes_removed'] and report['instance_removed'] else 1
return 0 if 'failure' not in report and report['trace_saved'] and report['probes_removed'] and report['instance_removed'] else 1
if __name__ == '__main__':