tools: harden capture_stock/replay_live, run_native_hello, and bringup_verdict

- tools/ioctl_capture/capture_stock.sh: strictly validate lowercase PCI BDF and sysfs existence, pass BDF via positional arg to sh -c (no shell interpolation), reject path traversal and missing commands in run, link shim with -pthread, create nested output dirs lazily, propagate workload exit code instead of always returning 0, check dev_reload.sh status, and clean all /dev/nvidia[0-9]* nodes on restore.
- tools/ioctl_capture/replay_live.sh: reject unknown CLI flags (exit 2) and verify captures/golden/stock-620.73.04.json exists before running.
- tools/run_native_hello.py: wrap CLI in main(), handle unbound PCI devices cleanly in binding(), verify binary/cubin and libcuda.so.1 ldd resolution, and catch missing trace/strace/invalid JSON stdout cleanly.
- tools/bringup_verdict.py: validate 32-bit hex note values instead of crashing with ValueError, and reject 0xffffffff PCIe bus-error readbacks in sec2_stop and block_1704_after_bind.
- tests/offline/test_capture_hello_and_verdict_tools.py: 8 offline unit tests covering all 4 tools.
This commit is contained in:
morebrackets
2026-12-02 02:36:28 -08:00
parent db720ba4a6
commit 09029607c1
5 changed files with 317 additions and 85 deletions

View File

@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Offline unit tests for capture_stock.sh, replay_live.sh, run_native_hello.py, and bringup_verdict.py."""
from __future__ import annotations
import importlib.util
import os
from pathlib import Path
import subprocess
import sys
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 TestBringupVerdict(unittest.TestCase):
def test_builtin_check_passes(self) -> None:
res = subprocess.run(
[sys.executable, str(ROOT / "tools/bringup_verdict.py"), "--check"],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(res.returncode, 0, res.stderr + res.stdout)
self.assertIn("cases passed", res.stdout)
def test_malformed_and_bus_error_values(self) -> None:
mod = load_module("bringup_verdict", "tools/bringup_verdict.py")
self.assertEqual(mod.outcome({"stage": None}, mod.ACR_COMPLETED), "invalid")
self.assertEqual(mod.outcome({"stage": "-1"}, mod.ACR_COMPLETED), "invalid")
self.assertEqual(mod.outcome({"stage": "100000000"}, mod.ACR_COMPLETED), "invalid")
self.assertEqual(mod.outcome({"stage": "00080000"}, mod.ACR_COMPLETED), "completed")
class TestRunNativeHello(unittest.TestCase):
def test_import_has_no_side_effects_and_helpers_handle_missing(self) -> None:
mod = load_module("run_native_hello", "tools/run_native_hello.py")
with tempfile.TemporaryDirectory() as td:
self.assertIsNone(mod.binding(Path(td)))
self.assertIsNone(mod.resolve_libcuda("\tlibc.so.6 => /lib/x86_64-linux-gnu/libc.so.6\n"))
self.assertIsNone(mod.resolve_libcuda("\tlibcuda.so.1 => not found\n"))
def test_main_refuses_unbound_device_cleanly(self) -> None:
mod = load_module("run_native_hello", "tools/run_native_hello.py")
with self.assertRaises(SystemExit) as ctx:
mod.main(["--pci", "ffff:ff:ff.0", "--expect-pci-driver", "nvidia_rs", "--label", "test"])
self.assertIn("refusing mismatched PCI driver: None", str(ctx.exception))
class TestCaptureAndReplayScripts(unittest.TestCase):
def test_shell_syntax_clean(self) -> None:
for script in ("tools/ioctl_capture/capture_stock.sh", "tools/ioctl_capture/replay_live.sh"):
res = subprocess.run(["sh", "-n", str(ROOT / script)], capture_output=True, text=True)
self.assertEqual(res.returncode, 0, f"{script}: {res.stderr}")
def test_capture_stock_rejects_bad_bdf_and_path_traversal(self) -> None:
script = str(ROOT / "tools/ioctl_capture/capture_stock.sh")
for bad_bdf in ("", "0000:01:00.0;id", "0000:01:00.8", "0000:01:00.A", "ffff:ff:ff.0"):
env = {**os.environ, "NV_RS_CAPTURE_BDF": bad_bdf}
res = subprocess.run(["sh", script, "swap"], env=env, capture_output=True, text=True)
self.assertEqual(res.returncode, 2, f"bdf={bad_bdf!r}: {res.stdout}{res.stderr}")
for bad_name in ("../escape", "/abs", "a/../b", "bad name", "trailing/"):
res = subprocess.run(["sh", script, "run", bad_name, "--", "true"], capture_output=True, text=True)
self.assertEqual(res.returncode, 2, f"name={bad_name!r}: {res.stdout}{res.stderr}")
res_nocmd = subprocess.run(["sh", script, "run", "okname", "--"], capture_output=True, text=True)
self.assertEqual(res_nocmd.returncode, 2, res_nocmd.stdout + res_nocmd.stderr)
res_extra = subprocess.run(["sh", script, "restore", "extra"], capture_output=True, text=True)
self.assertEqual(res_extra.returncode, 2, res_extra.stdout + res_extra.stderr)
def test_capture_stock_run_propagates_exit_code_and_creates_subdir(self) -> None:
script = str(ROOT / "tools/ioctl_capture/capture_stock.sh")
with tempfile.TemporaryDirectory() as td:
# Run inside a temporary copy layout so repo captures/ stays clean.
tmp_root = Path(td)
(tmp_root / "tools/ioctl_capture").mkdir(parents=True)
for name in ("capture_stock.sh", "nv_ioctl_capture.c"):
(tmp_root / "tools/ioctl_capture" / name).write_text(
(ROOT / "tools/ioctl_capture" / name).read_text()
)
tmp_script = str(tmp_root / "tools/ioctl_capture/capture_stock.sh")
ok = subprocess.run(
["sh", tmp_script, "run", "sub/ok_case", "--", "sh", "-c", "echo hi"],
capture_output=True,
text=True,
)
self.assertEqual(ok.returncode, 0, ok.stdout + ok.stderr)
self.assertTrue((tmp_root / "captures/sub/ok_case.jsonl").is_file())
self.assertEqual((tmp_root / "captures/sub/ok_case.stdout").read_text(), "hi\n")
fail = subprocess.run(
["sh", tmp_script, "run", "sub/fail_case", "--", "sh", "-c", "exit 7"],
capture_output=True,
text=True,
)
self.assertEqual(fail.returncode, 7, fail.stdout + fail.stderr)
self.assertIn("exit=7", fail.stdout)
def test_replay_live_rejects_unknown_flags_and_missing_golden(self) -> None:
script = str(ROOT / "tools/ioctl_capture/replay_live.sh")
res = subprocess.run(["sh", script, "--bogus"], capture_output=True, text=True)
self.assertEqual(res.returncode, 2, res.stdout + res.stderr)
res2 = subprocess.run(["sh", script, "--update", "extra"], capture_output=True, text=True)
self.assertEqual(res2.returncode, 2, res2.stdout + res2.stderr)
with tempfile.TemporaryDirectory() as td:
tmp_root = Path(td)
(tmp_root / "tools/ioctl_capture").mkdir(parents=True)
(tmp_root / "tools/ioctl_capture/replay_live.sh").write_text(
(ROOT / "tools/ioctl_capture/replay_live.sh").read_text()
)
res3 = subprocess.run(
["sh", str(tmp_root / "tools/ioctl_capture/replay_live.sh")],
capture_output=True,
text=True,
)
self.assertEqual(res3.returncode, 2, res3.stdout + res3.stderr)
self.assertIn("missing golden capture", res3.stderr)
if __name__ == "__main__":
unittest.main()

View File

@ -15,6 +15,7 @@ got as far as its gate; cleanup bits that are absent or incomplete after any reg
the level; system memory that was kept or leaked; a SEC2 that a failed load left neither
halted nor confirmed stopped.
"""
import re
import sys
ACR_COMPLETED, ACR_UNLOAD_ONLY = 0x00080000, 0x00080001
@ -22,13 +23,27 @@ PMU_COMPLETED = 0x00090000
STAGE_WORDS = {0xffff0002: "refused", 0xffff0003: "not run", 0xffff0004: "failed",
ACR_UNLOAD_ONLY: "unload only"}
ACR_CLEANUP, PMU_CLEANUP = "00000007", "0000003f"
BUS_ERROR_WORD = 0xffffffff
_HEX32_RE = re.compile(r"^(?:0[xX])?[0-9a-fA-F]{1,8}$")
def _parse_hex32(value):
"""Parse an unsigned 32-bit hex note string, or return None if malformed."""
if not isinstance(value, str):
return None
stripped = value.strip()
if not _HEX32_RE.fullmatch(stripped):
return None
return int(stripped, 16)
def outcome(notes, completed):
"""`completed`, `refused`, `not run`, `failed`, `unload only`, `missing` or `unknown`."""
"""`completed`, `refused`, `not run`, `failed`, `unload only`, `missing`, `invalid` or `unknown`."""
if not notes or "stage" not in notes:
return "missing"
stage = int(notes["stage"], 16)
stage = _parse_hex32(notes["stage"])
if stage is None:
return "invalid"
if stage == completed:
return "completed"
return STAGE_WORDS.get(stage, "unknown")
@ -70,9 +85,11 @@ def failures(level, acr, pmu, regions_cleared_after_unload):
if "system_memory_leaked" in acr:
found.append(f"LEVEL 8: SYSTEM MEMORY LEFT ALLOCATED ({acr['system_memory_leaked']}: "
"bit 0 image, bit 1 flush page, bit 2 DMA context with its PCI reference)")
if "sec2_stop" in acr and int(acr["sec2_stop"], 16) & 5 != 5:
found.append(f"LEVEL 8: SEC2 NOT CONFIRMED STOPPED AFTER A FAILED LOAD "
f"(sec2_stop {acr['sec2_stop']})")
if "sec2_stop" in acr:
sec2_stop = _parse_hex32(acr["sec2_stop"])
if sec2_stop is None or sec2_stop == BUS_ERROR_WORD or (sec2_stop & 5) != 5:
found.append(f"LEVEL 8: SEC2 NOT CONFIRMED STOPPED AFTER A FAILED LOAD "
f"(sec2_stop {acr['sec2_stop']})")
if level >= 9:
result = outcome(pmu, PMU_COMPLETED)
if result != "completed":
@ -120,10 +137,12 @@ def bar1_failures(requested, bar1):
if bar1.get("init_status") != "00000000":
found.append(f"BAR1: BRING-UP STATUS {bar1.get('init_status')}")
block = bar1.get("block_1704_after_bind")
if block is None or not int(block, 16) & 0x80000000:
block_val = _parse_hex32(block)
if block_val is None or block_val == BUS_ERROR_WORD or not (block_val & 0x80000000):
found.append(f"BAR1: 0x1704 AFTER THE BIND IS {block}")
status = bar1.get("bind_status_1710")
if status is None or int(status, 16) & 3:
status_val = _parse_hex32(status)
if status_val is None or (status_val & 3):
found.append(f"BAR1: BIND STATUS 0x1710 IS {status}")
if bar1.get("written_through_bar1_read_through_bar2") != BAR1_WORD_BAR1:
found.append("BAR1: THE WORD WRITTEN THROUGH BAR1 WAS NOT READ THROUGH BAR2 "
@ -135,7 +154,8 @@ def bar1_failures(requested, bar1):
if bar1.get(name) != "00000000":
found.append(f"BAR1: {name.upper()} IS {bar1.get(name)}")
after = bar1.get("block_1704_after_unbind")
if after is None or int(after, 16) & 0x80000000:
after_val = _parse_hex32(after)
if after_val is None or (after_val & 0x80000000):
found.append(f"BAR1: 0x1704 AFTER THE UNBIND IS {after} (BAR1 MAY STILL BE BOUND TO "
"A DESTROYED ADDRESS SPACE)")
return found
@ -177,6 +197,11 @@ def check():
"bind_status_1710": "00000001", "block_1704_after_unbind": "007fffa0"}, 7),
("still bound afterwards", True,
{**good_bar1, "result": "00000005", "block_1704_after_unbind": "807fffa0"}, 2),
("bus error readback on 0x1704 after bind", True,
{**good_bar1, "block_1704_after_bind": "ffffffff"}, 1),
("malformed hex notes fail instead of raising", True,
{**good_bar1, "block_1704_after_bind": "not-hex",
"bind_status_1710": "zzzz", "block_1704_after_unbind": "100000000"}, 3),
]
for name, requested, notes, expected in bar1_cases:
found = bar1_failures(requested, notes)
@ -235,11 +260,17 @@ def check():
("level 9 out of budget", 9, good_acr,
{**good_pmu, "stage": "ffff0004", "start_budget_spent_before_step": "00000008"},
True, 2),
("malformed stage fails cleanly", 8, {**good_acr, "stage": "not-hex"}, {}, True, 1),
("bus error sec2_stop is not treated as stopped", 8,
{**good_acr, "sec2_stop": "ffffffff"}, {}, True, 1),
("malformed sec2_stop fails cleanly", 8,
{**good_acr, "sec2_stop": "xyz"}, {}, True, 1),
]
for name, level, acr, pmu, cleared, expected in cases:
found = failures(level, acr, pmu, cleared)
assert len(found) == expected, (name, found)
assert outcome({"stage": "12345678"}, ACR_COMPLETED) == "unknown"
assert outcome({"stage": "not-hex"}, ACR_COMPLETED) == "invalid"
print(f"bringup verdict: {len(cases) + len(bar1_cases)} cases passed")

View File

@ -12,7 +12,6 @@ set -u
cd "$(dirname "$0")/../.." || exit 2
STOCK_SRC=${STOCK_SRC:-$(pwd)/../nvidia-open-620.73.04/kernel-open}
SHIM_DIR=captures/.build
mkdir -p captures "$SHIM_DIR"
bounded() { # bounded SECONDS CMD...: run, report and fail if it does not return in time
t=$1; shift
@ -29,12 +28,14 @@ bounded() { # bounded SECONDS CMD...: run, report and fail if it does not return
case "${1:-}" in
swap)
[ "$#" -eq 1 ] || { echo "usage: $0 swap"; exit 2; }
# Opt-in: the swap unbinds a GPU from nvidia_rs and loads the stock modules. Name the one device.
CAPTURE_BDF=${NV_RS_CAPTURE_BDF:-}
case "$CAPTURE_BDF" in
*:*:*.*) ;;
*) echo "refusing: set NV_RS_CAPTURE_BDF=<domain:bus:dev.fn> (the one GPU the swap may unbind)"; exit 2 ;;
[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f].[0-7]) ;;
*) echo "refusing: set NV_RS_CAPTURE_BDF=<domain:bus:dev.fn> (lowercase hex, the one GPU the swap may unbind)"; exit 2 ;;
esac
[ -d "/sys/bus/pci/devices/$CAPTURE_BDF" ] || { echo "refusing: PCI device $CAPTURE_BDF does not exist"; exit 2; }
for d in /sys/bus/pci/drivers/nvidia_rs/*:*:*.*; do
[ -e "$d" ] || continue
[ "${d##*/}" = "$CAPTURE_BDF" ] || { echo "refusing: nvidia_rs is also bound to ${d##*/}"; exit 2; }
@ -46,7 +47,7 @@ swap)
sudo systemctl stop nvidia-persistenced 2>/dev/null
for d in /sys/bus/pci/drivers/nvidia_rs/*:*:*.*; do
[ -e "$d" ] || continue
bounded 60 sh -c "echo ${d##*/} | sudo tee /sys/bus/pci/drivers/nvidia_rs/unbind >/dev/null" || exit 1
bounded 60 sh -c 'printf "%s\n" "$1" | sudo tee /sys/bus/pci/drivers/nvidia_rs/unbind >/dev/null' _ "${d##*/}" || exit 1
done
for m in nvidia_rs nvidia_uvm nvidia; do
[ -e "/sys/module/$m" ] || continue
@ -58,27 +59,48 @@ swap)
ls -l /dev/nvidia* && cat /proc/driver/nvidia/version
;;
run)
name=${2:?capture name}; shift 2
[ "$#" -ge 2 ] || { echo "usage: $0 run NAME -- CMD..."; exit 2; }
name=$2; shift 2
[ "${1:-}" = "--" ] && shift
gcc -shared -fPIC -O1 -o "$SHIM_DIR/nv_ioctl_capture.so" tools/ioctl_capture/nv_ioctl_capture.c -ldl || exit 2
case "$name" in
""|/*|*/|..|../*|*/..|*/../*|*[![:alnum:]._/-]*)
echo "invalid capture name: $name"; exit 2 ;;
esac
[ "$#" -gt 0 ] || { echo "missing command for capture '$name'"; exit 2; }
mkdir -p captures "$SHIM_DIR"
gcc -shared -fPIC -O1 -pthread -o "$SHIM_DIR/nv_ioctl_capture.so" tools/ioctl_capture/nv_ioctl_capture.c -ldl || exit 2
out=captures/$name.jsonl
mkdir -p "$(dirname "$out")"
: > "$out"
# CAPTURE_SUDO=sudo is needed against nvidia_rs when dev mode makes the nodes root-only.
${CAPTURE_SUDO:-} env NV_CAPTURE_OUT="$(pwd)/$out" LD_PRELOAD="$(pwd)/$SHIM_DIR/nv_ioctl_capture.so" timeout -k 5 120 "$@" \
> "captures/$name.stdout" 2> "captures/$name.stderr"
echo "exit=$? records=$(wc -l < "$out")"
rc=$?
echo "exit=$rc records=$(wc -l < "$out")"
exit "$rc"
;;
restore)
[ "$#" -eq 1 ] || { echo "usage: $0 restore"; exit 2; }
if [ -n "${NV_RS_CAPTURE_BDF:-}" ]; then
case "$NV_RS_CAPTURE_BDF" in
[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f].[0-7]) ;;
*) echo "refusing: invalid NV_RS_CAPTURE_BDF=$NV_RS_CAPTURE_BDF"; exit 2 ;;
esac
fi
sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches; echo 1 > /proc/sys/vm/compact_memory'
for m in nvidia_uvm nvidia; do
[ -e "/sys/module/$m" ] || continue
bounded 120 sudo rmmod "$m" || exit 1
done
# nvidia-modprobe made real nodes (major != nvidia_rs's misc 10) that would shadow our symlinks.
sudo rm -f /dev/nvidia-uvm /dev/nvidia-uvm-tools /dev/nvidia0 /dev/nvidiactl
sudo rm -f /dev/nvidia-uvm /dev/nvidia-uvm-tools /dev/nvidiactl
for n in /dev/nvidia[0-9]*; do
[ -e "$n" ] || [ -L "$n" ] || continue
sudo rm -f "$n"
done
# Reloading nvidia_rs needs tools/dev_reload.sh (development-mode tooling, separate PR).
if [ -f tools/dev_reload.sh ]; then
NV_RS_DEV_RELOAD_BDF=${NV_RS_CAPTURE_BDF:-} sh tools/dev_reload.sh
NV_RS_DEV_RELOAD_BDF=${NV_RS_CAPTURE_BDF:-} sh tools/dev_reload.sh || exit 1
else
echo "stock modules unloaded; load nvidia_rs yourself (tools/dev_reload.sh is not in this tree)"
fi

View File

@ -9,10 +9,26 @@
# like any CUDA program; it never swaps drivers.
set -u
cd "$(dirname "$0")/../.." || exit 2
UPDATE=
case "$#" in
0) ;;
1)
if [ "$1" = "--update" ]; then
UPDATE=--update-baseline
else
echo "usage: $0 [--update]" >&2
exit 2
fi
;;
*)
echo "usage: $0 [--update]" >&2
exit 2
;;
esac
GOLDEN=captures/golden/stock-620.73.04.json
[ -f "$GOLDEN" ] || { echo "missing golden capture: $GOLDEN" >&2; exit 2; }
[ ! -f tools/dev_health.sh ] || sh tools/dev_health.sh pre >/dev/null 2>&1 || { echo "dev_health pre failed; not replaying"; exit 1; }
[ -d /sys/module/nvidia_rs ] || { echo "nvidia_rs is not loaded"; exit 1; }
UPDATE=
[ "${1:-}" = "--update" ] && UPDATE=--update-baseline
mkdir -p captures/ours captures/baseline
rc=0
for w in nvidia-smi-L:"nvidia-smi -L" nvidia-smi:"nvidia-smi" cuda-basic:"python3 tools/ioctl_capture/cuda_basic.py"; do
@ -20,7 +36,7 @@ for w in nvidia-smi-L:"nvidia-smi -L" nvidia-smi:"nvidia-smi" cuda-basic:"python
cmd=${w#*:}
# shellcheck disable=SC2086
CAPTURE_SUDO=sudo sh tools/ioctl_capture/capture_stock.sh run "ours/$name" -- $cmd >/dev/null || rc=1
python3 tools/ioctl_capture/replay_diff.py diff captures/golden/stock-620.73.04.json "$name" \
python3 tools/ioctl_capture/replay_diff.py diff "$GOLDEN" "$name" \
"captures/ours/$name.jsonl" --baseline "captures/baseline/$name.json" $UPDATE || rc=1
done
exit $rc

View File

@ -13,75 +13,105 @@ import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument("--pci", required=True, help="domain:bus:device.function")
parser.add_argument("--expect-pci-driver", required=True)
parser.add_argument("--label", required=True)
args = parser.parse_args()
if not re.fullmatch(r"[A-Za-z0-9_-]+", args.label):
parser.error("label must contain only letters, digits, underscores or hyphens")
if not re.fullmatch(r"[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-7]", args.pci):
parser.error("invalid PCI address")
device = Path("/sys/bus/pci/devices") / args.pci.lower()
out = ROOT / "reports" / ("native-hello-" + args.label)
out.mkdir(parents=True, exist_ok=True)
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def binding():
return (device / "driver").resolve(strict=True).name
before = binding()
if before != args.expect_pci_driver:
raise SystemExit(f"refusing mismatched PCI driver: {before}")
binary = ROOT / "target/hardware-hello/native-hello"
cubin = ROOT / "target/hardware-hello/native_hello.sm70.cubin"
linkage = subprocess.check_output(["ldd", str(binary)], text=True)
(out / "linkage.txt").write_text(linkage)
library = Path(re.search(r"libcuda\.so\.1 => (\S+)", linkage)[1]).resolve()
artifacts = [binary, cubin, library, ROOT / "tests/hardware/native_hello.rs",
ROOT / "tests/hardware/native_hello.cu"]
report = {
"label": args.label, "pci": args.pci.lower(), "pci_driver_before": before,
"kernel": os.uname().release, "artifacts": {str(p): digest(p) for p in artifacts},
"environment": {key: os.environ.get(key) for key in
("CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER")},
"nvidia_version": Path("/proc/driver/nvidia/version").read_text()
if Path("/proc/driver/nvidia/version").exists() else None,
"scope": "Native sm70 cubin execution via CUDA Driver API on the recorded driver. An original-driver pass is only a baseline.",
"full_driver_parity_proven": False, "runs": [], "passed": False,
}
for seed in (0x12F04321, 0xD86B9170):
trace = out / f"syscalls-{seed}.log"
command = ["strace", "-f", "-qq", "-s", "128", "-e",
"trace=openat,ioctl,mmap,munmap,close", "-o", str(trace),
str(binary), str(cubin), args.pci, str(seed)]
def binding(device):
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=60)
run = {"seed": seed, "exit_code": result.returncode,
"stdout": result.stdout, "stderr": result.stderr,
"command": command, "trace_sha256": digest(trace)}
if result.returncode == 0:
observed = json.loads(result.stdout)
run["observed"] = observed
run["passed"] = (observed.get("passed") is True
and observed.get("seed") == seed
and observed.get("verified_words") == 64
and observed.get("context_destroyed") is True)
else:
run["passed"] = False
except subprocess.TimeoutExpired as error:
run = {"seed": seed, "passed": False, "timeout": True, "error": str(error)}
report["runs"].append(run)
if not run["passed"]:
break
report["pci_driver_after"] = binding()
report["passed"] = (len(report["runs"]) == 2 and all(run["passed"] for run in report["runs"])
and report["pci_driver_after"] == before)
(out / "validation.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
raise SystemExit(0 if report["passed"] else 1)
return (device / "driver").resolve(strict=True).name
except OSError:
return None
def resolve_libcuda(linkage):
match = re.search(r"libcuda\.so\.1 => (\S+)", linkage)
if match is None or match.group(1) == "not":
return None
library = Path(match.group(1)).resolve()
return library if library.is_file() else None
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("--pci", required=True, help="domain:bus:device.function")
parser.add_argument("--expect-pci-driver", required=True)
parser.add_argument("--label", required=True)
args = parser.parse_args(argv)
if not re.fullmatch(r"[A-Za-z0-9_-]+", args.label):
parser.error("label must contain only letters, digits, underscores or hyphens")
if not re.fullmatch(r"[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-7]", args.pci):
parser.error("invalid PCI address")
device = Path("/sys/bus/pci/devices") / args.pci.lower()
before = binding(device)
if before != args.expect_pci_driver:
raise SystemExit(f"refusing mismatched PCI driver: {before}")
binary = ROOT / "target/hardware-hello/native-hello"
cubin = ROOT / "target/hardware-hello/native_hello.sm70.cubin"
for required in (binary, cubin):
if not required.is_file():
raise SystemExit(f"missing required artifact: {required}")
out = ROOT / "reports" / ("native-hello-" + args.label)
out.mkdir(parents=True, exist_ok=True)
linkage = subprocess.check_output(["ldd", str(binary)], text=True)
(out / "linkage.txt").write_text(linkage)
library = resolve_libcuda(linkage)
if library is None:
raise SystemExit(f"failed to resolve libcuda.so.1 from ldd output for {binary}")
artifacts = [binary, cubin, library, ROOT / "tests/hardware/native_hello.rs",
ROOT / "tests/hardware/native_hello.cu"]
report = {
"label": args.label, "pci": args.pci.lower(), "pci_driver_before": before,
"kernel": os.uname().release, "artifacts": {str(p): digest(p) for p in artifacts},
"environment": {key: os.environ.get(key) for key in
("CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER")},
"nvidia_version": Path("/proc/driver/nvidia/version").read_text()
if Path("/proc/driver/nvidia/version").exists() else None,
"scope": "Native sm70 cubin execution via CUDA Driver API on the recorded driver. An original-driver pass is only a baseline.",
"full_driver_parity_proven": False, "runs": [], "passed": False,
}
for seed in (0x12F04321, 0xD86B9170):
trace = out / f"syscalls-{seed}.log"
command = ["strace", "-f", "-qq", "-s", "128", "-e",
"trace=openat,ioctl,mmap,munmap,close", "-o", str(trace),
str(binary), str(cubin), args.pci, str(seed)]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=60)
run = {"seed": seed, "exit_code": result.returncode,
"stdout": result.stdout, "stderr": result.stderr,
"command": command,
"trace_sha256": digest(trace) if trace.is_file() else None}
if result.returncode == 0:
try:
observed = json.loads(result.stdout)
except json.JSONDecodeError as error:
run["error"] = f"invalid JSON stdout: {error}"
run["passed"] = False
else:
run["observed"] = observed
run["passed"] = (isinstance(observed, dict)
and observed.get("passed") is True
and observed.get("seed") == seed
and observed.get("verified_words") == 64
and observed.get("context_destroyed") is True)
else:
run["passed"] = False
except subprocess.TimeoutExpired as error:
run = {"seed": seed, "passed": False, "timeout": True, "error": str(error)}
except OSError as error:
run = {"seed": seed, "passed": False, "error": str(error)}
report["runs"].append(run)
if not run["passed"]:
break
report["pci_driver_after"] = binding(device)
report["passed"] = (len(report["runs"]) == 2 and all(run["passed"] for run in report["runs"])
and report["pci_driver_after"] == before)
(out / "validation.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
return 0 if report["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())