mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
434 lines
16 KiB
Python
434 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""Execute selected original timer instructions under Unicorn with scripted MMIO.
|
|
No native target, driver or GPU execution. Regenerates independent Rust vectors.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import warnings
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
TEXT, DATA, STACK, STUB, STOP = 0x10000000, 0x30000000, 0x40000000, 0x50000000, 0x60000000
|
|
TARGET_NAMES = ["_nv016384rm", "_nv059642rm", "_nv059655rm", "_nv030927rm", "_nv059578rm", "_nv059579rm"]
|
|
HOOK_NAMES = ["_nv053912rm", "_nv047869rm", "_nv049086rm", "_nv005245rm"]
|
|
|
|
|
|
def _discover_rm_object(explicit=None) -> Path:
|
|
if explicit is not None:
|
|
return Path(explicit).expanduser().resolve()
|
|
candidates = []
|
|
for var in ("NV_RS_RM_OBJECT", "NV_KERNEL_O_BINARY"):
|
|
val = os.environ.get(var)
|
|
if val:
|
|
candidates.append(Path(val).expanduser())
|
|
env_kernel = os.environ.get("NV_RS_KERNEL_SRC")
|
|
if env_kernel:
|
|
candidates.append(Path(env_kernel).expanduser() / "nvidia/nv-kernel.o_binary")
|
|
env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT")
|
|
if env_analysis:
|
|
candidates.append(
|
|
Path(env_analysis).expanduser() / "extracted/kernel/nvidia/nv-kernel.o_binary"
|
|
)
|
|
candidates.extend(
|
|
[
|
|
Path.home()
|
|
/ "nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary",
|
|
Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary"),
|
|
Path("/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary"),
|
|
]
|
|
)
|
|
for cand in candidates:
|
|
if cand.is_file():
|
|
return cand.resolve()
|
|
return candidates[0].resolve()
|
|
|
|
|
|
def _parse_elf64(raw: bytes):
|
|
if len(raw) < 64 or raw[:4] != b"\x7fELF" or raw[4] != 2 or raw[5] != 1:
|
|
raise SystemExit("RM object is not a little-endian ELF64 file")
|
|
e_shoff = struct.unpack_from("<Q", raw, 40)[0]
|
|
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", raw, 58)
|
|
sh0 = struct.unpack_from("<IIQQQQIIQQ", raw, e_shoff)
|
|
if e_shnum == 0:
|
|
e_shnum = sh0[5]
|
|
if e_shstrndx == 0xFFFF:
|
|
e_shstrndx = sh0[6]
|
|
headers = [
|
|
struct.unpack_from("<IIQQQQIIQQ", raw, e_shoff + i * e_shentsize)
|
|
for i in range(e_shnum)
|
|
]
|
|
_, _, _, _, shstr_off, shstr_size, _, _, _, _ = headers[e_shstrndx]
|
|
shstr = raw[shstr_off : shstr_off + shstr_size]
|
|
idx_by_name = {}
|
|
sec_data = {}
|
|
for number, hdr in enumerate(headers):
|
|
sh_name, sh_type, _flags, _addr, sh_offset, sh_size, *_rest = hdr
|
|
end = shstr.find(b"\0", sh_name)
|
|
name = shstr[sh_name : end if end != -1 else len(shstr)].decode("utf-8", errors="replace")
|
|
idx_by_name[name] = number
|
|
sec_data[name] = b"" if sh_type == 8 else raw[sh_offset : sh_offset + sh_size]
|
|
strtab = sec_data[".strtab"]
|
|
symbols = []
|
|
for name_off, _info, _other, shndx, value, size in struct.iter_unpack(
|
|
"<IBBHQQ", sec_data[".symtab"]
|
|
):
|
|
end = strtab.find(b"\0", name_off)
|
|
name = strtab[name_off : end if end != -1 else len(strtab)].decode("utf-8", errors="replace")
|
|
symbols.append((name, shndx, value, size))
|
|
rela_text = list(struct.iter_unpack("<QQq", sec_data[".rela.text"]))
|
|
return idx_by_name[".text"], sec_data[".text"], symbols, rela_text
|
|
|
|
|
|
def load_relocated_timer_alarm(rm_object: Path):
|
|
"""Relocate the 6 timer alarm functions using stdlib ELF64 (no pyelftools)."""
|
|
if not rm_object.is_file():
|
|
raise SystemExit(
|
|
f"Missing 580.178.04 nv-kernel.o_binary: {rm_object} "
|
|
"(set NV_RS_RM_OBJECT, NV_RS_KERNEL_SRC, NV_RS_ANALYSIS_ROOT, or --rm-object)"
|
|
)
|
|
raw = rm_object.read_bytes()
|
|
digest = hashlib.sha256(raw).hexdigest()
|
|
if digest != DIGEST:
|
|
raise SystemExit(f"SHA-256 mismatch for {rm_object}: expected {DIGEST}, got {digest}")
|
|
|
|
text_index, text_bytes, symbols, rela_text = _parse_elf64(raw)
|
|
defined = {name: (shndx, val, size) for name, shndx, val, size in symbols if name}
|
|
text = bytearray(text_bytes)
|
|
functions = {name: (defined[name][1], defined[name][2]) for name in TARGET_NAMES}
|
|
undefined = {}
|
|
hooks = {}
|
|
for off, r_info, r_addend in rela_text:
|
|
if not any(start <= off < start + size for start, size in functions.values()):
|
|
continue
|
|
sym_name, sym_shndx, sym_val, _ssize = symbols[r_info >> 32]
|
|
kind = r_info & 0xFFFFFFFF
|
|
if sym_shndx == text_index:
|
|
target = TEXT + sym_val
|
|
elif sym_shndx == 0:
|
|
target = undefined.setdefault(sym_name, STUB + 0x100 + len(undefined) * 16)
|
|
hooks[target] = sym_name
|
|
else:
|
|
target = STUB + 0x8000
|
|
if kind not in (2, 4, 11):
|
|
raise SystemExit(f"Unexpected relocation kind {kind} at {off:#x} ({sym_name})")
|
|
value = target + r_addend - (TEXT + off) if kind in (2, 4) else target + r_addend
|
|
struct.pack_into("<i", text, off, value)
|
|
for name in HOOK_NAMES:
|
|
hooks[TEXT + defined[name][1]] = name
|
|
return digest, defined, functions, hooks, bytes(text)
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Run or verify timer alarm/schedule/countdown Unicorn vectors."
|
|
)
|
|
parser.add_argument("--rm-object", type=Path, default=None)
|
|
parser.add_argument("--check", action="store_true")
|
|
options = parser.parse_args(argv)
|
|
|
|
rm_object = _discover_rm_object(options.rm_object)
|
|
digest, defined, functions, hooks, text = load_relocated_timer_alarm(rm_object)
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning, module="unicorn")
|
|
try:
|
|
from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_HOOK_MEM_READ, UC_MODE_64, Uc
|
|
from unicorn import x86_const as x86
|
|
except ImportError as exc:
|
|
raise SystemExit("Unicorn (`unicorn`) is required to run timer-alarm-oracle") from exc
|
|
|
|
uc = Uc(UC_ARCH_X86, UC_MODE_64)
|
|
for address, size in (
|
|
(TEXT, (len(text) + 4095) & ~4095),
|
|
(DATA, 0x30000),
|
|
(STACK, 0x10000),
|
|
(STUB, 0x10000),
|
|
(STOP, 4096),
|
|
):
|
|
uc.mem_map(address, size)
|
|
uc.mem_write(TEXT, text)
|
|
hooks[STUB + 0x10] = "clock_leaf"
|
|
hooks[STUB + 0x20] = "pending_leaf"
|
|
|
|
def put(offset, value):
|
|
uc.mem_write(DATA + offset, struct.pack("<Q", value))
|
|
|
|
def ret(value):
|
|
sp = uc.reg_read(x86.UC_X86_REG_RSP)
|
|
target = struct.unpack("<Q", uc.mem_read(sp, 8))[0]
|
|
uc.reg_write(x86.UC_X86_REG_RAX, value)
|
|
uc.reg_write(x86.UC_X86_REG_RSP, sp + 8)
|
|
uc.reg_write(x86.UC_X86_REG_RIP, target)
|
|
|
|
gpu, timer = DATA, DATA + 0x10000
|
|
cases = []
|
|
|
|
def case(
|
|
kind="alarm",
|
|
deadline=100,
|
|
flags=0,
|
|
gpu908=0,
|
|
disabled=0,
|
|
countdown=0,
|
|
policy="valid",
|
|
times=None,
|
|
pending=None,
|
|
):
|
|
return dict(
|
|
kind=kind,
|
|
deadline=deadline,
|
|
flags=flags,
|
|
gpu908=gpu908,
|
|
disabled=disabled,
|
|
countdown=countdown,
|
|
policy=policy,
|
|
times=times or [0],
|
|
pending=pending or [0],
|
|
)
|
|
|
|
for attempts in range(1, 25):
|
|
cases.append(case(times=[i * 1000000000000 + 100 for i in range(attempts - 1)] + [0]))
|
|
cases.append(
|
|
case(
|
|
kind="schedule",
|
|
times=[i * 1000000000000 + 100 for i in range(attempts)],
|
|
pending=[0] * (attempts - 1) + [1],
|
|
)
|
|
)
|
|
for access in (0, 1, 0xFF, 0x100, 0x8000, 0xFFFF00, 0xFF000000, 0xFFFFFFFF):
|
|
for kind in ("alarm", "schedule", "countdown"):
|
|
cases.append(
|
|
case(
|
|
kind=kind,
|
|
gpu908=access,
|
|
deadline=0x1234567887654321,
|
|
flags=0x9876543210,
|
|
times=[0],
|
|
)
|
|
)
|
|
for value, now in (
|
|
(0, 0),
|
|
(1, 0),
|
|
(1, 1),
|
|
(1, 2),
|
|
(0x100000010, 0xFFFFFFF0),
|
|
(0x200000010, 1),
|
|
(0xFFFFFFFFFFFFFFFF, 0),
|
|
(0, 0xFFFFFFFFFFFFFFFF),
|
|
(0xFFFFFFFFFFFFFFF0, 0xFFFFFFFFFFFFFFF1),
|
|
):
|
|
for policy in ("valid", "not_loaded", "inaccessible"):
|
|
cases.append(
|
|
case(kind="schedule", countdown=1, deadline=value, times=[now], policy=policy)
|
|
)
|
|
for disabled in (1, 255):
|
|
for countdown in (0, 1, 255):
|
|
cases.append(
|
|
case(
|
|
kind="schedule",
|
|
disabled=disabled,
|
|
countdown=countdown,
|
|
gpu908=0xFFFF00,
|
|
deadline=0xFFFFFFFFFFFFFFFF,
|
|
)
|
|
)
|
|
for flags in (0, 1, 0x100000001, 0xFFFFFFFFFFFFFFFF):
|
|
for delta in (0, 1, 0xFFFFFFFF):
|
|
cases.append(case(kind="countdown", deadline=delta, flags=flags))
|
|
for deadline in (0, 0xFFFFFFFFFFFFFFF0, 0xFFFFFFFFFFFFFFFF):
|
|
cases.append(case(deadline=deadline, times=[0xFFFFFFFFFFFFFFFF] * 24, pending=[0]))
|
|
for policy in ("not_loaded", "inaccessible"):
|
|
for countdown in (0, 1):
|
|
cases.append(
|
|
case(kind="schedule", countdown=countdown, policy=policy, deadline=50, times=[0])
|
|
)
|
|
# A late timestamp then a noncanonical pending byte; caller tests AL only.
|
|
cases.append(case(times=[100], pending=[255]))
|
|
|
|
state = {
|
|
"events": [],
|
|
"time_index": 0,
|
|
"pending_index": 0,
|
|
"returns": {},
|
|
"current": None,
|
|
"visited": set(),
|
|
}
|
|
|
|
def on_code(emu, address, size, user):
|
|
if address == STOP:
|
|
emu.emu_stop()
|
|
return
|
|
if address in state["returns"]:
|
|
out = state["returns"].pop(address)
|
|
value = struct.unpack("<Q", emu.mem_read(out, 8))[0]
|
|
status = emu.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF
|
|
state["events"].append(["time", value, status])
|
|
if address == TEXT + defined["_nv030927rm"][1]:
|
|
state["events"].append(["access", state["current"]["gpu908"]])
|
|
if address == TEXT + defined["_nv059578rm"][1]:
|
|
sp = emu.reg_read(x86.UC_X86_REG_RSP)
|
|
state["returns"][struct.unpack("<Q", emu.mem_read(sp, 8))[0]] = emu.reg_read(
|
|
x86.UC_X86_REG_RSI
|
|
)
|
|
for fname, (start, _length) in functions.items():
|
|
if address == TEXT + start:
|
|
state["visited"].add(fname)
|
|
name = hooks.get(address)
|
|
if name is None:
|
|
return
|
|
if name == "__x86_indirect_thunk_rax":
|
|
emu.reg_write(x86.UC_X86_REG_RIP, emu.reg_read(x86.UC_X86_REG_RAX))
|
|
return
|
|
if name in ("_nv049086rm", "_nv005245rm"):
|
|
ret(gpu)
|
|
return
|
|
if name == "clock_leaf":
|
|
if emu.reg_read(x86.UC_X86_REG_RDX) != 0:
|
|
raise RuntimeError("Unexpected non-zero RDX in clock_leaf")
|
|
values = state["current"]["times"]
|
|
value = values[min(state["time_index"], len(values) - 1)]
|
|
state["time_index"] += 1
|
|
ret(value)
|
|
return
|
|
if name == "pending_leaf":
|
|
if emu.reg_read(x86.UC_X86_REG_RDX) != 0:
|
|
raise RuntimeError("Unexpected non-zero RDX in pending_leaf")
|
|
values = state["current"]["pending"]
|
|
value = values[min(state["pending_index"], len(values) - 1)]
|
|
state["pending_index"] += 1
|
|
state["events"].append(["pending", value & 255])
|
|
ret(value)
|
|
return
|
|
if name == "_nv053912rm":
|
|
if emu.reg_read(x86.UC_X86_REG_RDI) != gpu + 0x4120:
|
|
raise RuntimeError("Unexpected RDI in _nv053912rm")
|
|
if emu.reg_read(x86.UC_X86_REG_RSI) != 0 or emu.reg_read(x86.UC_X86_REG_RDX) != 0:
|
|
raise RuntimeError("Unexpected RSI/RDX in _nv053912rm")
|
|
state["events"].append(
|
|
[
|
|
"write",
|
|
emu.reg_read(x86.UC_X86_REG_RCX),
|
|
emu.reg_read(x86.UC_X86_REG_R8) & 0xFFFFFFFF,
|
|
emu.reg_read(x86.UC_X86_REG_R9),
|
|
]
|
|
)
|
|
ret(0)
|
|
return
|
|
if name == "_nv047869rm":
|
|
code = emu.reg_read(x86.UC_X86_REG_RSI)
|
|
if code not in (0x8D0000, 0xAF0000):
|
|
raise RuntimeError(f"Unexpected diagnostic code {code:#x}")
|
|
state["events"].append(["diagnostic", 1 if code == 0x8D0000 else 2])
|
|
ret(0)
|
|
return
|
|
raise RuntimeError("Unexpected " + name)
|
|
|
|
def memory_read(emu, access, address, size, value, user):
|
|
if address in (timer + 0x248, timer + 0x24C):
|
|
state["events"].append(
|
|
["flag", address - timer, int.from_bytes(emu.mem_read(address, size), "little")]
|
|
)
|
|
|
|
uc.hook_add(UC_HOOK_CODE, on_code)
|
|
uc.hook_add(UC_HOOK_MEM_READ, memory_read)
|
|
rows = []
|
|
clear_regs = [
|
|
x86.UC_X86_REG_RAX,
|
|
x86.UC_X86_REG_RBX,
|
|
x86.UC_X86_REG_RCX,
|
|
x86.UC_X86_REG_RDX,
|
|
x86.UC_X86_REG_R8,
|
|
x86.UC_X86_REG_R9,
|
|
x86.UC_X86_REG_R10,
|
|
x86.UC_X86_REG_R11,
|
|
x86.UC_X86_REG_R12,
|
|
x86.UC_X86_REG_R13,
|
|
x86.UC_X86_REG_R14,
|
|
x86.UC_X86_REG_R15,
|
|
]
|
|
arg_regs = [
|
|
x86.UC_X86_REG_RDI,
|
|
x86.UC_X86_REG_RSI,
|
|
x86.UC_X86_REG_RDX,
|
|
x86.UC_X86_REG_RCX,
|
|
x86.UC_X86_REG_R8,
|
|
]
|
|
for index, current in enumerate(cases):
|
|
state["current"] = current
|
|
uc.mem_write(DATA, bytes(0x30000))
|
|
uc.mem_write(STACK, bytes(0x10000))
|
|
put(0x10000 + 0x1B8, STUB + 0x10)
|
|
put(0x10000 + 0x1E8, STUB + 0x20)
|
|
put(0x10000 + 0x1E0, TEXT + defined["_nv059642rm"][1])
|
|
put(0x10000 + 0x210, TEXT + defined["_nv059655rm"][1])
|
|
uc.mem_write(timer + 0x24C, bytes([current["disabled"]]))
|
|
uc.mem_write(timer + 0x248, bytes([current["countdown"]]))
|
|
uc.mem_write(gpu + 0x908, struct.pack("<I", current["gpu908"]))
|
|
uc.mem_write(gpu + 0x915, b"\1")
|
|
if current["policy"] == "not_loaded":
|
|
uc.mem_write(gpu + 0x915, b"\0")
|
|
if current["policy"] == "inaccessible":
|
|
uc.mem_write(gpu + 0x917, b"\1")
|
|
for reg in clear_regs:
|
|
uc.reg_write(reg, 0)
|
|
kind = current["kind"]
|
|
name = {"alarm": "_nv059642rm", "schedule": "_nv016384rm", "countdown": "_nv059655rm"}[kind]
|
|
call_args = [gpu, timer, current["deadline"]]
|
|
if kind == "alarm":
|
|
call_args.append(current["flags"])
|
|
if kind == "countdown":
|
|
call_args += [0, current["flags"]]
|
|
for reg, value in zip(arg_regs, call_args):
|
|
uc.reg_write(reg, value)
|
|
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFF8)
|
|
uc.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
|
|
uc.mem_write(STACK + 0xFFF8, struct.pack("<Q", STOP))
|
|
state["events"] = []
|
|
state["time_index"] = 0
|
|
state["pending_index"] = 0
|
|
state["returns"] = {}
|
|
state["visited"] = set()
|
|
uc.emu_start(TEXT + defined[name][1], STOP, count=100000)
|
|
if uc.reg_read(x86.UC_X86_REG_RIP) != STOP:
|
|
raise SystemExit(f"Timer alarm case {index} did not reach STOP")
|
|
rows.append(
|
|
{
|
|
"case": index,
|
|
"input": current,
|
|
"events": state["events"],
|
|
"status": None if kind == "schedule" else uc.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF,
|
|
"entered_original": sorted(state["visited"]),
|
|
}
|
|
)
|
|
|
|
report = {
|
|
"artifact_sha256": digest,
|
|
"cases": rows,
|
|
"case_count": len(rows),
|
|
"original_bodies": ["016384", "059642", "059655", "030927", "059578", "059579"],
|
|
"scripted_boundaries": [
|
|
"owner lookup/cast049086/005245",
|
|
"selectedrawclockmethod+1b8",
|
|
"selectedpendingmethod+1e8",
|
|
"053912MMIOwrite",
|
|
"diagnostics047869",
|
|
],
|
|
"physical_gpu_access": False,
|
|
}
|
|
dest = ROOT / "reports/timer-alarm-original.json"
|
|
data = json.dumps(report, indent=2) + "\n"
|
|
if options.check:
|
|
if not dest.is_file() or dest.read_text() != data:
|
|
raise SystemExit(f"Alarm original instruction vectors drift: {dest}")
|
|
else:
|
|
dest.write_text(data)
|
|
print(len(rows), "whole-original timer scheduling/alarm/countdown cases")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|