mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
tools: harden mmiotrace capture, ACR/trace analysis paths, and kernel archive preparer
This commit is contained in:
117
tests/offline/test_mmiotrace_capture_acr_and_archive_tools.py
Normal file
117
tests/offline/test_mmiotrace_capture_acr_and_archive_tools.py
Normal file
@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for capture_original_mmiotrace, analyze_acr_bootstrap,
|
||||
map_trace_segments, and prepare_kernel_archive hardening.
|
||||
"""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_module(name: str, rel_path: str):
|
||||
spec = importlib.util.spec_from_file_location(name, ROOT / rel_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec.loader is not None
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class CaptureOriginalMmiotraceTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.mod = _load_module("capture_original_mmiotrace", "tools/capture_original_mmiotrace.py")
|
||||
|
||||
def test_import_does_not_execute_cli_and_validates_args(self):
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
self.mod.main([
|
||||
"--pci", "0000:b3:00.0",
|
||||
"--confirm", "0000:b3:00.0",
|
||||
"--label", "test",
|
||||
"--buffer-mib", "0",
|
||||
])
|
||||
self.assertEqual(ctx.exception.code, 2)
|
||||
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
self.mod.main([
|
||||
"--pci", "0000:b3:00.0",
|
||||
"--confirm", "0000:b3:00.1",
|
||||
"--label", "test",
|
||||
])
|
||||
self.assertEqual(ctx.exception.code, 2)
|
||||
|
||||
def test_parse_smi_index_normalizes_extended_domain_and_rejects_malformed(self):
|
||||
stdout = "0, 00000000:B3:00.0, 0\n1, 00000000:b4:00.0, 128\n"
|
||||
self.assertEqual(self.mod._parse_smi_index(stdout, "0000:b3:00.0"), (0, 0))
|
||||
self.assertEqual(self.mod._parse_smi_index(stdout, "0000:b4:00.0"), (1, 128))
|
||||
with self.assertRaisesRegex(SystemExit, "unexpected nvidia-smi memory.used"):
|
||||
self.mod._parse_smi_index("0, 00000000:B3:00.0, [N/A]\n", "0000:b3:00.0")
|
||||
with self.assertRaisesRegex(SystemExit, "does not list"):
|
||||
self.mod._parse_smi_index(stdout, "0000:81:00.0")
|
||||
|
||||
def test_parse_workload_verified_words_handles_non_json(self):
|
||||
self.assertEqual(self.mod._parse_workload_verified_words('{"verified_words": 64}'), 64)
|
||||
self.assertIsNone(self.mod._parse_workload_verified_words("cuInit failed"))
|
||||
self.assertIsNone(self.mod._parse_workload_verified_words("[1, 2, 3]"))
|
||||
|
||||
|
||||
class AnalyzeAcrAndMapSegmentsTest(unittest.TestCase):
|
||||
def test_analyze_acr_honors_env_overrides(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fake_root = Path(tmp) / "analysis"
|
||||
fake_obj = Path(tmp) / "nv-kernel.o_binary"
|
||||
fake_obj.write_bytes(b"")
|
||||
with mock.patch.dict(os.environ, {
|
||||
"NV_RS_ANALYSIS_ROOT": str(fake_root),
|
||||
"NV_RS_RM_OBJECT": str(fake_obj),
|
||||
}):
|
||||
mod = _load_module("analyze_acr_env", "tools/analyze_acr_bootstrap.py")
|
||||
self.assertEqual(mod.ORIGINAL, fake_root)
|
||||
self.assertEqual(mod.RM_OBJECT, fake_obj)
|
||||
self.assertEqual(
|
||||
mod.SYMBOL_MAP,
|
||||
fake_root / "decompiled/kernel-rm-all/original-symbol-export-map.jsonl",
|
||||
)
|
||||
|
||||
def test_map_trace_segments_honors_env_override(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fake_root = Path(tmp) / "analysis"
|
||||
with mock.patch.dict(os.environ, {"NV_RS_ANALYSIS_ROOT": str(fake_root)}):
|
||||
mod = _load_module("map_trace_env", "tools/map_trace_segments.py")
|
||||
self.assertEqual(
|
||||
mod.SYMBOLS,
|
||||
fake_root / "decompiled/kernel-rm-all/original-symbol-export-map.jsonl",
|
||||
)
|
||||
|
||||
|
||||
class PrepareKernelArchiveHardeningTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.mod = _load_module("prepare_kernel_archive_harden", "tools/prepare_kernel_archive.py")
|
||||
|
||||
def test_missing_source_raises_file_not_found(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
self.mod.prepare(root / "missing.a", root / "out" / "kernel.a")
|
||||
|
||||
def test_creates_nested_destination_parent_directory(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
obj = root / "entry.o"
|
||||
src = root / "source.a"
|
||||
dst = root / "nested" / "dir" / "kernel.a"
|
||||
subprocess.run(["as", "-o", str(obj)], input=".text\n.globl entry\nentry: ret\n",
|
||||
text=True, check=True)
|
||||
subprocess.run(["ar", "rcs", str(src), str(obj)], check=True)
|
||||
self.mod.prepare(src, dst)
|
||||
self.assertTrue(dst.is_file())
|
||||
self.assertEqual(dst.read_bytes(), src.read_bytes())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -31,14 +31,37 @@ existing_rust, external_knowledge and inference. Nothing here touches a GPU.
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ORIGINAL = Path("/home/geodd/nvidia-driver/analysis-580.178.04")
|
||||
RM_OBJECT = ORIGINAL / "extracted/kernel/nvidia/nv-kernel.o_binary"
|
||||
|
||||
|
||||
def _resolve_analysis_root() -> Path:
|
||||
env = os.environ.get("NV_RS_ANALYSIS_ROOT")
|
||||
if env:
|
||||
return Path(env)
|
||||
return Path("/home/geodd/nvidia-driver/analysis-580.178.04")
|
||||
|
||||
|
||||
def _resolve_rm_object(analysis_root: Path) -> Path:
|
||||
env = os.environ.get("NV_RS_RM_OBJECT")
|
||||
if env:
|
||||
return Path(env)
|
||||
primary = analysis_root / "extracted/kernel/nvidia/nv-kernel.o_binary"
|
||||
if primary.exists():
|
||||
return primary
|
||||
fallback = Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary")
|
||||
if fallback.exists():
|
||||
return fallback
|
||||
return primary
|
||||
|
||||
|
||||
ORIGINAL = _resolve_analysis_root()
|
||||
RM_OBJECT = _resolve_rm_object(ORIGINAL)
|
||||
SYMBOL_MAP = ORIGINAL / "decompiled/kernel-rm-all/original-symbol-export-map.jsonl"
|
||||
OBJECT_SHA256 = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
||||
BAR1, BAR1_SIZE = 0x39a000000000, 0x800000000
|
||||
@ -1002,15 +1025,18 @@ def main():
|
||||
}
|
||||
text = json.dumps(report, indent=1) + "\n"
|
||||
if arguments.check:
|
||||
if not arguments.out.exists() or arguments.out.read_text() != text:
|
||||
if not arguments.out.exists() or arguments.out.read_text(encoding="utf-8") != text:
|
||||
raise SystemExit("the report is stale")
|
||||
else:
|
||||
arguments.out.write_text(text)
|
||||
arguments.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
arguments.out.write_text(text, encoding="utf-8")
|
||||
print(f"{len(steps)} steps, {len(stream_report)} Falcon loads, {len(blob_entries)} WPR entries, "
|
||||
f"{sum(check['passed'] for check in checks)}/{len(checks)} disassembly checks, "
|
||||
f"{len(problems)} problems")
|
||||
for problem in problems:
|
||||
print("problem:", problem)
|
||||
print("problem:", problem, file=sys.stderr)
|
||||
if problems:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@ -26,28 +26,8 @@ import time
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TRACING = Path("/sys/kernel/tracing")
|
||||
ORIGINAL = Path("/sys/bus/pci/drivers/nvidia")
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawTextHelpFormatter)
|
||||
parser.add_argument("--pci", required=True)
|
||||
parser.add_argument("--confirm", required=True)
|
||||
parser.add_argument("--label", required=True)
|
||||
parser.add_argument("--buffer-mib", type=int, default=1024)
|
||||
arguments = parser.parse_args()
|
||||
if os.geteuid() != 0:
|
||||
raise SystemExit("run with sudo")
|
||||
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")
|
||||
if arguments.confirm != arguments.pci:
|
||||
parser.error("--confirm must repeat --pci")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]+", arguments.label):
|
||||
parser.error("label must contain only letters, digits, underscores or hyphens")
|
||||
if Path("/sys/module/nvidia_rs").exists():
|
||||
raise SystemExit("nvidia_rs is loaded; this capture is for the original driver only")
|
||||
bdf = arguments.pci
|
||||
device = Path("/sys/bus/pci/devices") / bdf
|
||||
out = ROOT / "reports" / f"original-mmiotrace-{arguments.label}"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
trace_path = out / "mmiotrace.txt"
|
||||
BDF_RE = re.compile(r"[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]")
|
||||
LABEL_RE = re.compile(r"[A-Za-z0-9_-]+")
|
||||
|
||||
|
||||
def write(path, text):
|
||||
@ -55,121 +35,255 @@ def write(path, text):
|
||||
handle.write(text)
|
||||
|
||||
|
||||
def driver():
|
||||
def driver(device):
|
||||
link = device / "driver"
|
||||
return link.resolve().name if link.exists() else None
|
||||
|
||||
|
||||
def online_cpus():
|
||||
return Path("/sys/devices/system/cpu/online").read_text().strip()
|
||||
try:
|
||||
return Path("/sys/devices/system/cpu/online").read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def smi_index():
|
||||
rows = subprocess.run(["nvidia-smi", "--query-gpu=index,pci.bus_id,memory.used",
|
||||
"--format=csv,noheader,nounits"], capture_output=True, text=True,
|
||||
timeout=120).stdout.splitlines()
|
||||
for row in rows:
|
||||
index, bus, used = (field.strip() for field in row.split(","))
|
||||
if bus.lower().endswith(bdf):
|
||||
return int(index), int(used)
|
||||
def _normalize_smi_bdf(bus_id):
|
||||
cleaned = bus_id.strip().lower()
|
||||
if len(cleaned) == 16 and cleaned.startswith("0000") and cleaned[8] == ":":
|
||||
cleaned = cleaned[4:]
|
||||
return cleaned
|
||||
|
||||
|
||||
def _parse_smi_index(stdout, bdf):
|
||||
target = bdf.lower()
|
||||
for row in stdout.splitlines():
|
||||
parts = [field.strip() for field in row.split(",")]
|
||||
if len(parts) < 3:
|
||||
continue
|
||||
index_s, bus, used_s = parts[0], parts[1], parts[2]
|
||||
if _normalize_smi_bdf(bus) != target:
|
||||
continue
|
||||
try:
|
||||
index = int(index_s)
|
||||
except ValueError as error:
|
||||
raise SystemExit(f"unexpected nvidia-smi index for {bdf}: {index_s!r}") from error
|
||||
try:
|
||||
used = int(used_s)
|
||||
except ValueError as error:
|
||||
raise SystemExit(f"unexpected nvidia-smi memory.used for {bdf}: {used_s!r}") from error
|
||||
return index, used
|
||||
raise SystemExit(f"nvidia-smi does not list {bdf}")
|
||||
|
||||
|
||||
def _run_smi(args):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["nvidia-smi", *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
raise SystemExit(f"nvidia-smi failed: {error}") from error
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).strip()
|
||||
raise SystemExit(f"nvidia-smi exited {result.returncode}: {detail}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def smi_index(bdf):
|
||||
stdout = _run_smi([
|
||||
"--query-gpu=index,pci.bus_id,memory.used",
|
||||
"--format=csv,noheader,nounits",
|
||||
])
|
||||
return _parse_smi_index(stdout, bdf)
|
||||
|
||||
|
||||
def mark(text):
|
||||
write(TRACING / "trace_marker", text + "\n")
|
||||
|
||||
|
||||
if driver() != "nvidia":
|
||||
raise SystemExit(f"{bdf} is bound to {driver()}, not the original driver")
|
||||
index, used = smi_index()
|
||||
busy = subprocess.run(["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader"],
|
||||
capture_output=True, text=True, timeout=120).stdout.strip()
|
||||
if used != 0 or busy:
|
||||
raise SystemExit("a GPU is in use; refusing to offline CPUs under running work")
|
||||
uuid = subprocess.run(["nvidia-smi", "-i", str(index), "--query-gpu=uuid", "--format=csv,noheader"],
|
||||
capture_output=True, text=True, timeout=120).stdout.strip()
|
||||
report = {"label": arguments.label, "pci": bdf, "gpu_uuid": uuid, "kernel": os.uname().release,
|
||||
"evidence_category": "original-driver observation",
|
||||
"original_version": Path("/proc/driver/nvidia/version").read_text(),
|
||||
"cpus_online_before": online_cpus(), "steps": []}
|
||||
stop = threading.Event()
|
||||
copied = [0]
|
||||
def _parse_workload_verified_words(stdout):
|
||||
try:
|
||||
payload = json.loads(stdout)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
return payload.get("verified_words")
|
||||
|
||||
|
||||
def drain():
|
||||
with open(TRACING / "trace_pipe", "rb", buffering=0) as pipe, open(trace_path, "wb") as sink:
|
||||
os.set_blocking(pipe.fileno(), False)
|
||||
while True:
|
||||
try:
|
||||
chunk = pipe.read(1 << 20)
|
||||
except BlockingIOError:
|
||||
chunk = None
|
||||
if chunk:
|
||||
sink.write(chunk)
|
||||
copied[0] += len(chunk)
|
||||
elif stop.is_set():
|
||||
break
|
||||
else:
|
||||
time.sleep(0.05)
|
||||
def build_parser():
|
||||
parser = argparse.ArgumentParser(
|
||||
description=__doc__,
|
||||
formatter_class=argparse.RawTextHelpFormatter,
|
||||
)
|
||||
parser.add_argument("--pci", required=True)
|
||||
parser.add_argument("--confirm", required=True)
|
||||
parser.add_argument("--label", required=True)
|
||||
parser.add_argument("--buffer-mib", type=int, default=1024)
|
||||
return parser
|
||||
|
||||
|
||||
failure = None
|
||||
reader = None
|
||||
tracing = False
|
||||
try:
|
||||
write(TRACING / "buffer_size_kb", str(arguments.buffer_mib * 1024))
|
||||
write(TRACING / "current_tracer", "mmiotrace")
|
||||
tracing = True
|
||||
report["cpus_online_during"] = online_cpus()
|
||||
reader = threading.Thread(target=drain, daemon=True)
|
||||
reader.start()
|
||||
mark(f"nv_rs unbind {bdf}")
|
||||
write(ORIGINAL / "unbind", bdf)
|
||||
mark(f"nv_rs bind {bdf}")
|
||||
write(ORIGINAL / "bind", bdf)
|
||||
if driver() != "nvidia":
|
||||
raise RuntimeError("the GPU did not rebind to the original driver")
|
||||
mark("nv_rs workload start")
|
||||
def main(argv=None):
|
||||
parser = build_parser()
|
||||
arguments = parser.parse_args(argv)
|
||||
if not BDF_RE.fullmatch(arguments.pci):
|
||||
parser.error("a lowercase domain:bus:device.function is required")
|
||||
if arguments.confirm != arguments.pci:
|
||||
parser.error("--confirm must repeat --pci")
|
||||
if not LABEL_RE.fullmatch(arguments.label):
|
||||
parser.error("label must contain only letters, digits, underscores or hyphens")
|
||||
if arguments.buffer_mib <= 0:
|
||||
parser.error("--buffer-mib must be positive")
|
||||
if os.geteuid() != 0:
|
||||
raise SystemExit("run with sudo")
|
||||
if Path("/sys/module/nvidia_rs").exists():
|
||||
raise SystemExit("nvidia_rs is loaded; this capture is for the original driver only")
|
||||
|
||||
bdf = arguments.pci
|
||||
device = Path("/sys/bus/pci/devices") / bdf
|
||||
if not device.exists():
|
||||
raise SystemExit(f"PCI device {bdf} does not exist under /sys/bus/pci/devices")
|
||||
bound = driver(device)
|
||||
if bound != "nvidia":
|
||||
raise SystemExit(f"{bdf} is bound to {bound}, not the original driver")
|
||||
|
||||
workload = ROOT / "target/hardware-hello"
|
||||
started = time.time()
|
||||
result = subprocess.run([str(workload / "native-hello"),
|
||||
str(workload / "native_hello.sm70.cubin"), bdf, str(0x12F04321)],
|
||||
capture_output=True, text=True, timeout=3600)
|
||||
mark("nv_rs workload end")
|
||||
report["workload"] = {"exit_code": result.returncode, "seconds": round(time.time() - started, 1),
|
||||
"stdout": result.stdout[-4000:], "stderr": result.stderr[-4000:]}
|
||||
if result.returncode != 0 or json.loads(result.stdout).get("verified_words") != 64:
|
||||
raise RuntimeError("the native workload failed under tracing")
|
||||
# Let the driver finish its last-close teardown before the tracer stops.
|
||||
time.sleep(5)
|
||||
mark("nv_rs capture end")
|
||||
except Exception as error: # the tracer must still be turned off
|
||||
failure = str(error)
|
||||
finally:
|
||||
if tracing:
|
||||
time.sleep(1)
|
||||
stop.set()
|
||||
if reader:
|
||||
reader.join(timeout=120)
|
||||
write(TRACING / "current_tracer", "nop")
|
||||
report["cpus_online_after"] = online_cpus()
|
||||
report["driver_final"] = driver()
|
||||
report["trace_bytes"] = copied[0]
|
||||
if trace_path.exists():
|
||||
digest = hashlib.sha256()
|
||||
lines = maps = 0
|
||||
with trace_path.open("rb") as handle:
|
||||
for line in handle:
|
||||
digest.update(line)
|
||||
lines += 1
|
||||
maps += line.startswith(b"MAP ")
|
||||
report.update(trace_sha256=digest.hexdigest(), trace_lines=lines, map_records=maps)
|
||||
report["error"] = failure
|
||||
report["passed"] = (failure is None and report["driver_final"] == "nvidia"
|
||||
and report["cpus_online_after"] == report["cpus_online_before"]
|
||||
and report.get("map_records", 0) > 0)
|
||||
(out / "capture.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps({key: report.get(key) for key in (
|
||||
"passed", "error", "trace_lines", "map_records", "trace_bytes", "cpus_online_during",
|
||||
"cpus_online_after", "driver_final")}, indent=2))
|
||||
raise SystemExit(0 if report["passed"] else 1)
|
||||
hello_bin = workload / "native-hello"
|
||||
hello_cubin = workload / "native_hello.sm70.cubin"
|
||||
for artifact in (hello_bin, hello_cubin):
|
||||
if not artifact.is_file():
|
||||
raise SystemExit(f"missing workload artifact: {artifact}")
|
||||
|
||||
index, used = smi_index(bdf)
|
||||
busy = _run_smi(["--query-compute-apps=pid", "--format=csv,noheader"]).strip()
|
||||
if used != 0 or busy:
|
||||
raise SystemExit("a GPU is in use; refusing to offline CPUs under running work")
|
||||
uuid = _run_smi(["-i", str(index), "--query-gpu=uuid", "--format=csv,noheader"]).strip()
|
||||
try:
|
||||
original_version = Path("/proc/driver/nvidia/version").read_text(encoding="utf-8")
|
||||
except OSError as error:
|
||||
raise SystemExit(f"failed to read /proc/driver/nvidia/version: {error}") from error
|
||||
|
||||
out = ROOT / "reports" / f"original-mmiotrace-{arguments.label}"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
trace_path = out / "mmiotrace.txt"
|
||||
|
||||
report = {
|
||||
"label": arguments.label,
|
||||
"pci": bdf,
|
||||
"gpu_uuid": uuid,
|
||||
"kernel": os.uname().release,
|
||||
"evidence_category": "original-driver observation",
|
||||
"original_version": original_version,
|
||||
"cpus_online_before": online_cpus(),
|
||||
"steps": [],
|
||||
}
|
||||
stop = threading.Event()
|
||||
copied = [0]
|
||||
drain_error = [None]
|
||||
|
||||
def drain():
|
||||
try:
|
||||
with open(TRACING / "trace_pipe", "rb", buffering=0) as pipe, open(trace_path, "wb") as sink:
|
||||
os.set_blocking(pipe.fileno(), False)
|
||||
while True:
|
||||
try:
|
||||
chunk = pipe.read(1 << 20)
|
||||
except BlockingIOError:
|
||||
chunk = None
|
||||
if chunk:
|
||||
sink.write(chunk)
|
||||
copied[0] += len(chunk)
|
||||
elif stop.is_set():
|
||||
break
|
||||
else:
|
||||
time.sleep(0.05)
|
||||
except OSError as error:
|
||||
drain_error[0] = str(error)
|
||||
|
||||
failure = None
|
||||
reader = None
|
||||
tracing = False
|
||||
try:
|
||||
write(TRACING / "buffer_size_kb", str(arguments.buffer_mib * 1024))
|
||||
write(TRACING / "current_tracer", "mmiotrace")
|
||||
tracing = True
|
||||
report["cpus_online_during"] = online_cpus()
|
||||
reader = threading.Thread(target=drain, daemon=True)
|
||||
reader.start()
|
||||
mark(f"nv_rs unbind {bdf}")
|
||||
write(ORIGINAL / "unbind", bdf)
|
||||
mark(f"nv_rs bind {bdf}")
|
||||
write(ORIGINAL / "bind", bdf)
|
||||
if driver(device) != "nvidia":
|
||||
raise RuntimeError("the GPU did not rebind to the original driver")
|
||||
mark("nv_rs workload start")
|
||||
started = time.monotonic()
|
||||
result = subprocess.run(
|
||||
[str(hello_bin), str(hello_cubin), bdf, str(0x12F04321)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=3600,
|
||||
)
|
||||
mark("nv_rs workload end")
|
||||
report["workload"] = {
|
||||
"exit_code": result.returncode,
|
||||
"seconds": round(time.monotonic() - started, 1),
|
||||
"stdout": result.stdout[-4000:],
|
||||
"stderr": result.stderr[-4000:],
|
||||
}
|
||||
if result.returncode != 0 or _parse_workload_verified_words(result.stdout) != 64:
|
||||
raise RuntimeError("the native workload failed under tracing")
|
||||
# Let the driver finish its last-close teardown before the tracer stops.
|
||||
time.sleep(5)
|
||||
mark("nv_rs capture end")
|
||||
except Exception as error: # the tracer must still be turned off
|
||||
failure = str(error)
|
||||
finally:
|
||||
if tracing:
|
||||
time.sleep(1)
|
||||
stop.set()
|
||||
if reader:
|
||||
reader.join(timeout=120)
|
||||
try:
|
||||
write(TRACING / "current_tracer", "nop")
|
||||
except OSError as error:
|
||||
teardown_msg = f"failed to reset current_tracer to nop: {error}"
|
||||
failure = f"{failure}; {teardown_msg}" if failure else teardown_msg
|
||||
if drain_error[0]:
|
||||
drain_msg = f"trace_pipe drain failed: {drain_error[0]}"
|
||||
failure = f"{failure}; {drain_msg}" if failure else drain_msg
|
||||
|
||||
report["cpus_online_after"] = online_cpus()
|
||||
report["driver_final"] = driver(device)
|
||||
report["trace_bytes"] = copied[0]
|
||||
if trace_path.exists():
|
||||
digest = hashlib.sha256()
|
||||
lines = maps = 0
|
||||
with trace_path.open("rb") as handle:
|
||||
for line in handle:
|
||||
digest.update(line)
|
||||
lines += 1
|
||||
maps += line.startswith(b"MAP ")
|
||||
report.update(trace_sha256=digest.hexdigest(), trace_lines=lines, map_records=maps)
|
||||
report["error"] = failure
|
||||
report["passed"] = (
|
||||
failure is None
|
||||
and report["driver_final"] == "nvidia"
|
||||
and report["cpus_online_after"] == report["cpus_online_before"]
|
||||
and report.get("map_records", 0) > 0
|
||||
)
|
||||
(out / "capture.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({
|
||||
key: report.get(key) for key in (
|
||||
"passed", "error", "trace_lines", "map_records", "trace_bytes",
|
||||
"cpus_online_during", "cpus_online_after", "driver_final",
|
||||
)
|
||||
}, indent=2))
|
||||
return 0 if report["passed"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
@ -29,6 +29,7 @@ import argparse
|
||||
from collections import Counter, OrderedDict
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
@ -43,8 +44,10 @@ FULL_TRACE = ROOT / "reports/original-mmiotrace-b3-first/mmiotrace.txt"
|
||||
REPORT = ROOT / "reports/original-trace-b3-segment-map.json"
|
||||
RUST = ROOT / "src/nvidia/src"
|
||||
PACK = ROOT / "reports/gv100-firmware-pack.json"
|
||||
SYMBOLS = Path("/home/geodd/nvidia-driver/analysis-580.178.04/decompiled/kernel-rm-all/"
|
||||
"original-symbol-export-map.jsonl")
|
||||
SYMBOLS = (
|
||||
Path(os.environ.get("NV_RS_ANALYSIS_ROOT", "/home/geodd/nvidia-driver/analysis-580.178.04"))
|
||||
/ "decompiled/kernel-rm-all/original-symbol-export-map.jsonl"
|
||||
)
|
||||
FIRST_LINE = 198 # the brief says 199; line 198 is the read half of the same rewrite
|
||||
BAR1 = (0x39a000000000, 0x39a7ffffffff)
|
||||
BAR2 = (0x39a800000000, 0x39a801ffffff) # PCI resource 3
|
||||
@ -1017,7 +1020,11 @@ def main():
|
||||
if not REPORT.exists():
|
||||
print("report is missing", file=sys.stderr)
|
||||
return 1
|
||||
stored = json.loads(REPORT.read_text())
|
||||
try:
|
||||
stored = json.loads(REPORT.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
|
||||
print(f"failed to read stored report: {error}", file=sys.stderr)
|
||||
return 1
|
||||
fresh = json.loads(text)
|
||||
if stored != fresh:
|
||||
# Core sources change independently of the transcript: a moved citation is
|
||||
@ -1031,7 +1038,8 @@ def main():
|
||||
print("note: symbol citations in src/nvidia/src changed since the report was written")
|
||||
print(f"{REPORT.relative_to(ROOT)}: {len(report['segments'])} segments, up to date")
|
||||
else:
|
||||
REPORT.write_text(text)
|
||||
REPORT.parent.mkdir(parents=True, exist_ok=True)
|
||||
REPORT.write_text(text, encoding="utf-8")
|
||||
print(f"wrote {REPORT.relative_to(ROOT)}: {len(report['segments'])} segments")
|
||||
return 0
|
||||
|
||||
|
||||
@ -15,6 +15,8 @@ import tempfile
|
||||
|
||||
|
||||
def prepare(source: Path, destination: Path, ar: str = "ar", nm: str = "nm") -> None:
|
||||
if not source.is_file():
|
||||
raise FileNotFoundError(f"source archive not found: {source}")
|
||||
if source.resolve() == destination.resolve():
|
||||
raise ValueError("source and destination must differ")
|
||||
output = subprocess.check_output(
|
||||
@ -50,6 +52,7 @@ def prepare(source: Path, destination: Path, ar: str = "ar", nm: str = "nm") ->
|
||||
or members.count(member) != 1
|
||||
):
|
||||
raise ValueError(f"cannot safely omit builtin member {member}: {sorted(exports[member])}")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=destination.parent) as directory:
|
||||
temporary = Path(directory) / "kernel.a"
|
||||
shutil.copyfile(source, temporary)
|
||||
|
||||
Reference in New Issue
Block a user