mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
631 lines
23 KiB
Python
631 lines
23 KiB
Python
#!/usr/bin/env python3
|
|
"""Multi-State Stateful RM Control Unicorn Binary Oracle (Pillar 5).
|
|
|
|
Probes ALL 2,096 NVIDIA 580.178.04 RM controls in `nv-kernel.o_binary` via Unicorn
|
|
on the real GV100 `gpu_world()` across multiple input states per control:
|
|
- state 0 (`zero`): zeroed parameter buffer
|
|
- state 1 (`nonzero_one`): populated non-zero input (index/count/flags/handle = 1)
|
|
- state 2 (`boundary_ff`): boundary / invalid-argument sentinel (`0xffffffff` words)
|
|
|
|
Exports `run_checks() -> list[dict]` returning `{"name": ..., "passed": bool, "diffs": [...]}`
|
|
and is runnable standalone via `/home/geodd/.local/opt/rea-python/bin/python3 tools/oracle_rm_multistate.py`.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tools"))
|
|
|
|
# Intentional artificial-restriction unlocks (brand/GeForce/P2P/RDMA/vGPU/NVENC/CSP):
|
|
# never add artificial NVIDIA restriction blocks for these controls.
|
|
INTENTIONAL_UNLOCK_CONTROLS: set[int] = set()
|
|
|
|
|
|
def load_all_580_controls() -> dict[int, tuple[int, int, int, str]]:
|
|
"""Parse all 2,096 unique RM controls from src/nvidia/src/rmapi/control_table.rs."""
|
|
ct_src = (ROOT / "src/nvidia/src/rmapi/control_table.rs").read_text()
|
|
all_methods: dict[int, tuple[int, int, int, str]] = {}
|
|
for m in re.finditer(
|
|
r"m\((0x[0-9a-f]+),\s*(0x[0-9a-f]+),\s*(0x[0-9a-f]+),\s*(\d+),\s*(\d+),\s*(\d+)\)",
|
|
ct_src,
|
|
):
|
|
cls, cid, fl, _ar, psz, h = (
|
|
int(m[1], 16),
|
|
int(m[2], 16),
|
|
int(m[3], 16),
|
|
int(m[4]),
|
|
int(m[5]),
|
|
int(m[6]),
|
|
)
|
|
if cid not in all_methods:
|
|
all_methods[cid] = (cls, fl, psz, f"_nv{h:06d}rm")
|
|
return all_methods
|
|
|
|
|
|
def make_state_input(state_name: str, psz: int) -> bytes:
|
|
"""Build deterministic input parameter buffer for a given state."""
|
|
if psz == 0:
|
|
return b""
|
|
if state_name == "zero":
|
|
return b"\x00" * psz
|
|
if state_name == "nonzero_one":
|
|
buf = bytearray(psz)
|
|
# Set first up to 4 u32 words to 1 (or single byte/u16 for tiny structs).
|
|
if psz < 4:
|
|
buf[0] = 1
|
|
else:
|
|
n_words = min(4, psz // 4)
|
|
for i in range(n_words):
|
|
struct.pack_into("<I", buf, i * 4, 1)
|
|
return bytes(buf)
|
|
if state_name == "boundary_ff":
|
|
buf = bytearray(psz)
|
|
# Set first up to 16 bytes to 0xff (0xffffffff sentinel in first 4 u32 words).
|
|
n = min(16, psz)
|
|
for i in range(n):
|
|
buf[i] = 0xFF
|
|
return bytes(buf)
|
|
raise ValueError(f"unknown state {state_name}")
|
|
|
|
|
|
def find_rust_test_binary() -> Path:
|
|
"""Build (if needed) and locate the compiled nv-rs-core unittest binary."""
|
|
env = dict(os.environ)
|
|
cargo_bin = str(Path.home() / ".cargo/bin")
|
|
if cargo_bin not in env.get("PATH", ""):
|
|
env["PATH"] = f"{cargo_bin}:{env.get('PATH', '')}"
|
|
cmd = [
|
|
"cargo",
|
|
"test",
|
|
"--manifest-path",
|
|
str(ROOT / "src/nvidia/Cargo.toml"),
|
|
"--lib",
|
|
"--no-run",
|
|
"--message-format=json",
|
|
]
|
|
out = subprocess.check_output(cmd, env=env, text=True)
|
|
for line in out.splitlines():
|
|
if not line.startswith("{"):
|
|
continue
|
|
msg = json.loads(line)
|
|
if (
|
|
msg.get("reason") == "compiler-artifact"
|
|
and msg.get("executable")
|
|
and "lib" in msg.get("target", {}).get("kind", [])
|
|
):
|
|
return Path(msg["executable"])
|
|
raise RuntimeError("could not find nv-rs-core unittest binary")
|
|
|
|
|
|
def run_rust_batch(requests: list[tuple[int, int, bytes]]) -> list[tuple[bool, int, bytes]]:
|
|
"""Run (cmd, psz, in_bytes) batch through real compiled Rust ctrl_ext*::dispatch."""
|
|
exe = find_rust_test_binary()
|
|
with tempfile.TemporaryDirectory() as td:
|
|
in_file = Path(td) / "in.txt"
|
|
out_file = Path(td) / "out.txt"
|
|
with in_file.open("w") as f:
|
|
for cid, psz, data in requests:
|
|
# Cap extremely large buffers to 65536 bytes only if identical tail;
|
|
# actually pass exact hex for <= 16384 or full buffer (max is 229KB, rare).
|
|
hex_in = "-" if not data else data.hex()
|
|
f.write(f"{cid:08x} {psz} {hex_in}\n")
|
|
env = dict(os.environ)
|
|
env["NV_RS_ORACLE_BATCH_IN"] = str(in_file)
|
|
env["NV_RS_ORACLE_BATCH_OUT"] = str(out_file)
|
|
subprocess.run(
|
|
[str(exe), "--exact", "rmapi::ctrl_ext10::multistate_oracle_bridge::oracle_multistate_batch_dispatch", "--nocapture"],
|
|
env=env,
|
|
check=True,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
results: list[tuple[bool, int, bytes]] = []
|
|
with out_file.open() as f:
|
|
for line in f:
|
|
parts = line.strip().split(" ")
|
|
handled = parts[1] == "1"
|
|
st = int(parts[2], 16)
|
|
out_bytes = b"" if parts[3] == "-" else bytes.fromhex(parts[3])
|
|
results.append((handled, st, out_bytes))
|
|
return results
|
|
|
|
|
|
def build_unicorn_world():
|
|
"""Initialize GV100 gpu_world() via check_rmapi_binary (same clean setup as mock_gv100_diff.py)."""
|
|
import check_rmapi_binary as crb
|
|
|
|
if not crb.TRANSCRIPT.exists():
|
|
alt = Path(__file__).resolve().parents[1] / "target/trace/b3-bar0.txt"
|
|
if alt.exists():
|
|
crb.TRANSCRIPT = alt
|
|
|
|
seq = crb.GpuSequence("rm_controls_multistate_2096")
|
|
seq.initialized(1)
|
|
crb.state["admin"] = 1
|
|
E = crb.E
|
|
|
|
def _replace_hook(sym_name: str, fn):
|
|
if sym_name in crb.HOOKS:
|
|
E.cpu.hook_del(crb.HOOKS.pop(sym_name))
|
|
E.handlers.pop(sym_name, None)
|
|
crb.HOOKS[sym_name] = E.install(sym_name, fn)
|
|
|
|
class _DefaultRegs(dict):
|
|
def __contains__(self, k):
|
|
return True
|
|
|
|
def __getitem__(self, k):
|
|
return dict.get(self, k, 0)
|
|
|
|
crb.gpu_state["registers"] = _DefaultRegs(crb.gpu_state["registers"])
|
|
|
|
def _safe_copy(a):
|
|
dst, src, n = a[0], a[1], a[2]
|
|
try:
|
|
E.cpu.mem_write(dst, bytes(E.cpu.mem_read(src, n)))
|
|
return 0
|
|
except Exception:
|
|
return 0x3D
|
|
|
|
def _safe_alloc(a):
|
|
sz = a[1] & 0xFFFFFFFF
|
|
if sz > 0x400000:
|
|
E.wq(a[0], 0)
|
|
return 0x51 # NV_ERR_NO_MEMORY
|
|
try:
|
|
E.wq(a[0], E.allocate(sz, 0xCC))
|
|
return 0
|
|
except Exception:
|
|
E.wq(a[0], 0)
|
|
return 0x51
|
|
|
|
_replace_hook("os_alloc_mem", _safe_alloc)
|
|
_replace_hook("os_memcpy_from_user", _safe_copy)
|
|
_replace_hook("os_memcpy_to_user", _safe_copy)
|
|
for _ext, _fn in (
|
|
("os_get_random_bytes", lambda a: (E.write(a[0], b"\x11" * min(a[1], 0x1000)), 0)[1]),
|
|
("os_call_vgpu_vfio", lambda a: 0x56),
|
|
("os_pci_remove_supported", lambda a: 0),
|
|
("nv_get_ctl_state", lambda a: 0),
|
|
("os_get_monotonic_tick_resolution_ns", lambda a: 1000000),
|
|
("os_get_monotonic_time_ns_hr", lambda a: 1000000),
|
|
(
|
|
"os_get_system_time",
|
|
lambda a: (
|
|
E.wd(a[0], 1700000000) if a[0] else None,
|
|
E.wd(a[1], 0) if a[1] else None,
|
|
0,
|
|
)[2],
|
|
),
|
|
("os_semaphore_may_sleep", lambda a: 1),
|
|
("os_is_grid_supported", lambda a: 0),
|
|
("os_device_vm_present", lambda a: 0),
|
|
("nv_acpi_dsm_method", lambda a: 0x56),
|
|
("nv_acpi_rom_method", lambda a: 0x56),
|
|
("nv_audio_dynamic_power", lambda a: 0),
|
|
("os_queue_work_item", lambda a: 0),
|
|
("os_delay_us", lambda a: 0),
|
|
("os_delay", lambda a: 0),
|
|
("os_pci_read_word", lambda a: 0),
|
|
("os_pci_read_dword", lambda a: 0),
|
|
("os_pci_read_byte", lambda a: 0),
|
|
("os_pci_write_dword", lambda a: 0),
|
|
("os_pci_write_word", lambda a: 0),
|
|
("os_pci_write_byte", lambda a: 0),
|
|
):
|
|
if _ext in E.externals and _ext not in crb.HOOKS:
|
|
crb.HOOKS[_ext] = E.install(_ext, _fn)
|
|
|
|
stub_ret56 = 0x3F001000
|
|
try:
|
|
E.cpu.mem_map(0x3F000000, 0x4000)
|
|
except Exception:
|
|
pass
|
|
E.cpu.mem_write(stub_ret56, b"\xb8\x56\x00\x00\x00\xc3")
|
|
dummy_vt = E.allocate(0x2000)
|
|
for o in range(0, 0x2000, 8):
|
|
E.wq(dummy_vt + o, stub_ret56)
|
|
|
|
def mk_sub(sz: int = 0x1000) -> int:
|
|
p = E.allocate(sz)
|
|
E.wq(p, dummy_vt)
|
|
return p
|
|
|
|
clk_ptr = E.q(seq.gpu + 0x2058)
|
|
for o in range(0x1490, 0x1560, 8):
|
|
if E.q(clk_ptr + o) == 0:
|
|
E.wq(clk_ptr + o, mk_sub(0x1000))
|
|
|
|
_, hc = seq.alloc(0, 0, 0, 0)
|
|
_, hd = seq.alloc(hc, hc, 0x1000, 0x80, params=bytes(56))
|
|
_, hs = seq.alloc(hc, hd, 0x2000, 0x2080, params=bytes(4))
|
|
rm_handles = {0x0000: hc, 0x0080: hd, 0x2080: hs}
|
|
for p, par, prm in (
|
|
(0x0004, hd, None),
|
|
(0x0073, hd, bytes(64)),
|
|
(0x90EC, hs, bytes(64)),
|
|
(0xA081, hs, bytes(64)),
|
|
(0xC372, hs, bytes(64)),
|
|
):
|
|
try:
|
|
st_a, nh = seq.alloc(hc, par, 0x3000 + p, p, params=prm)
|
|
if st_a == 0:
|
|
rm_handles[p] = nh
|
|
except Exception:
|
|
pass
|
|
|
|
gr = E.allocate(0x400)
|
|
E.wq(gr, dummy_vt)
|
|
E.wq(gr + 0xE0, seq.gpu)
|
|
E.wq(gr + 0xE8, seq.gpu)
|
|
rs_ref = E.allocate(0x400)
|
|
rs_cli = E.allocate(0x400)
|
|
E.wq(rs_ref + 0x48, rs_cli)
|
|
E.wq(rs_ref + 0x50, gr)
|
|
E.wq(rs_cli, dummy_vt)
|
|
E.wq(rs_cli + 0x48, rs_cli)
|
|
|
|
sub_uni = E.allocate(0x2000)
|
|
E.wq(sub_uni, dummy_vt)
|
|
E.wq(sub_uni + 0x48, rs_cli)
|
|
E.wq(sub_uni + 0x50, gr)
|
|
E.wq(sub_uni + 0xE0, seq.gpu)
|
|
E.wq(sub_uni + 0xE8, seq.gpu)
|
|
E.wq(sub_uni + 0x110, rs_ref)
|
|
E.wq(sub_uni + 0x118, rs_ref)
|
|
E.wq(sub_uni + 0x120, seq.gpu)
|
|
E.wq(sub_uni + 0x128, seq.gpu)
|
|
E.wq(sub_uni + 0x140, rs_ref)
|
|
E.wq(sub_uni + 0x158, gr)
|
|
|
|
gr2 = E.allocate(0x400)
|
|
E.wq(gr2, dummy_vt)
|
|
E.wq(gr2 + 0xE0, seq.gpu)
|
|
E.wq(gr2 + 0xE8, sub_uni)
|
|
E.wq(gr2 + 0xF0, sub_uni)
|
|
E.wq(gr2 + 0x118, rs_ref)
|
|
|
|
cls_simple = E.allocate(0x400)
|
|
E.wq(cls_simple + 0x128, gr)
|
|
E.wq(cls_simple + 0x158, gr)
|
|
E.wq(cls_simple + 0x1D0, sub_uni)
|
|
E.wq(cls_simple + 0x210, gr)
|
|
E.wd(cls_simple + 0x1A0, 1)
|
|
|
|
cls_zero = E.allocate(0x800)
|
|
E.wd(cls_zero + 0x1A0, 1)
|
|
|
|
cls_full = E.allocate(0x800)
|
|
E.wq(cls_full, dummy_vt)
|
|
for o in range(0x08, 0x400, 8):
|
|
E.wq(cls_full + o, sub_uni)
|
|
E.wq(cls_full + 0x128, gr2)
|
|
E.wq(cls_full + 0x158, gr2)
|
|
E.wq(cls_full + 0x210, gr2)
|
|
E.wd(cls_full + 0x1A0, 1)
|
|
|
|
d_obj = mk_sub(0x4000)
|
|
d_res = E.allocate(0x400)
|
|
E.wq(d_res, dummy_vt)
|
|
for o in (0xE0, 0xE8, 0x120, 0x128):
|
|
E.wq(d_res + o, seq.gpu)
|
|
d_stub = 0x3F000000
|
|
E.cpu.mem_write(d_stub, b"\xc3" * 0x100)
|
|
|
|
def _d_get_sub(args):
|
|
if (args[4] & 0xFFFFFFFF) != 0:
|
|
return 0x1F
|
|
if args[2]:
|
|
E.wq(args[2], seq.gpu)
|
|
if args[3]:
|
|
E.wq(args[3], d_obj)
|
|
return 0
|
|
|
|
E.install(d_stub, _d_get_sub)
|
|
E.wq(d_res + 0x118, d_stub)
|
|
d_cls = E.allocate(0x400)
|
|
E.wq(d_cls, dummy_vt)
|
|
for o in (0x28, 0x30, 0x128, 0x158, 0x1B8, 0x210):
|
|
E.wq(d_cls + o, d_res)
|
|
|
|
scratch = E.allocate(0x50000)
|
|
orig_start = E.cpu.emu_start
|
|
E.cpu.emu_start = lambda b, u, timeout=0, count=0: orig_start(
|
|
b, u, timeout=timeout or 200_000, count=count or 200_000
|
|
)
|
|
bss_base = 0x38000000
|
|
bss_snap = bytes(E.cpu.mem_read(bss_base, len(E.pristine[".bss"])))
|
|
saved_ctx = E.cpu.context_save()
|
|
saved_heap = E.heap
|
|
obj_snaps = [
|
|
(addr, bytes(E.cpu.mem_read(addr, sz)))
|
|
for addr, sz in (
|
|
(seq.gpu, 0x8000),
|
|
(seq.sys, 0x400),
|
|
(cls_simple, 0x400),
|
|
(cls_zero, 0x800),
|
|
(cls_full, 0x800),
|
|
(d_cls, 0x400),
|
|
(sub_uni, 0x2000),
|
|
(gr, 0x400),
|
|
(gr2, 0x400),
|
|
(d_obj, 0x4000),
|
|
(d_res, 0x400),
|
|
(rs_ref, 0x400),
|
|
(rs_cli, 0x400),
|
|
)
|
|
]
|
|
|
|
return {
|
|
"crb": crb,
|
|
"seq": seq,
|
|
"E": E,
|
|
"hc": hc,
|
|
"rm_handles": rm_handles,
|
|
"cls_simple": cls_simple,
|
|
"cls_zero": cls_zero,
|
|
"cls_full": cls_full,
|
|
"d_obj": d_obj,
|
|
"d_cls": d_cls,
|
|
"scratch": scratch,
|
|
"bss_base": bss_base,
|
|
"bss_snap": bss_snap,
|
|
"saved_ctx": saved_ctx,
|
|
"saved_heap": saved_heap,
|
|
"obj_snaps": obj_snaps,
|
|
"guard_mapped": False,
|
|
}
|
|
|
|
|
|
def exec_one_unicorn(world: dict, cid: int, psz: int, sym: str, in_bytes: bytes, allow_guard: bool = False):
|
|
"""Execute one (control, input_bytes) in Unicorn.
|
|
Returns (ok, mode, status_u32, out_bytes) where mode is 'rmapi' or 'direct'.
|
|
"""
|
|
E = world["E"]
|
|
seq = world["seq"]
|
|
hc = world["hc"]
|
|
rm_handles = world["rm_handles"]
|
|
scratch = world["scratch"]
|
|
bss_base = world["bss_base"]
|
|
bss_snap = world["bss_snap"]
|
|
saved_ctx = world["saved_ctx"]
|
|
saved_heap = world["saved_heap"]
|
|
d_obj = world["d_obj"]
|
|
d_cls = world["d_cls"]
|
|
|
|
E.heap = saved_heap
|
|
p = cid >> 16
|
|
if p in rm_handles:
|
|
try:
|
|
prm = None if psz == 0 else in_bytes
|
|
st, out = seq.control(hc, rm_handles[p], cid, params=prm, size=psz)
|
|
E.heap = saved_heap
|
|
return True, "rmapi", st & 0xFFFFFFFF, out
|
|
except Exception:
|
|
E.cpu.context_restore(saved_ctx)
|
|
E.cpu.mem_write(bss_base, bss_snap)
|
|
E.heap = saved_heap
|
|
if p == 0x0073:
|
|
E.wq(seq.gpu + 0x1F70, d_obj)
|
|
sz = min(max(psz, 16), 0x50000)
|
|
E.cpu.mem_write(scratch, in_bytes.ljust(sz, b"\x00"))
|
|
try:
|
|
st = E.call(sym, d_cls, scratch) & 0xFFFFFFFF
|
|
out = bytes(E.cpu.mem_read(scratch, psz)) if psz else b""
|
|
E.wq(seq.gpu + 0x1F70, 0)
|
|
E.heap = saved_heap
|
|
return True, "direct", st, out
|
|
except Exception:
|
|
E.wq(seq.gpu + 0x1F70, 0)
|
|
E.cpu.context_restore(saved_ctx)
|
|
E.cpu.mem_write(bss_base, bss_snap)
|
|
E.heap = saved_heap
|
|
|
|
sz = min(max(psz, 16), 0x50000)
|
|
if p in (0x5070, 0xC370, 0xC372):
|
|
E.wq(seq.gpu + 0x1F70, d_obj)
|
|
cands = (
|
|
(world["cls_simple"], world["cls_zero"], d_cls, world["cls_full"])
|
|
if allow_guard
|
|
else (world["cls_simple"], d_cls, world["cls_full"])
|
|
)
|
|
for cand in cands:
|
|
E.cpu.mem_write(scratch, in_bytes.ljust(sz, b"\x00"))
|
|
try:
|
|
st = E.call(sym, cand, scratch) & 0xFFFFFFFF
|
|
out = bytes(E.cpu.mem_read(scratch, psz)) if psz else b""
|
|
if p in (0x5070, 0xC370, 0xC372):
|
|
E.wq(seq.gpu + 0x1F70, 0)
|
|
E.heap = saved_heap
|
|
return True, "direct", st, out
|
|
except Exception:
|
|
E.cpu.context_restore(saved_ctx)
|
|
E.cpu.mem_write(bss_base, bss_snap)
|
|
E.heap = saved_heap
|
|
if p in (0x5070, 0xC370, 0xC372):
|
|
E.wq(seq.gpu + 0x1F70, 0)
|
|
return False, "fail", 0, b""
|
|
|
|
|
|
def run_checks(discover_only: bool = False) -> list[dict]:
|
|
all_methods = load_all_580_controls()
|
|
states = ("zero", "nonzero_one", "boundary_ff")
|
|
|
|
# 1. Build full (cid, state, in_bytes) matrix
|
|
cases: list[tuple[int, int, str, str, bytes]] = []
|
|
for cid, (_cls, _fl, psz, sym) in sorted(all_methods.items()):
|
|
for st_name in states:
|
|
cases.append((cid, psz, sym, st_name, make_state_input(st_name, psz)))
|
|
|
|
# 2. Run Rust batch dispatcher on all cases in one fast call
|
|
rust_res = run_rust_batch([(cid, psz, data) for cid, psz, _sym, _sn, data in cases])
|
|
|
|
# 3. Run Unicorn across all 2,096 * 3 = 6,288 cases
|
|
world = build_unicorn_world()
|
|
uni_results: dict[int, tuple[bool, str, int, bytes]] = {}
|
|
pass2_indices: list[int] = []
|
|
|
|
for idx, (cid, psz, sym, st_name, in_bytes) in enumerate(cases):
|
|
ok, mode, st, out = exec_one_unicorn(world, cid, psz, sym, in_bytes, allow_guard=False)
|
|
if ok:
|
|
uni_results[idx] = (ok, mode, st, out)
|
|
else:
|
|
pass2_indices.append(idx)
|
|
|
|
# Pass 2 with 0x0 guard page on restored clean object templates for uninitialized-subobject controls
|
|
if pass2_indices:
|
|
E = world["E"]
|
|
E.cpu.context_restore(world["saved_ctx"])
|
|
E.cpu.mem_write(world["bss_base"], world["bss_snap"])
|
|
for addr, snap in world["obj_snaps"]:
|
|
E.cpu.mem_write(addr, snap)
|
|
E.heap = world["saved_heap"]
|
|
try:
|
|
E.cpu.mem_map(0x0, 0x10000)
|
|
except Exception:
|
|
pass
|
|
E.install(0x0, lambda _a: 0x56)
|
|
world["guard_mapped"] = True
|
|
for idx in pass2_indices:
|
|
cid, psz, sym, st_name, in_bytes = cases[idx]
|
|
E.cpu.mem_write(0x0, b"\x00" * 0x10000)
|
|
for addr, snap in world["obj_snaps"]:
|
|
E.cpu.mem_write(addr, snap)
|
|
if cid == 0x00410110 and st_name != "zero":
|
|
buf = bytearray(in_bytes)
|
|
nested_ptr = world["scratch"] + 0x40000
|
|
E.cpu.mem_write(nested_ptr, struct.pack("<II", 1 if st_name == "nonzero_one" else 0xFFFF, 0))
|
|
struct.pack_into("<IIQ", buf, 0, 1, 0, nested_ptr)
|
|
in_bytes = bytes(buf)
|
|
if cid == 0x90740103:
|
|
# _nv059682rm -> _nv000904rm calls _nv042689rm(lVar5 + 0x240), which reads
|
|
# *(u32*)(param_1 + 0x10) = *(u32*)(0x250); non-zero exercises the bounded-queue path cleanly.
|
|
E.wd(0x250, 1)
|
|
ok, mode, st, out = exec_one_unicorn(world, cid, psz, sym, in_bytes, allow_guard=True)
|
|
uni_results[idx] = (ok, mode, st, out)
|
|
|
|
# 4. Build check 1 (full 2,096 x 3 = 6,288 Unicorn coverage) and
|
|
# check 2 (multi-state Rust ctrl_ext*::dispatch parity vs nv-kernel.o_binary).
|
|
exec_diffs = []
|
|
parity_diffs = []
|
|
executed_controls: set[int] = set()
|
|
executed_cases = 0
|
|
|
|
# Group by control to identify all multi-state stateful RMAPI controls
|
|
# (controls where nv-kernel.o_binary status or OK output varies across states).
|
|
by_ctrl: dict[int, list[tuple[int, str, int, bytes, bool, str, int, bytes, bool, int, bytes]]] = {}
|
|
for idx, (cid, psz, sym, st_name, in_bytes) in enumerate(cases):
|
|
ok, mode, u_st, u_out = uni_results[idx]
|
|
r_handled, r_st, r_out = rust_res[idx]
|
|
if ok:
|
|
executed_controls.add(cid)
|
|
executed_cases += 1
|
|
else:
|
|
exec_diffs.append({
|
|
"control": hex(cid),
|
|
"symbol": sym,
|
|
"state": st_name,
|
|
"error": "unicorn_exec_failed",
|
|
})
|
|
by_ctrl.setdefault(cid, []).append(
|
|
(psz, sym, idx, in_bytes, ok, mode, u_st, u_out, r_handled, r_st, r_out)
|
|
)
|
|
|
|
# Controls whose zero-state behavior is specifically asserted against standalone
|
|
# Emulator() or live GV100 NVML/PMGR tables in gpu_tests.rs & mock_gv100_diff.py.
|
|
LIVE_GV100_TABLE_CONTROLS = {0x00000110, 0x20800112, 0x20800194, 0x2080A028, 0x2080A635}
|
|
|
|
multistate_controls_verified = 0
|
|
multistate_cases_verified = 0
|
|
for cid, rows in sorted(by_ctrl.items()):
|
|
if cid in INTENTIONAL_UNLOCK_CONTROLS or cid in LIVE_GV100_TABLE_CONTROLS:
|
|
continue
|
|
if not all(r[4] and r[5] == "rmapi" and r[8] for r in rows):
|
|
continue
|
|
# Check whether this control has multi-state behavior in nv-kernel.o_binary
|
|
# (status varies across zero / nonzero_one / boundary_ff, OR is one of the
|
|
# explicitly upgraded stateful byte-writing controls).
|
|
orig_statuses = {r[6] for r in rows}
|
|
stateful_byte_cids = {0x20801328, 0x20808545, 0x2080A801}
|
|
if len(orig_statuses) <= 1 and cid not in stateful_byte_cids:
|
|
continue
|
|
# Skip constant-status controls that only differ on non-zero states when zero also differs
|
|
# solely due to unpopulated gpu_world() sub-engine tables (already tracked separately).
|
|
multistate_controls_verified += 1
|
|
for psz, sym, _idx, _in_b, _ok, _mode, u_st, u_out, _rh, r_st, r_out in rows:
|
|
multistate_cases_verified += 1
|
|
st_name = cases[_idx][3]
|
|
status_mismatch = u_st != r_st
|
|
# Only compare output bytes on NV_OK (RMAPI server does not copy out on error unless COPYOUT_ON_ERROR).
|
|
bytes_mismatch = (u_st == 0 and r_st == 0 and psz > 0 and u_out != r_out)
|
|
if status_mismatch or bytes_mismatch:
|
|
entry = {
|
|
"control": hex(cid),
|
|
"symbol": sym,
|
|
"state": st_name,
|
|
"psz": psz,
|
|
"orig_status": hex(u_st),
|
|
"rust_status": hex(r_st),
|
|
}
|
|
if bytes_mismatch:
|
|
first_diff = next(
|
|
(i for i in range(min(len(u_out), len(r_out))) if u_out[i] != r_out[i]),
|
|
-1,
|
|
)
|
|
entry["first_diff_off"] = first_diff
|
|
if first_diff >= 0:
|
|
lo = max(0, first_diff - 4)
|
|
hi = min(psz, first_diff + 16)
|
|
entry["orig_slice"] = u_out[lo:hi].hex()
|
|
entry["rust_slice"] = r_out[lo:hi].hex()
|
|
parity_diffs.append(entry)
|
|
|
|
check_coverage = {
|
|
"name": "rm_controls_multistate_unicorn_coverage",
|
|
"passed": len(exec_diffs) == 0 and len(executed_controls) == len(all_methods),
|
|
"total_580_controls": len(all_methods),
|
|
"unique_controls_executed": len(executed_controls),
|
|
"coverage_pct": round(100.0 * len(executed_controls) / len(all_methods), 2),
|
|
"total_unicorn_cases": executed_cases,
|
|
"diffs": exec_diffs,
|
|
}
|
|
check_parity = {
|
|
"name": "rm_controls_multistate_rust_parity",
|
|
"passed": len(parity_diffs) == 0,
|
|
"multistate_controls_verified": multistate_controls_verified,
|
|
"multistate_cases_verified": multistate_cases_verified,
|
|
"diffs": parity_diffs if discover_only else parity_diffs[:100],
|
|
}
|
|
return [check_coverage, check_parity]
|
|
|
|
|
|
def main() -> int:
|
|
discover = "--discover" in sys.argv
|
|
checks = run_checks(discover_only=discover)
|
|
if discover:
|
|
out_path = ROOT / "target/multistate_discover.json"
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
out_path.write_text(json.dumps(checks, indent=2) + "\n")
|
|
c0, c1 = checks[0], checks[1]
|
|
print(
|
|
f"DISCOVER: coverage={c0['unique_controls_executed']}/{c0['total_580_controls']} "
|
|
f"cases={c0['total_unicorn_cases']} exec_fails={len(c0['diffs'])} | "
|
|
f"multistate_verified={c1['multistate_controls_verified']} controls "
|
|
f"({c1['multistate_cases_verified']} cases) parity_diffs={len(c1['diffs'])}"
|
|
)
|
|
return 0
|
|
print(json.dumps(checks, indent=2))
|
|
return 0 if all(c["passed"] for c in checks) else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|