Files
nvdriver/tools/verify_580_citations.py

332 lines
12 KiB
Python
Executable File

#!/usr/bin/env python3
"""Verify `_nv<N>rm` 580.178.04 symbol citations against `nv-kernel.o_binary`.
Zero-Ghidra verifier complementing Issue #60:
1. Scans Rust sources for every `_nv\\d{6}rm` citation.
2. Verifies every cited symbol exists in the 580.178.04 `nv-kernel.o_binary`
defined symbol table (`nm --defined-only`) and validates the binary SHA-256.
3. Optionally disassembles targeted symbols (`--inspect`) via `objdump -dr`,
extracting instruction counts, direct `_nv*rm` callees, and BAR0 MMIO
register immediates (including Ghidra-logger-safe parsing helpers).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CANONICAL_580_SHA256 = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
SYM_RE = re.compile(r"\b(_nv\d{6}rm)\b")
GHIDRA_MARKER_RE = re.compile(r"====\s+(_nv\d{6}rm)\s+@\s+([0-9a-fA-F]+)")
CALL_RELOC_RE = re.compile(r"^\s+[0-9a-f]+:\s+R_X86_64_(?:PLT32|PC32)\s+(_nv\d{6}rm)\b")
RELOC_LINE_RE = re.compile(r"^\s+[0-9a-f]+:\s+R_[A-Z0-9_]+\b")
CALL_INSN_RE = re.compile(r"^\s+[0-9a-f]+:\s+call[qlw]?\b")
INSN_RE = re.compile(r"^\s+[0-9a-f]+:\s+(?!R_[A-Z0-9_]+\b)[a-zA-Z]")
MMIO_IMM_RE = re.compile(
r"\$(0x(?:1[01][0-9a-f]{4}|1fa[0-9a-f]{3}|9[08a][0-9a-f]{4}|8[0-9a-f]{5}|c[0-9a-f]{5}))(?![0-9a-fA-F])"
)
DEFAULT_BINARY_CANDIDATES = (
"/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary",
"/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary",
)
def find_binary(explicit: str | None) -> Path | None:
if explicit:
p = Path(explicit)
return p if p.is_file() else None
env_bin = os.environ.get("NV_RS_580_BINARY")
if env_bin:
p = Path(env_bin)
if p.is_file():
return p
analysis_root = os.environ.get("NV_RS_ANALYSIS_ROOT")
if analysis_root:
p = Path(analysis_root) / "extracted/kernel/nvidia/nv-kernel.o_binary"
if p.is_file():
return p
for cand in DEFAULT_BINARY_CANDIDATES:
p = Path(cand)
if p.is_file():
return p
return None
def collect_citations(paths: list[Path], root: Path = ROOT) -> dict[str, list[str]]:
if not paths:
raise ValueError("no source paths provided")
cited: dict[str, list[str]] = {}
files: list[Path] = []
for p in paths:
if p.is_file():
files.append(p)
elif p.is_dir():
files.extend(sorted(p.rglob("*.rs")))
else:
raise FileNotFoundError(f"source path not found: {p}")
if not files:
raise ValueError("no source files found under requested paths")
for f in files:
try:
rel = str(f.relative_to(root))
except ValueError:
rel = str(f)
for lineno, line in enumerate(f.read_text(errors="ignore").splitlines(), 1):
for sym in SYM_RE.findall(line):
cited.setdefault(sym, []).append(f"{rel}:{lineno}")
return cited
def parse_ghidra_markers(log_text: str) -> list[tuple[str, str]]:
"""Extract (symbol, address) markers even when headless Ghidra prefixes lines with logger text."""
return GHIDRA_MARKER_RE.findall(log_text)
def load_defined_symbols(binary: Path) -> set[str]:
out = subprocess.check_output(
["nm", "--defined-only", str(binary)],
text=True,
env=dict(os.environ, LC_ALL="C"),
)
return set(SYM_RE.findall(out))
def parse_objdump_inspect(sym: str, out: str) -> dict[str, object]:
insns: list[str] = []
callees_set: set[str] = set()
prev_is_call = False
for ln in out.splitlines():
if RELOC_LINE_RE.match(ln):
if prev_is_call:
m = CALL_RELOC_RE.match(ln)
if m:
callees_set.add(m.group(1))
continue
if INSN_RE.match(ln):
insns.append(ln)
prev_is_call = bool(CALL_INSN_RE.match(ln))
else:
prev_is_call = False
mmio = sorted(set(MMIO_IMM_RE.findall(out)))
return {
"symbol": sym,
"instructions": len(insns),
"callees": sorted(callees_set),
"mmio_immediates": mmio,
}
def inspect_symbol(binary: Path, sym: str) -> dict[str, object]:
out = subprocess.check_output(
["objdump", "-dr", "--no-show-raw-insn", f"--disassemble={sym}", str(binary)],
text=True,
env=dict(os.environ, LC_ALL="C"),
)
return parse_objdump_inspect(sym, out)
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def _check(cond: bool, msg: object) -> None:
if not cond:
raise AssertionError(msg)
def run_self_check() -> int:
# 1. Verify Ghidra logger-prefixed markers parse identically to bare markers (Issue #60).
sample_log = (
"INFO DecompileByName.java> ==== _nv041361rm @ 06887400 (GhidraScript)\n"
"==== _nv041332rm @ 00717920\n"
)
markers = parse_ghidra_markers(sample_log)
_check(markers == [("_nv041361rm", "06887400"), ("_nv041332rm", "00717920")], markers)
# 2. Verify citation collector scans gsp_boot.rs + gsp_transport.rs without error,
# and rejects nonexistent or empty scan targets.
gsp_files = [
ROOT / "src/nvidia/src/gpu/gsp_boot.rs",
ROOT / "src/nvidia/src/gpu/gsp_transport.rs",
]
cited = collect_citations(gsp_files)
_check(
"_nv041332rm" in cited and "_nv041222rm" in cited and "_nv041429rm" in cited,
f"unexpected GSP citation set: {sorted(cited)[:10]}",
)
try:
collect_citations([ROOT / "src/does_not_exist_typo.rs"])
raise AssertionError("expected nonexistent path to raise FileNotFoundError")
except FileNotFoundError:
pass
with tempfile.TemporaryDirectory() as empty_td:
try:
collect_citations([Path(empty_td)])
raise AssertionError("expected empty directory to raise ValueError")
except ValueError:
pass
# 3. Verify instruction counting, callee extraction, and MMIO immediate boundaries.
_check(INSN_RE.match(" 0:\tmov $0x1,%eax") is not None, "instruction line must match")
_check(INSN_RE.match(" 7:\t00 00") is None, "wrapped raw bytes must not match")
_check(
INSN_RE.match(" 1:\tR_X86_64_PC32\t_nv041332rm-0x4") is None,
"relocation record must not count as an instruction",
)
sample_disasm = "\n".join([
"0000000000000000 <_nv041407rm>:",
" 0:\tmov $0x110040,%esi",
" 5:\tmov $0x100000,%edx",
" a:\tmov $0x10000000,%ecx",
" f:\tlea 0x0(%rip),%rax",
" 12:\tR_X86_64_PC32\t_nv099999rm-0x4",
" 16:\tcall 1b <_nv041407rm+0x1b>",
" 17:\tR_X86_64_PLT32\t_nv043721rm-0x4",
" 1b:\tcallq 20 <_nv041407rm+0x20>",
" 1c:\tR_X86_64_PC32\t_nv053912rm-0x4",
" 20:\tret",
])
parsed = parse_objdump_inspect("_nv041407rm", sample_disasm)
_check(parsed["instructions"] == 7, f"expected 7 instructions (excluding relocs), got {parsed}")
_check(
parsed["callees"] == ["_nv043721rm", "_nv053912rm"],
f"expected only call targets (PLT32+PC32, no lea), got {parsed['callees']}",
)
_check(
parsed["mmio_immediates"] == ["0x100000", "0x110040"],
f"expected complete hex boundary excluding $0x10000000, got {parsed['mmio_immediates']}",
)
# 4. Verify a noncanonical ELF defining every cited symbol is still rejected and
# --paths with a missing file exits nonzero.
cc = shutil.which("cc")
nm = shutil.which("nm")
if cc and nm:
with tempfile.TemporaryDirectory() as td:
td_path = Path(td)
src_rs = td_path / "sample.rs"
src_rs.write_text("// _nv041332rm\n", encoding="utf-8")
src_c = td_path / "fake.c"
src_c.write_text("void _nv041332rm(void) {}\n", encoding="utf-8")
obj = td_path / "fake.o"
subprocess.run([cc, "-c", str(src_c), "-o", str(obj)], check=True)
proc = subprocess.run(
[sys.executable, str(Path(__file__)), "--binary", str(obj), "--paths", str(src_rs), "--json"],
capture_output=True,
text=True,
)
_check(
proc.returncode == 1,
f"expected rc=1 for noncanonical binary, got {proc.returncode}: {proc.stdout}",
)
payload = json.loads(proc.stdout)
_check(payload["missing_count"] == 0, payload)
_check(payload["canonical_580_sha256_match"] is False, payload)
_check(payload["passed"] is False, payload)
missing_proc = subprocess.run(
[sys.executable, str(Path(__file__)), "--binary", str(obj), "--paths", str(td_path / "typo.rs")],
capture_output=True,
text=True,
)
_check(
missing_proc.returncode == 2,
f"expected rc=2 for missing path, got {missing_proc.returncode}: {missing_proc.stderr}",
)
print(f"verify_580_citations self-check PASS ({len(cited)} distinct GSP symbols collected)")
return 0
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="Verify 580.178.04 _nv<N>rm symbol citations.")
ap.add_argument("--self-check", action="store_true", help="Run offline parser/collector self-check.")
ap.add_argument("--binary", help="Path to 580.178.04 nv-kernel.o_binary.")
ap.add_argument(
"--paths",
nargs="*",
default=[str(ROOT / "src")],
help="Files or directories to scan for _nv<N>rm citations (default: src/).",
)
ap.add_argument(
"--inspect",
nargs="*",
default=[],
help="Optional symbol names to disassemble and summarize via objdump -dr.",
)
ap.add_argument("--json", action="store_true", help="Emit machine-readable JSON output.")
args = ap.parse_args(argv)
if args.self_check:
return run_self_check()
binary = find_binary(args.binary)
if binary is None:
print(
"SKIP: 580.178.04 nv-kernel.o_binary not found "
"(pass --binary or set NV_RS_580_BINARY / NV_RS_ANALYSIS_ROOT)",
file=sys.stderr,
)
return 2
digest = sha256_file(binary)
sha256_match = digest == CANONICAL_580_SHA256
defined = load_defined_symbols(binary)
scan_paths = [Path(p) for p in args.paths]
try:
cited = collect_citations(scan_paths)
except (FileNotFoundError, ValueError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
missing = {sym: locs for sym, locs in sorted(cited.items()) if sym not in defined}
inspected = [inspect_symbol(binary, sym) for sym in args.inspect]
report = {
"passed": len(missing) == 0 and sha256_match,
"binary": str(binary),
"binary_sha256": digest,
"canonical_580_sha256_match": sha256_match,
"defined_symbols": len(defined),
"cited_distinct": len(cited),
"missing_count": len(missing),
"missing": missing,
"inspected": inspected,
}
if args.json:
print(json.dumps(report, indent=2))
else:
print(
f"580.178.04 citation check: {len(cited) - len(missing)}/{len(cited)} cited symbols "
f"defined in {binary} (sha256_match={report['canonical_580_sha256_match']}, "
f"missing={len(missing)})"
)
if not sha256_match:
print(
f" SHA256 MISMATCH: expected canonical 580.178.04 {CANONICAL_580_SHA256}, "
f"got {digest}"
)
for sym, locs in missing.items():
print(f" MISSING {sym}: {', '.join(locs[:5])}")
for info in inspected:
print(
f" INSPECT {info['symbol']}: {info['instructions']} insns, "
f"mmio={info['mmio_immediates']}, callees={info['callees'][:8]}"
)
return 0 if report["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())