mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
tools: harden mmiotrace/register/summary/kprobe and QEMU EDU runner tools
- tools/analyze_mmiotrace.py: skip malformed resource/trace lines cleanly, reject empty --find patterns (avoiding IndexError) and negative --first-writes, accept uppercase hex in --find, create output parent dirs, wrap CLI in main(). - tools/read_gpu_registers.py: check BAR0 size before mmap, handle missing sysfs driver/power_state cleanly, create output parent dirs, wrap CLI in main(). - tools/summarize_native_hello.py: validate JSON/payload hex/lengths cleanly via require_capture instead of raw KeyError/struct.error/JSONDecodeError, create output parent dirs, wrap CLI in main(). - tools/vm/run_guest.py: handle both bytes and str on TimeoutExpired, validate NV_RS_VM_RAM_MB and required VM artifacts before launch, wrap CLI in main(). - tools/vm/verify_rust_guest.py: use exact nm symbol matching for vm_rust_backing, fail cleanly on missing artifacts/rustc/RUSTFLAGS, exit with status code instead of assert (which python3 -O strips), wrap in main(). - tools/capture_original_init_kernel.py: open kprobe_events with O_APPEND, isolate trace-read errors from per-probe disable so kprobes are always disabled before removal (preventing EBUSY leaks), validate --pid/--timeout/euid without assert, guard kprobe_events verification reads, wrap in main(). - tests/offline/test_mmiotrace_vm_and_summary_tools.py: 6 offline unit tests.
This commit is contained in:
125
tests/offline/test_mmiotrace_vm_and_summary_tools.py
Normal file
125
tests/offline/test_mmiotrace_vm_and_summary_tools.py
Normal file
@ -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()
|
||||
@ -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())
|
||||
|
||||
@ -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 and not(out/'stop-kernel-trace').exists():time.sleep(.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');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())
|
||||
|
||||
@ -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('<I', bar, offset)[0]:08x}"
|
||||
finally:
|
||||
bar.close()
|
||||
os.close(descriptor)
|
||||
report = {"pci": arguments.pci, "driver": driver, "kernel": os.uname().release,
|
||||
"power_state": (device / "power_state").read_text().strip(),
|
||||
"scope": "Read-only BAR0 snapshot through sysfs under the recorded driver.",
|
||||
"inventory": values}
|
||||
text = json.dumps(report, indent=1) + "\n"
|
||||
if arguments.out:
|
||||
arguments.out.write_text(text)
|
||||
print(text, end="")
|
||||
def read_driver(device):
|
||||
try:
|
||||
return (device / "driver").resolve(strict=True).name
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def read_power_state(device):
|
||||
try:
|
||||
return (device / "power_state").read_text().strip() or None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--pci", required=True)
|
||||
parser.add_argument("--out", type=Path)
|
||||
arguments = parser.parse_args(argv)
|
||||
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 = read_driver(device)
|
||||
resource = device / "resource0"
|
||||
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(resource, error)
|
||||
try:
|
||||
bar_size = os.fstat(descriptor).st_size
|
||||
if bar_size < MIN_BAR0_SIZE:
|
||||
raise SystemExit(
|
||||
f"{resource} size {bar_size:#x} is smaller than required {MIN_BAR0_SIZE:#x}"
|
||||
)
|
||||
map_size = min(bar_size, MAX_BAR0_MAP)
|
||||
try:
|
||||
bar = mmap.mmap(descriptor, map_size, mmap.MAP_SHARED, mmap.PROT_READ)
|
||||
except (OSError, ValueError) as error:
|
||||
raise refusal(resource, error)
|
||||
except BaseException:
|
||||
os.close(descriptor)
|
||||
raise
|
||||
values = {}
|
||||
try:
|
||||
for first, count in INVENTORY:
|
||||
for index in range(count):
|
||||
offset = first + 4 * index
|
||||
values[f"{offset:06x}"] = f"{struct.unpack_from('<I', bar, offset)[0]:08x}"
|
||||
finally:
|
||||
bar.close()
|
||||
os.close(descriptor)
|
||||
report = {"pci": arguments.pci, "driver": driver, "kernel": os.uname().release,
|
||||
"power_state": read_power_state(device),
|
||||
"scope": "Read-only BAR0 snapshot through sysfs under the recorded driver.",
|
||||
"inventory": values}
|
||||
text = json.dumps(report, 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())
|
||||
|
||||
@ -16,67 +16,99 @@ def require_capture(condition, message):
|
||||
raise SystemExit(f"Rejected capture: {message}")
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("capture", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
args = parser.parse_args()
|
||||
evidence = json.loads(args.capture.read_text())
|
||||
result = evidence["normalized_result"]
|
||||
require_capture(result["state"] == "detached" and result["cleanup_error"] is None,
|
||||
"capture did not detach cleanly")
|
||||
require_capture(result["messages_truncated"] is False, "messages were truncated")
|
||||
require_capture(all(message["type"] == "send" for message in result["messages"]),
|
||||
"unexpected message type")
|
||||
messages = [message["payload"] for message in result["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["name"] for message in completed] == expected,
|
||||
"completed CUDA calls differ from the expected sequence")
|
||||
require_capture(all(message["result"] == 0 for message in completed),
|
||||
"a CUDA call failed")
|
||||
stdout = "".join(message["text"] for message in messages if message.get("kind") == "stdout")
|
||||
workload = json.loads(stdout)
|
||||
require_capture(workload["passed"] is True and workload["verified_words"] == 64,
|
||||
"CUDA workload did not verify all 64 words")
|
||||
require_capture(workload["context_destroyed"] is True, "CUDA context was not destroyed")
|
||||
calls = [message for message in messages if "request" in message]
|
||||
|
||||
|
||||
def word(data, offset):
|
||||
return struct.unpack_from("<I", bytes.fromhex(data), offset)[0]
|
||||
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]
|
||||
|
||||
|
||||
allocations = [call for call in calls if call["request"] == 0xc030462b]
|
||||
controls = [call for call in calls if call["request"] == 0xc020462a]
|
||||
classes = Counter(word(call["before"], 12) for call in allocations)
|
||||
commands = Counter(word(call["before"], 8) for call in controls)
|
||||
summary = {
|
||||
"evidence_id": evidence["evidence_id"],
|
||||
"capture_sha256": hashlib.sha256(args.capture.read_bytes()).hexdigest(),
|
||||
"instrumentation_sha256": result["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["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["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.write_text(json.dumps(summary, indent=2) + "\n")
|
||||
print(json.dumps({"device_ioctls": len(calls), "cuda_calls_passed": len(completed),
|
||||
"capture_evidence_id": evidence["evidence_id"]}))
|
||||
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 = "".join(message.get("text", "") for message in messages if message.get("kind") == "stdout")
|
||||
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]
|
||||
|
||||
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())
|
||||
|
||||
@ -1,46 +1,131 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
import subprocess,json,hashlib,re,argparse,os,pwd
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from guest_results import validate_guest_results
|
||||
parser=argparse.ArgumentParser();parser.add_argument("--iommu",action="store_true");options=parser.parse_args()
|
||||
R=Path(__file__).resolve().parents[2];O=R/'target/vm';user=pwd.getpwuid(os.getuid()).pw_name;ram_mb=os.environ.get('NV_RS_VM_RAM_MB','1024');qemu=['qemu-system-x86_64'] if os.access('/dev/kvm',os.R_OK|os.W_OK) else ['sudo','-n','-u',user,'-g','kvm','qemu-system-x86_64'];args=qemu+['-machine','q35,accel=kvm','-cpu','host','-m',ram_mb,'-smp','2','-nodefaults','-display','none','-serial','stdio','-monitor','none','-no-reboot','-nic','none','-device','edu,addr=01.0,dma_mask=4294967295','-kernel',str(O/'vmlinuz'),'-initrd',str(O/'initramfs.cpio.gz'),'-append','console=ttyS0 rdinit=/init panic=-1 nokaslr ignore_loglevel']
|
||||
if options.iommu:
|
||||
args[args.index('-append')+1]+=' intel_iommu=on iommu.strict=1'
|
||||
args+=['-device','intel-iommu,intremap=off,caching-mode=on']
|
||||
suffix='-iommu' if options.iommu else ''
|
||||
timeout=False
|
||||
validation_errors=[]
|
||||
try:
|
||||
p=subprocess.run(args,capture_output=True,text=True,timeout=90);out=p.stdout+p.stderr;code=p.returncode
|
||||
except subprocess.TimeoutExpired as e:
|
||||
timeout=True;out=(e.stdout or b'').decode(errors='replace')+(e.stderr or b'').decode(errors='replace');code=None
|
||||
except OSError as e:
|
||||
out="";code=None
|
||||
validation_errors.append(f"cannot launch EDU guest: {e}")
|
||||
|
||||
reports=R/'reports'
|
||||
reports.mkdir(exist_ok=True)
|
||||
(reports/f'vm-adapter{suffix}-serial.log').write_text(out)
|
||||
results=[]
|
||||
for match in re.findall(r'NV_RS_VM_PASS ([^\r\n]*)',out):
|
||||
try:
|
||||
result=json.loads(match)
|
||||
except json.JSONDecodeError:
|
||||
validation_errors.append("unreadable EDU guest result")
|
||||
continue
|
||||
if not isinstance(result,dict):
|
||||
validation_errors.append("EDU guest result is not a JSON object")
|
||||
continue
|
||||
results.append(result)
|
||||
validation_errors.extend(validate_guest_results(results,out,options.iommu))
|
||||
|
||||
input_hashes={}
|
||||
for artifact in (O/'vmlinuz',O/'initramfs.cpio.gz',R/'target/vm-module/nv_rs_edu_test.ko'):
|
||||
relative=str(artifact.relative_to(R))
|
||||
try:
|
||||
input_hashes[relative]=hashlib.sha256(artifact.read_bytes()).hexdigest()
|
||||
except OSError as e:
|
||||
validation_errors.append(f"cannot hash EDU guest input {relative}: {e}")
|
||||
def _decode_stream(chunk):
|
||||
if chunk is None:
|
||||
return ""
|
||||
if isinstance(chunk, bytes):
|
||||
return chunk.decode(errors="replace")
|
||||
return str(chunk)
|
||||
|
||||
d={'passed':not timeout and code==0 and not validation_errors,'validation_errors':validation_errors,'exit_code':code,'timeout':timeout,'guest_results':results,'command':args,'scope':'Real Linux PCI/MMIO/coherent-DMA/IRQ adapters and Rust-backed unpublished GV100-format page tables and coherent instance blocks in QEMU EDU, not NVIDIA hardware or CUDA parity. Production adapter sources use guest-only EDU admission macro.','inputs':input_hashes,'specification':'https://www.qemu.org/docs/master/specs/edu.html'}
|
||||
(reports/f'vm-adapter{suffix}-validation.json').write_text(json.dumps(d,indent=2)+'\n');print(json.dumps(d,indent=2));raise SystemExit(0 if d['passed'] else 1)
|
||||
|
||||
def _parse_ram_mb(raw):
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise SystemExit(f"invalid NV_RS_VM_RAM_MB={raw!r}: positive integer expected")
|
||||
if value <= 0:
|
||||
raise SystemExit(f"invalid NV_RS_VM_RAM_MB={raw!r}: positive integer expected")
|
||||
return str(value)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--iommu", action="store_true")
|
||||
options = parser.parse_args(argv)
|
||||
R = Path(__file__).resolve().parents[2]
|
||||
O = R / "target/vm"
|
||||
user = pwd.getpwuid(os.getuid()).pw_name
|
||||
ram_mb = _parse_ram_mb(os.environ.get("NV_RS_VM_RAM_MB", "1024"))
|
||||
qemu = (
|
||||
["qemu-system-x86_64"]
|
||||
if os.access("/dev/kvm", os.R_OK | os.W_OK)
|
||||
else ["sudo", "-n", "-u", user, "-g", "kvm", "qemu-system-x86_64"]
|
||||
)
|
||||
args = qemu + [
|
||||
"-machine", "q35,accel=kvm",
|
||||
"-cpu", "host",
|
||||
"-m", ram_mb,
|
||||
"-smp", "2",
|
||||
"-nodefaults",
|
||||
"-display", "none",
|
||||
"-serial", "stdio",
|
||||
"-monitor", "none",
|
||||
"-no-reboot",
|
||||
"-nic", "none",
|
||||
"-device", "edu,addr=01.0,dma_mask=4294967295",
|
||||
"-kernel", str(O / "vmlinuz"),
|
||||
"-initrd", str(O / "initramfs.cpio.gz"),
|
||||
"-append", "console=ttyS0 rdinit=/init panic=-1 nokaslr ignore_loglevel",
|
||||
]
|
||||
if options.iommu:
|
||||
args[args.index("-append") + 1] += " intel_iommu=on iommu.strict=1"
|
||||
args += ["-device", "intel-iommu,intremap=off,caching-mode=on"]
|
||||
suffix = "-iommu" if options.iommu else ""
|
||||
timeout = False
|
||||
validation_errors = []
|
||||
required_inputs = (O / "vmlinuz", O / "initramfs.cpio.gz", R / "target/vm-module/nv_rs_edu_test.ko")
|
||||
missing = [str(p.relative_to(R)) for p in required_inputs if not p.is_file()]
|
||||
if missing:
|
||||
out = ""
|
||||
code = None
|
||||
for rel in missing:
|
||||
validation_errors.append(f"missing EDU guest artifact: {rel}")
|
||||
else:
|
||||
try:
|
||||
p = subprocess.run(args, capture_output=True, text=True, timeout=90)
|
||||
out = p.stdout + p.stderr
|
||||
code = p.returncode
|
||||
except subprocess.TimeoutExpired as e:
|
||||
timeout = True
|
||||
out = _decode_stream(e.stdout) + _decode_stream(e.stderr)
|
||||
code = None
|
||||
except OSError as e:
|
||||
out = ""
|
||||
code = None
|
||||
validation_errors.append(f"cannot launch EDU guest: {e}")
|
||||
|
||||
reports = R / "reports"
|
||||
reports.mkdir(exist_ok=True)
|
||||
(reports / f"vm-adapter{suffix}-serial.log").write_text(out)
|
||||
results = []
|
||||
for match in re.findall(r"NV_RS_VM_PASS ([^\r\n]*)", out):
|
||||
try:
|
||||
result = json.loads(match)
|
||||
except json.JSONDecodeError:
|
||||
validation_errors.append("unreadable EDU guest result")
|
||||
continue
|
||||
if not isinstance(result, dict):
|
||||
validation_errors.append("EDU guest result is not a JSON object")
|
||||
continue
|
||||
results.append(result)
|
||||
validation_errors.extend(validate_guest_results(results, out, options.iommu))
|
||||
|
||||
input_hashes = {}
|
||||
for artifact in required_inputs:
|
||||
relative = str(artifact.relative_to(R))
|
||||
try:
|
||||
input_hashes[relative] = hashlib.sha256(artifact.read_bytes()).hexdigest()
|
||||
except OSError as e:
|
||||
validation_errors.append(f"cannot hash EDU guest input {relative}: {e}")
|
||||
|
||||
d = {
|
||||
"passed": not timeout and code == 0 and not validation_errors,
|
||||
"validation_errors": validation_errors,
|
||||
"exit_code": code,
|
||||
"timeout": timeout,
|
||||
"guest_results": results,
|
||||
"command": args,
|
||||
"scope": "Real Linux PCI/MMIO/coherent-DMA/IRQ adapters and Rust-backed unpublished GV100-format page tables and coherent instance blocks in QEMU EDU, not NVIDIA hardware or CUDA parity. Production adapter sources use guest-only EDU admission macro.",
|
||||
"inputs": input_hashes,
|
||||
"specification": "https://www.qemu.org/docs/master/specs/edu.html",
|
||||
}
|
||||
(reports / f"vm-adapter{suffix}-validation.json").write_text(json.dumps(d, indent=2) + "\n")
|
||||
print(json.dumps(d, indent=2))
|
||||
return 0 if d["passed"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
@ -1,24 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reject unsupported Rust module code generation before starting a guest."""
|
||||
from pathlib import Path
|
||||
import subprocess,re,json,hashlib,shutil,os
|
||||
R=Path(__file__).resolve().parents[2];O=R/'target/vm-module';obj=O/'rust_backing.o_binary';module=O/'nv_rs_edu_test.ko'
|
||||
def run(*args):return subprocess.check_output(args,text=True,env=dict(os.environ,LC_ALL='C'))
|
||||
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))
|
||||
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())
|
||||
|
||||
Reference in New Issue
Block a user