Files
nvdriver/tools/compare_software_controls.py
morebrackets 7818fd7a18 tools: make UVM/TLB/time C oracles portable and harden control compare/capture
- tools/check_uvm_ioctl_layout.py: resolve NVIDIA 580.178.04 sources via
  NV_RS_KERNEL_SRC / NV_RS_ANALYSIS_ROOT / /usr/src/nvidia-580.178.04 /
  /usr/src/nvidia-srv-580.178.04 instead of failing when /home/geodd is
  absent; replace -O-disabled asserts with explicit errors and argparse.
- tools/check_gv100_tlb_oracle.py and tools/check_system_time_source.py:
  resolve kernel sources portably, wrap execution in main(), create
  report parent dirs, and replace -O-disabled asserts.
- tools/compare_software_controls.py: wrap in main(), guard unknown
  ioctl kinds instead of KeyError, create output parent dirs, and use
  single-pass boundary-aware hex handle normalization so chained or
  prefix-overlapping handle mappings do not corrupt labels.
- tools/ioctl_capture/cuda_basic.py: set explicit 64-bit ctypes argtypes
  for all CUDA Driver API calls, fail non-zero on H2D/D2H roundtrip
  mismatch, and clean up allocations/context in a try/finally inside
  main().
- tests/offline/test_oracle_portability_and_capture.py: offline unit
  tests covering path resolution, CLI validation, single-pass handle
  normalization, and 64-bit ctypes signatures.
2026-12-02 04:16:27 -08:00

181 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""Actual original-vs-loaded Rust parity; normalize only opaque handles/pointers."""
import argparse
import hashlib
import json
from pathlib import Path
import re
R = Path(__file__).resolve().parent.parent
HANDLE_OFFSETS = {0x2b: (0, 4, 8), 0x2a: (0, 4), 0x29: (0, 4, 8)}
def word(b, offset):
return int.from_bytes(b[offset:offset + 4], "little")
def _mapped(b, offset, mapping):
if offset + 4 > len(b):
return
key = word(b, offset)
if key in mapping:
b[offset:offset + 4] = mapping[key].to_bytes(4, "little")
def normalize_top(data, kind, mapping):
buf = bytearray.fromhex(data)
for offset in HANDLE_OFFSETS.get(kind, ()):
_mapped(buf, offset, mapping)
return buf
def normalize_payload(data, kind, mapping):
buf = bytearray.fromhex(data or "")
if kind == 0x2a and len(buf) >= 4:
_mapped(buf, 0, mapping)
return buf
def normalize_label(label, mapping):
if not mapping:
return label
replacements = {hex(before): hex(after) for before, after in mapping.items()}
pattern = re.compile(
r"(?<![0-9a-fA-FxX])(?:"
+ "|".join(re.escape(k) for k in sorted(replacements, key=len, reverse=True))
+ r")(?![0-9a-fA-F])"
)
return pattern.sub(lambda m: replacements[m.group(0)], label)
def compare_records(original, rust):
orig_records = original.get("records")
rust_records = rust.get("records")
if not isinstance(orig_records, list) or not isinstance(rust_records, list):
raise SystemExit("Both comparison files must contain a 'records' list")
if len(orig_records) != len(rust_records):
raise SystemExit("Request sequence lengths differ")
if not orig_records:
raise SystemExit("No records to compare")
mapping = {}
cases = []
for old, new in zip(orig_records, rust_records):
issues = []
req = int(old["request"], 16)
kind = req & 255
if kind not in HANDLE_OFFSETS:
issues.append(f"unsupported ioctl kind 0x{kind:02x}")
if req != int(new["request"], 16):
issues.append("request ioctl differs")
inp = normalize_top(old["input_top"], kind, mapping)
actual_input = bytearray.fromhex(new["input_top"])
ptr_offset = 16 if kind in (0x2a, 0x2b) else None
# Only known Python-backed non-null parameter pointers are normalized. NULL and
# sentinel/non-backed addresses would remain exact and expose validation gaps.
pointer_pair = None
if (
ptr_offset is not None
and ptr_offset + 8 <= len(inp)
and ptr_offset + 8 <= len(actual_input)
and old.get("input_payload") is not None
and new.get("input_payload") is not None
):
oldptr = int.from_bytes(inp[ptr_offset:ptr_offset + 8], "little")
newptr = int.from_bytes(actual_input[ptr_offset:ptr_offset + 8], "little")
if oldptr and newptr:
pointer_pair = (oldptr, newptr)
inp[ptr_offset:ptr_offset + 8] = newptr.to_bytes(8, "little")
if inp != actual_input:
issues.append("normalized request wrapper differs")
if normalize_payload(old.get("input_payload"), kind, mapping) != bytearray.fromhex(
new.get("input_payload") or ""
):
issues.append("normalized input payload differs")
if old["linux_errno"] != new["linux_errno"]:
issues.append("Linux errno differs")
if old["status"] != new["status"]:
issues.append("NV status differs")
if kind == 0x2b:
old_resp = bytes.fromhex(old["response"])
new_resp = bytes.fromhex(new["response"])
old_in = bytes.fromhex(old["input_top"])
expected_obj = word(old_resp, 8)
actual_obj = word(new_resp, 8)
if (
word(old_in, 0) == 0
and expected_obj
and (old["status"] == 0 or expected_obj != word(old_in, 8))
):
if expected_obj in mapping and mapping[expected_obj] != actual_obj:
issues.append("client handle mapping changed")
if actual_obj == 0:
issues.append("generated client became NULL")
if any(k != expected_obj and v == actual_obj for k, v in mapping.items()):
issues.append("opaque client mapping collapsed distinct handles")
mapping[expected_obj] = actual_obj
out = normalize_top(old["response"], kind, mapping)
actual_out = bytearray.fromhex(new["response"])
if pointer_pair is not None and ptr_offset + 8 <= len(out):
oldptr, newptr = pointer_pair
if int.from_bytes(out[ptr_offset:ptr_offset + 8], "little") == oldptr:
out[ptr_offset:ptr_offset + 8] = newptr.to_bytes(8, "little")
if out != actual_out:
issues.append("normalized response wrapper differs")
if normalize_payload(old.get("payload"), kind, mapping) != bytearray.fromhex(
new.get("payload") or ""
):
issues.append("normalized output payload differs")
label = normalize_label(old["label"], mapping)
if label != new["label"]:
issues.append("case identity/order differs after handle normalization")
cases.append({
"original_label": old["label"],
"rust_label": new["label"],
"passed": not issues,
"issues": issues,
})
return cases
def main(argv=None):
p = argparse.ArgumentParser()
p.add_argument("--original", type=Path, default=R / "reports/software-controls-replay-original.json")
p.add_argument("--rust", type=Path, default=R / "reports/software-controls-rust-live.json")
p.add_argument("--out", type=Path, default=R / "reports/software-controls-live-comparison.json")
a = p.parse_args(argv)
original = json.loads(a.original.read_text())
rust = json.loads(a.rust.read_text())
cases = compare_records(original, rust)
report = {
"passed": all(c["passed"] for c in cases),
"scope": "Actual loaded Rust software-only controls vs original responses. Not CUDA or physical GPU parity.",
"cases": cases,
"case_count": len(cases),
"source_sha256": {
str(f): hashlib.sha256(f.read_bytes()).hexdigest() for f in (a.original, a.rust)
},
"rust_module_identity": rust.get("module_identity"),
"normalization": [
"Generated client handles mapped consistently/injectively at root allocation responses.",
"Only known non-null Python-backed nested parameter pointer fields are normalized.",
"No NV status, Linux errno, padding, method values or output payload data are excluded.",
],
"limits": [
"Runs occur at different times; identical deterministic control inputs and normalized opaque identifiers are compared.",
"This finite software-client suite does not establish GPU/backend/security/concurrency parity.",
],
}
a.out.parent.mkdir(parents=True, exist_ok=True)
a.out.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({
"passed": report["passed"],
"cases": len(cases),
"failures": [c for c in cases if not c["passed"]],
}, indent=2))
raise SystemExit(0 if report["passed"] else 1)
if __name__ == "__main__":
main()