diff --git a/tests/offline/test_mmiotrace_vm_and_summary_tools.py b/tests/offline/test_mmiotrace_vm_and_summary_tools.py new file mode 100644 index 00000000..604748fa --- /dev/null +++ b/tests/offline/test_mmiotrace_vm_and_summary_tools.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Offline tests for analyze_mmiotrace, read_gpu_registers, summarize_native_hello, +run_guest, verify_rust_guest, and capture_original_init_kernel.""" +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +def load_module(name: str, rel_path: str): + path = ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class TestAnalyzeMmiotrace(unittest.TestCase): + def test_skips_corrupt_lines_and_handles_uppercase_find_and_empty_pattern(self) -> None: + mod = load_module("analyze_mmiotrace", "tools/analyze_mmiotrace.py") + with tempfile.TemporaryDirectory() as td: + td_path = Path(td) + res = td_path / "resource" + res.write_text( + "0x00000000c0000000 0x00000000c0ffffff 0x0000000000040200\n" + "corrupt line\n" + "\n" + ) + trace = td_path / "trace.txt" + 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 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) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0]["values"], ["00000001", "fffffffe"]) + + with self.assertRaises(SystemExit): + mod.find(trace, "0000:01:00.0", " ", resource_file=res) + + out_file = td_path / "nested/out.json" + rc = mod.main([str(trace), "--pci", "0000:01:00.0", "--resource-file", str(res), + "--out", str(out_file)]) + self.assertEqual(rc, 0) + self.assertTrue(out_file.is_file()) + + with self.assertRaises(SystemExit): + mod.main([str(trace), "--pci", "0000:01:00.0", "--resource-file", str(res), + "--first-writes", "-1"]) + + +class TestReadGpuRegisters(unittest.TestCase): + def test_import_safe_and_missing_sysfs_handled(self) -> None: + mod = load_module("read_gpu_registers", "tools/read_gpu_registers.py") + with tempfile.TemporaryDirectory() as td: + d = Path(td) + self.assertIsNone(mod.read_driver(d)) + self.assertIsNone(mod.read_power_state(d)) + with self.assertRaises(SystemExit) as ctx: + mod.main(["--pci", "ffff:ff:ff.0"]) + self.assertIn("does not exist", str(ctx.exception)) + + +class TestSummarizeNativeHello(unittest.TestCase): + def test_rejects_malformed_capture_and_short_hex_cleanly(self) -> None: + mod = load_module("summarize_native_hello", "tools/summarize_native_hello.py") + with self.assertRaises(SystemExit): + mod.word("abcd", 12) + with self.assertRaises(SystemExit): + mod.word("not-hex", 0) + with self.assertRaises(SystemExit): + mod.word(None, 0) + + with tempfile.TemporaryDirectory() as td: + td_path = Path(td) + bad = td_path / "bad.json" + bad.write_text("{not json") + with self.assertRaises(SystemExit) as ctx: + mod.main([str(bad), str(td_path / "out.json")]) + self.assertIn("Rejected capture", str(ctx.exception)) + + +class TestVmTools(unittest.TestCase): + def test_run_guest_helpers(self) -> None: + mod = load_module("run_guest", "tools/vm/run_guest.py") + self.assertEqual(mod._decode_stream(None), "") + self.assertEqual(mod._decode_stream(b"hello\xff"), "hello\ufffd") + self.assertEqual(mod._decode_stream("already-str"), "already-str") + self.assertEqual(mod._parse_ram_mb("1024"), "1024") + for bad in ("", "0", "-5", "abc"): + with self.assertRaises(SystemExit): + mod._parse_ram_mb(bad) + + def test_verify_rust_guest_symbol_matching(self) -> None: + mod = load_module("verify_rust_guest", "tools/vm/verify_rust_guest.py") + self.assertTrue(mod.has_defined_symbol("0000000000000000 T vm_rust_backing\n", "vm_rust_backing")) + self.assertFalse(mod.has_defined_symbol("0000000000000000 T my_vm_rust_backing_helper\n", "vm_rust_backing")) + + +class TestCaptureOriginalInitKernel(unittest.TestCase): + def test_import_safe_and_validates_args(self) -> None: + mod = load_module("capture_original_init_kernel", "tools/capture_original_init_kernel.py") + self.assertIsNotNone(mod.live_identity(os.getpid())) + 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"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/analyze_mmiotrace.py b/tools/analyze_mmiotrace.py index 3679d823..1b90910f 100644 --- a/tools/analyze_mmiotrace.py +++ b/tools/analyze_mmiotrace.py @@ -50,9 +50,18 @@ def block(offset): def bars(pci, *, resource_file=None): ranges = [] path = resource_file if resource_file is not None else Path("/sys/bus/pci/devices") / pci / "resource" - lines = path.read_text().splitlines() + try: + lines = path.read_text().splitlines() + except OSError as error: + raise SystemExit(f"cannot read PCI resource map {path}: {error}") for index, line in enumerate(lines[:6]): - start, end, _flags = (int(field, 16) for field in line.split()) + parts = line.split() + if len(parts) < 3: + continue + try: + start, end, _flags = (int(field, 16) for field in parts[:3]) + except ValueError: + continue if end > start: ranges.append((index, start, end)) return ranges @@ -61,7 +70,11 @@ def bars(pci, *, resource_file=None): def parse(path, ranges): """Yield (phase, kind, bar, offset, width, value) for accesses to the function.""" phase = "before-first-marker" - with open(path, errors="replace") as stream: + try: + stream = open(path, errors="replace") + except OSError as error: + raise SystemExit(f"cannot open trace {path}: {error}") + with stream: for line in stream: fields = line.split() if not fields: @@ -70,11 +83,15 @@ def parse(path, ranges): phase = " ".join(fields[2:]) yield phase, "MARK", None, None, None, None elif fields[0] in ("R", "W") and len(fields) >= 6: - address = int(fields[4], 16) + try: + width = int(fields[1]) + address = int(fields[4], 16) + value = int(fields[5], 16) + except ValueError: + continue for index, start, end in ranges: if start <= address <= end: - yield (phase, fields[0], index, address - start, int(fields[1]), - int(fields[5], 16)) + yield (phase, fields[0], index, address - start, width, value) break @@ -110,11 +127,13 @@ def find(path, pci, pattern, *, resource_file=None): """Positions where consecutive BAR0 accesses match tokens like r:200 or w:200:fffffffe.""" wanted = [] for token in pattern.split(): - match = re.fullmatch(r"([rw]):([0-9a-f]+)(?::([0-9a-f]+))?", token) + match = re.fullmatch(r"([rw]):([0-9a-f]+)(?::([0-9a-f]+))?", token, re.IGNORECASE) if not match: raise SystemExit(f"bad token {token}") wanted.append((match[1].upper(), int(match[2], 16), None if match[3] is None else int(match[3], 16))) + if not wanted: + 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 == "MARK" or bar != 0: @@ -131,7 +150,7 @@ def find(path, pci, pattern, *, resource_file=None): return hits -if __name__ == "__main__": +def main(argv=None): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("trace", type=Path) @@ -141,8 +160,10 @@ if __name__ == "__main__": parser.add_argument("--first-writes", type=int, default=16) parser.add_argument("--find") parser.add_argument("--out", type=Path) - arguments = parser.parse_args() - if arguments.find: + arguments = parser.parse_args(argv) + if arguments.first_writes < 0: + parser.error("--first-writes must be non-negative") + if arguments.find is not None: result = {"pattern": arguments.find, "hits": find( arguments.trace, arguments.pci, arguments.find, resource_file=arguments.resource_file, )} @@ -151,5 +172,11 @@ if __name__ == "__main__": resource_file=arguments.resource_file) text = json.dumps(result, indent=1) + "\n" if arguments.out: + arguments.out.parent.mkdir(parents=True, exist_ok=True) arguments.out.write_text(text) print(text, end="") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/capture_original_init_kernel.py b/tools/capture_original_init_kernel.py index 1f9d8c93..f0f50b35 100644 --- a/tools/capture_original_init_kernel.py +++ b/tools/capture_original_init_kernel.py @@ -1,70 +1,221 @@ #!/usr/bin/env python3 """Own a PID-scoped tracefs instance and exact NVIDIA entry probes. No rebind/reset.""" -import argparse,hashlib,json,os,re,time +import argparse +import hashlib +import json +import os from pathlib import Path -p=argparse.ArgumentParser();p.add_argument('--pid',type=int,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--timeout',type=float,default=90);a=p.parse_args();assert os.geteuid()==0 -out=a.output.resolve();out.mkdir(parents=True,exist_ok=True);base=Path('/sys/kernel/tracing');group=f'nv_rs_init_{os.getpid()}';instance=base/'instances'/group;added=[];errors=[];registered=[];created=False +import time + # GPU argument is independently verified for these original routines. Raw args # are retained as well; no unverified pointer chains or memory writes are used. -symbols=['nv_open_device','nv_close_device','rm_init_adapter','rm_shutdown_adapter','_nv000790rm','_nv031364rm','_nv030235rm','_nv030241rm','_nv033663rm','_nv033665rm','_nv033300rm','_nv033662rm','_nv033231rm','_nv033664rm','_nv033298rm','_nv033685rm','_nv055403rm','_nv028309rm','_nv028308rm','_nv043609rm','_nv027753rm','_nv027729rm','_nv017686rm','_nv017682rm','_nv016741rm','_nv016753rm','_nv016953rm','_nv028470rm','_nv043236rm','_nv043182rm','_nv043215rm','_nv027605rm','_nv029864rm','_nv028607rm'] -gpu_symbols=set(symbols)-{'nv_open_device','nv_close_device','rm_init_adapter','rm_shutdown_adapter','_nv000790rm','_nv031364rm'} -specific={ - '_nv016741rm':'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8', - '_nv016753rm':'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8', - '_nv043236rm':'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 image_bytes=+0x194(%si):u32 excluded=+0x198(%si):x32', - '_nv043182rm':'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 falcon_id=+0x608(%dx):u32 falcon_isa=+0x650(%dx):u32', - '_nv028470rm':'falcon_isa=+0x650(%si):u32 falcon_3a7=+0x3a7(%si):u8', - '_nv027605rm':'netlist_slot=+0x1c8(%si):u32', - '_nv029864rm':'netlist_slot=+0x1f8(%si):u32', - '_nv055403rm':'interval=+0x1e18(%di):u32', +SYMBOLS = [ + 'nv_open_device', 'nv_close_device', 'rm_init_adapter', 'rm_shutdown_adapter', + '_nv000790rm', '_nv031364rm', '_nv030235rm', '_nv030241rm', '_nv033663rm', + '_nv033665rm', '_nv033300rm', '_nv033662rm', '_nv033231rm', '_nv033664rm', + '_nv033298rm', '_nv033685rm', '_nv055403rm', '_nv028309rm', '_nv028308rm', + '_nv043609rm', '_nv027753rm', '_nv027729rm', '_nv017686rm', '_nv017682rm', + '_nv016741rm', '_nv016753rm', '_nv016953rm', '_nv028470rm', '_nv043236rm', + '_nv043182rm', '_nv043215rm', '_nv027605rm', '_nv029864rm', '_nv028607rm', +] +GPU_SYMBOLS = set(SYMBOLS) - { + 'nv_open_device', 'nv_close_device', 'rm_init_adapter', + 'rm_shutdown_adapter', '_nv000790rm', '_nv031364rm', } -def write(path,text): - with path.open('w')as f:f.write(text) -def event_command(command): - fd=os.open(base/'kprobe_events',os.O_WRONLY) - try:os.write(fd,(command+'\n').encode()) - finally:os.close(fd) +SPECIFIC = { + '_nv016741rm': 'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8', + '_nv016753rm': 'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8', + '_nv043236rm': 'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 image_bytes=+0x194(%si):u32 excluded=+0x198(%si):x32', + '_nv043182rm': 'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 falcon_id=+0x608(%dx):u32 falcon_isa=+0x650(%dx):u32', + '_nv028470rm': 'falcon_isa=+0x650(%si):u32 falcon_3a7=+0x3a7(%si):u8', + '_nv027605rm': 'netlist_slot=+0x1c8(%si):u32', + '_nv029864rm': 'netlist_slot=+0x1f8(%si):u32', + '_nv055403rm': 'interval=+0x1e18(%di):u32', +} + + +def write(path, text): + with path.open('w') as f: + f.write(text) + + +def event_command(base, command): + fd = os.open(base / 'kprobe_events', os.O_WRONLY | os.O_APPEND) + try: + os.write(fd, (command + '\n').encode()) + finally: + os.close(fd) + + def bindings(): - r={} - for d in Path('/sys/bus/pci/devices').iterdir(): - try: - if (d/'vendor').read_text().strip()=='0x10de'and int((d/'class').read_text(),16)>>16==3:r[d.name]=(d/'driver').resolve().name if(d/'driver').exists()else None - except OSError:pass - return r + r = {} + pci_root = Path('/sys/bus/pci/devices') + if not pci_root.is_dir(): + return r + for d in pci_root.iterdir(): + try: + if (d / 'vendor').read_text().strip() == '0x10de' and int((d / 'class').read_text(), 16) >> 16 == 3: + driver_link = d / 'driver' + r[d.name] = driver_link.resolve().name if driver_link.exists() else None + except (OSError, ValueError): + pass + return r + + def live_identity(pid): - try: - s=Path(f'/proc/{pid}/stat').read_text();return s[s.rfind(')')+2:].split()[19] - except OSError:return None -identity=live_identity(a.pid);assert identity is not None,'selected target is gone' -report={'scope':'Only selected PID and inherited threads/children through event-fork. Entry probes and declared read-only fields; no driver rebinding, GPU reset, original memory writes, or service/persistence changes. Asynchronous kernel workers not inheriting the selected PID are not covered.','pid':a.pid,'pid_starttime':identity,'probe_group':group,'bindings_before':bindings(),'clock_before':{'monotonic_ns':time.monotonic_ns(),'realtime_ns':time.time_ns()},'kernel':os.uname().release,'nvidia_version':Path('/proc/driver/nvidia/version').read_text(),'errors':errors,'registered':registered} -try: - instance.mkdir();created=True;write(instance/'tracing_on','0');write(instance/'current_tracer','nop');write(instance/'buffer_size_kb','8192');write(instance/'trace_clock','mono');write(instance/'set_event_pid',str(a.pid));write(instance/'options/event-fork','1') - available={line.split()[2]for line in Path('/proc/kallsyms').read_text().splitlines()if len(line.split())>=4 and line.split()[3]=='[nvidia]'} - for i,symbol in enumerate(symbols): - if symbol not in available:errors.append({'symbol':symbol,'error':'not in current module symbol table'});continue - name=f'e{i:02d}';fetch='arg1=%di:x64 arg2=%si:x64 arg3=%dx:x64 arg4=%cx:x64 arg5=%r8:x64 arg6=%r9:x64' - if symbol in gpu_symbols:fetch+=' gpu_id=+0xca8(%di):x32' - if symbol in specific:fetch+=' '+specific[symbol] - definition=f'p:{group}/{name} {symbol} {fetch}' - try:event_command(definition);added.append(name);registered.append({'event':name,'symbol':symbol,'definition':definition}) - except OSError as e:errors.append({'symbol':symbol,'error':str(e)});continue - write(instance/'events'/group/name/'enable','1') - assert added,'no usable probes' - write(instance/'tracing_on','1');report['ready_monotonic_ns']=time.monotonic_ns();(out/'kernel-ready.json').write_text(json.dumps(report,indent=2)+'\n');print('READY',a.pid,len(added),flush=True) - deadline=time.monotonic()+a.timeout - while live_identity(a.pid)==identity and time.monotonic()=deadline -except BaseException as e:report['failure']=repr(e);print('CAPTURE_ERROR',repr(e),flush=True) -finally: - if created: - try: - write(instance/'tracing_on','0');trace=(instance/'trace').read_bytes();(out/'kernel-trace.txt').write_bytes(trace);report['trace_sha256']=hashlib.sha256(trace).hexdigest();report['trace_bytes']=len(trace);report['per_cpu_stats']={p.parent.name:p.read_text()for p in(instance/'per_cpu').glob('cpu*/stats')} - for name in added:write(instance/'events'/group/name/'enable','0') - except OSError as e:errors.append({'cleanup':'read/disable','error':str(e)}) - for name in added: - try:event_command(f'-:{group}/{name}') - except OSError as e:errors.append({'cleanup':name,'error':str(e)}) - if created: - try:instance.rmdir() - except OSError as e:errors.append({'cleanup':'instance','error':str(e)}) - report['probes_removed']=not any(group+'/'in line for line in(base/'kprobe_events').read_text().splitlines());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) + try: + s = Path(f'/proc/{pid}/stat').read_text() + rparen = s.rfind(')') + if rparen < 0: + return None + fields = s[rparen + 2:].split() + return fields[19] if len(fields) > 19 else None + except OSError: + return None + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--pid', type=int, required=True) + p.add_argument('--output', type=Path, required=True) + p.add_argument('--timeout', type=float, default=90) + 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 os.geteuid() != 0: + raise SystemExit('run as root') + identity = live_identity(a.pid) + if identity is None: + raise SystemExit(f'selected target pid {a.pid} is gone') + + out = a.output.resolve() + out.mkdir(parents=True, exist_ok=True) + base = Path('/sys/kernel/tracing') + group = f'nv_rs_init_{os.getpid()}' + instance = base / 'instances' / group + added = [] + errors = [] + registered = [] + created = False + + version_path = Path('/proc/driver/nvidia/version') + try: + nvidia_version = version_path.read_text() + except OSError: + nvidia_version = None + + report = { + 'scope': ( + 'Only selected PID and inherited threads/children through event-fork. ' + 'Entry probes and declared read-only fields; no driver rebinding, GPU reset, ' + 'original memory writes, or service/persistence changes. Asynchronous kernel ' + 'workers not inheriting the selected PID are not covered.' + ), + 'pid': a.pid, + 'pid_starttime': identity, + 'probe_group': group, + 'bindings_before': bindings(), + 'clock_before': {'monotonic_ns': time.monotonic_ns(), 'realtime_ns': time.time_ns()}, + 'kernel': os.uname().release, + 'nvidia_version': nvidia_version, + 'errors': errors, + 'registered': registered, + } + try: + instance.mkdir() + created = True + write(instance / 'tracing_on', '0') + write(instance / 'current_tracer', 'nop') + write(instance / 'buffer_size_kb', '8192') + write(instance / 'trace_clock', 'mono') + write(instance / 'set_event_pid', str(a.pid)) + write(instance / 'options/event-fork', '1') + available = { + parts[2] + for line in Path('/proc/kallsyms').read_text().splitlines() + if len(parts := line.split()) >= 4 and parts[3] == '[nvidia]' + } + for i, symbol in enumerate(SYMBOLS): + if symbol not in available: + errors.append({'symbol': symbol, 'error': 'not in current module symbol table'}) + continue + name = f'e{i:02d}' + fetch = 'arg1=%di:x64 arg2=%si:x64 arg3=%dx:x64 arg4=%cx:x64 arg5=%r8:x64 arg6=%r9:x64' + if symbol in GPU_SYMBOLS: + fetch += ' gpu_id=+0xca8(%di):x32' + if symbol in SPECIFIC: + fetch += ' ' + SPECIFIC[symbol] + definition = f'p:{group}/{name} {symbol} {fetch}' + try: + event_command(base, definition) + added.append(name) + registered.append({'event': name, 'symbol': symbol, 'definition': definition}) + except OSError as e: + errors.append({'symbol': symbol, 'error': str(e)}) + continue + write(instance / 'events' / group / name / 'enable', '1') + if not added: + raise RuntimeError('no usable probes') + write(instance / 'tracing_on', '1') + report['ready_monotonic_ns'] = time.monotonic_ns() + (out / 'kernel-ready.json').write_text(json.dumps(report, indent=2) + '\n') + print('READY', a.pid, len(added), flush=True) + deadline = time.monotonic() + a.timeout + while live_identity(a.pid) == identity and time.monotonic() < deadline and not (out / 'stop-kernel-trace').exists(): + time.sleep(0.05) + report['target_gone'] = live_identity(a.pid) != identity + report['timeout'] = time.monotonic() >= deadline + except BaseException as e: + report['failure'] = repr(e) + print('CAPTURE_ERROR', repr(e), flush=True) + finally: + if created: + try: + write(instance / 'tracing_on', '0') + except OSError as e: + errors.append({'cleanup': 'tracing_on', 'error': str(e)}) + try: + trace = (instance / 'trace').read_bytes() + (out / 'kernel-trace.txt').write_bytes(trace) + report['trace_sha256'] = hashlib.sha256(trace).hexdigest() + report['trace_bytes'] = len(trace) + report['per_cpu_stats'] = { + p.parent.name: p.read_text() + for p in (instance / 'per_cpu').glob('cpu*/stats') + } + except OSError as e: + errors.append({'cleanup': 'read_trace', 'error': str(e)}) + # Always disable every probe independently so kprobe removal never fails with EBUSY. + for name in added: + try: + write(instance / 'events' / group / name / 'enable', '0') + except OSError as e: + errors.append({'cleanup': f'disable:{name}', 'error': str(e)}) + for name in added: + try: + event_command(base, f'-:{group}/{name}') + except OSError as e: + errors.append({'cleanup': name, 'error': str(e)}) + if created: + try: + instance.rmdir() + except OSError as e: + errors.append({'cleanup': 'instance', 'error': str(e)}) + try: + kprobes_text = (base / 'kprobe_events').read_text() + report['probes_removed'] = not any(group + '/' in line for line in kprobes_text.splitlines()) + except OSError as e: + errors.append({'cleanup': 'verify_kprobe_events', 'error': str(e)}) + report['probes_removed'] = False + 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 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/read_gpu_registers.py b/tools/read_gpu_registers.py index a3d5fdbc..9b9d9a32 100644 --- a/tools/read_gpu_registers.py +++ b/tools/read_gpu_registers.py @@ -21,15 +21,8 @@ INVENTORY = ((0x000000, 2), (0x000a00, 1), (0x000100, 2), (0x000140, 2), (0x0002 (0x009400, 1), (0x009410, 1), (0x088000, 4), (0x002004, 1), (0x002390, 16), (0x022700, 64), (0x100ce0, 1), (0x10a100, 1), (0x10a240, 1), (0x087100, 1), (0x087240, 1), (0x409100, 1), (0x409240, 1), (0x41a100, 1), (0x41a240, 1)) -parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument("--pci", required=True) -parser.add_argument("--out", type=Path) -arguments = parser.parse_args() -if not re.fullmatch(r"[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]", arguments.pci): - parser.error("a lowercase domain:bus:device.function is required") -device = Path("/sys/bus/pci/devices") / arguments.pci -driver = (device / "driver").resolve().name if (device / "driver").exists() else None -resource = device / "resource0" +MIN_BAR0_SIZE = max(first + 4 * count for first, count in INVENTORY) +MAX_BAR0_MAP = 0x1000000 LOCKDOWN = Path("/sys/kernel/security/lockdown") @@ -41,7 +34,7 @@ def lockdown_level(): return None -def refusal(error): +def refusal(resource, error): """Why a read of BAR0 was refused, and what to use instead.""" if os.geteuid() != 0 and getattr(error, "errno", None) in (errno.EPERM, errno.EACCES): return SystemExit(f"{resource}: permission denied; run this with sudo") @@ -62,31 +55,70 @@ def refusal(error): "\nDo not disable Secure Boot or relax lockdown for this baseline.") -try: - descriptor = os.open(resource, os.O_RDONLY | os.O_SYNC) -except FileNotFoundError: - raise SystemExit(f"{resource} does not exist: check --pci and that BAR0 is present") -except OSError as error: - raise refusal(error) -try: - bar = mmap.mmap(descriptor, 0x1000000, mmap.MAP_SHARED, mmap.PROT_READ) -except (OSError, ValueError) as error: - os.close(descriptor) - raise refusal(error) -values = {} -try: - for first, count in INVENTORY: - for index in range(count): - offset = first + 4 * index - values[f"{offset:06x}"] = f"{struct.unpack_from(']+)>:',line) - if m:fn=m.group(1) - m=re.search(r'sub\s+\$0x([0-9a-f]+),%rsp',line) - if m:frames[fn]=frames.get(fn,0)+int(m.group(1),16) - if re.search(r'\bpush\s',line):pushes[fn]=pushes.get(fn,0)+8 -# Conservative static accounting: reserve all fixed subtractions and pushes in -# a function. This is not a whole-call-chain stack proof; fixed prologues and -# no dynamic stack adjustment are separately checked for this guest image. -all_fns=set(frames)|set(pushes);usage={f:frames.get(f,0)+pushes.get(f,0) for f in all_fns};maximum=max(usage.values(),default=0) -dynamic=bool(re.search(r'\bsub\s+%[^,]+,%rsp',assembly)) -checks={'no_unsupported_GOT_relocations':'GOT' not in relocations,'no_SIMD_x87_registers':not re.search(r'%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))',assembly),'no_Rust_unwind_sections':not re.search(r'\.eh_frame|\.gcc_except_table',sections),'bounded_fixed_function_stack':maximum<=1024,'no_dynamic_RSP_subtraction':not dynamic,'entrypoint_present':'vm_rust_backing' in run('nm','--defined-only',str(obj))} -rustc_env=os.environ.get('RUSTC');rustup_bin=shutil.which('rustup') or (str(Path.home()/'.cargo/bin/rustup') if (Path.home()/'.cargo/bin/rustup').exists() else None) -compiler=Path(rustc_env) if rustc_env else (Path(run(rustup_bin,'which','rustc').strip()) if rustup_bin else Path(shutil.which('rustc') or str(Path.home()/'.cargo/bin/rustc'))) -flags=next(l.split('=',1)[1].strip('"') for l in (R/'tools/vm/build_guest_test.sh').read_text().splitlines() if l.startswith('RUSTFLAGS=')) -d={'passed':all(checks.values()),'checks':checks,'largest_conservative_function_stack_bytes':maximum,'fixed_frame_bytes':frames,'conservative_frame_bytes':usage,'compiler':{'path':str(compiler),'sha256':hashlib.sha256(compiler.read_bytes()).hexdigest(),'version':run(str(compiler),'-vV')},'flags':flags,'module_sha256':hashlib.sha256(module.read_bytes()).hexdigest(),'rust_object_sha256':hashlib.sha256(obj.read_bytes()).hexdigest(),'scope':'Guest-only image structure/codegen checks. Runtime success is recorded separately. Per-function bound is not a full call-chain proof.'} -(R/'reports/vm-rust-object-validation.json').write_text(json.dumps(d,indent=2)+'\n');print('Guest Rust object validation:',checks,'maxframe=',maximum);assert d['passed'] +import hashlib +import json +import os +import re +import shutil +import subprocess + +R = Path(__file__).resolve().parents[2] + + +def run(*args): + return subprocess.check_output(args, text=True, env=dict(os.environ, LC_ALL="C")) + + +def resolve_rustc(): + rustc_env = os.environ.get("RUSTC") + if rustc_env: + candidate = Path(rustc_env) + else: + rustup_bin = shutil.which("rustup") or ( + str(Path.home() / ".cargo/bin/rustup") + if (Path.home() / ".cargo/bin/rustup").exists() + else None + ) + if rustup_bin: + candidate = Path(run(rustup_bin, "which", "rustc").strip()) + else: + candidate = Path(shutil.which("rustc") or str(Path.home() / ".cargo/bin/rustc")) + if not candidate.is_file(): + raise SystemExit(f"cannot find rustc binary at {candidate}") + return candidate + + +def has_defined_symbol(nm_output, symbol): + return any( + len(parts) >= 3 and parts[-1] == symbol + for line in nm_output.splitlines() + if (parts := line.split()) + ) + + +def main(): + O = R / "target/vm-module" + obj = O / "rust_backing.o_binary" + module = O / "nv_rs_edu_test.ko" + for required in (obj, module): + if not required.is_file(): + raise SystemExit(f"missing guest build artifact: {required}") + assembly = run("objdump", "-dr", str(obj)) + relocations = run("readelf", "-Wr", str(module)) + sections = run("readelf", "-SW", str(obj)) + fn = "" + frames = {} + pushes = {} + for line in assembly.splitlines(): + m = re.search(r"<([^>]+)>:", line) + if m: + fn = m.group(1) + m = re.search(r"sub\s+\$0x([0-9a-f]+),%rsp", line) + if m: + frames[fn] = frames.get(fn, 0) + int(m.group(1), 16) + if re.search(r"\bpush\s", line): + pushes[fn] = pushes.get(fn, 0) + 8 + # Conservative static accounting: reserve all fixed subtractions and pushes in + # a function. This is not a whole-call-chain stack proof; fixed prologues and + # no dynamic stack adjustment are separately checked for this guest image. + all_fns = set(frames) | set(pushes) + usage = {f: frames.get(f, 0) + pushes.get(f, 0) for f in all_fns} + maximum = max(usage.values(), default=0) + dynamic = bool(re.search(r"\bsub\s+%[^,]+,%rsp", assembly)) + nm_output = run("nm", "--defined-only", str(obj)) + checks = { + "no_unsupported_GOT_relocations": "GOT" not in relocations, + "no_SIMD_x87_registers": not re.search(r"%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))", assembly), + "no_Rust_unwind_sections": not re.search(r"\.eh_frame|\.gcc_except_table", sections), + "bounded_fixed_function_stack": maximum <= 1024, + "no_dynamic_RSP_subtraction": not dynamic, + "entrypoint_present": has_defined_symbol(nm_output, "vm_rust_backing"), + } + compiler = resolve_rustc() + build_script = R / "tools/vm/build_guest_test.sh" + flags = next( + ( + l.split("=", 1)[1].strip('"') + for l in build_script.read_text().splitlines() + if l.startswith("RUSTFLAGS=") + ), + None, + ) + if flags is None: + raise SystemExit(f"missing RUSTFLAGS= definition in {build_script}") + d = { + "passed": all(checks.values()), + "checks": checks, + "largest_conservative_function_stack_bytes": maximum, + "fixed_frame_bytes": frames, + "conservative_frame_bytes": usage, + "compiler": { + "path": str(compiler), + "sha256": hashlib.sha256(compiler.read_bytes()).hexdigest(), + "version": run(str(compiler), "-vV"), + }, + "flags": flags, + "module_sha256": hashlib.sha256(module.read_bytes()).hexdigest(), + "rust_object_sha256": hashlib.sha256(obj.read_bytes()).hexdigest(), + "scope": "Guest-only image structure/codegen checks. Runtime success is recorded separately. Per-function bound is not a full call-chain proof.", + } + (R / "reports").mkdir(exist_ok=True) + (R / "reports/vm-rust-object-validation.json").write_text(json.dumps(d, indent=2) + "\n") + print("Guest Rust object validation:", checks, "maxframe=", maximum) + return 0 if d["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main())