mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
472 lines
18 KiB
Python
472 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""Whole original059665/059564 and Linux049822 CPU-instruction differential vectors."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import warnings
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SHA = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
TEXT, RO, DATA, STACK, STUB, STOP = (
|
|
0x10000000,
|
|
0x18000000,
|
|
0x30000000,
|
|
0x40000000,
|
|
0x50000000,
|
|
0x60000000,
|
|
)
|
|
TARGET_NAMES = ["_nv059665rm", "_nv059564rm", "_nv049822rm"]
|
|
|
|
|
|
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, sec_data[".text"], sec_data[".rodata"], symbols, rela_text
|
|
|
|
|
|
def load_relocated_timer_state_load(rm_object: Path):
|
|
"""Verify SHA-256 and relocate StateLoad/OS-relative timer functions without 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()
|
|
got = hashlib.sha256(raw).hexdigest()
|
|
if got != SHA:
|
|
raise SystemExit(f"SHA-256 mismatch for {rm_object}: expected {SHA}, got {got}")
|
|
|
|
idx_by_name, text_bytes, ro, symbols, rela_text = _parse_elf64(raw)
|
|
ti = idx_by_name[".text"]
|
|
ri = idx_by_name[".rodata"]
|
|
syms = {name: (shndx, val, size) for name, shndx, val, size in symbols if name}
|
|
text = bytearray(text_bytes)
|
|
spans = [(syms[n][1], syms[n][2]) for n in TARGET_NAMES]
|
|
external = {}
|
|
for off, r_info, r_addend in rela_text:
|
|
if not any(a <= off < a + n for a, n in spans):
|
|
continue
|
|
sym_name, sym_shndx, sym_val, _ssize = symbols[r_info >> 32]
|
|
if sym_shndx == ti:
|
|
target = TEXT + sym_val
|
|
elif sym_shndx == ri:
|
|
target = RO + sym_val
|
|
elif sym_shndx == 0:
|
|
target = external.setdefault(sym_name, STUB + 0x100 + 16 * len(external))
|
|
else:
|
|
raise SystemExit(f"Unexpected relocation section for {sym_name!r}: {sym_shndx}")
|
|
value = target + r_addend
|
|
kind = r_info & 0xFFFFFFFF
|
|
if kind not in (2, 4, 11):
|
|
raise SystemExit(f"Unexpected relocation kind {kind} at {off:#x}")
|
|
if kind in (2, 4):
|
|
value -= TEXT + off
|
|
struct.pack_into("<i", text, off, value)
|
|
return syms, external, bytes(text), ro
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Run or verify timer StateLoad differential Unicorn vectors."
|
|
)
|
|
parser.add_argument("--rm-object", type=Path, default=None)
|
|
parser.add_argument("--check", action="store_true")
|
|
args = parser.parse_args(argv)
|
|
|
|
rm_object = _discover_rm_object(args.rm_object)
|
|
syms, external, text, ro = load_relocated_timer_state_load(rm_object)
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning, module="unicorn")
|
|
try:
|
|
from unicorn import (
|
|
UC_ARCH_X86,
|
|
UC_HOOK_CODE,
|
|
UC_HOOK_MEM_READ,
|
|
UC_HOOK_MEM_WRITE,
|
|
UC_MODE_64,
|
|
Uc,
|
|
)
|
|
from unicorn import x86_const as x86
|
|
except ImportError as exc:
|
|
raise SystemExit("Unicorn (`unicorn`) is required to run timer-state-load-oracle") from exc
|
|
|
|
u = Uc(UC_ARCH_X86, UC_MODE_64)
|
|
for addr, size in (
|
|
(TEXT, len(text)),
|
|
(RO, len(ro)),
|
|
(DATA, 0x50000),
|
|
(STACK, 0x10000),
|
|
(STUB, 0x10000),
|
|
(STOP, 4096),
|
|
):
|
|
u.mem_map(addr, (size + 4095) & ~4095)
|
|
u.mem_write(TEXT, text)
|
|
u.mem_write(RO, ro)
|
|
|
|
def address(n):
|
|
return TEXT + syms[n][1]
|
|
|
|
def w32(a, v):
|
|
u.mem_write(a, struct.pack("<I", v))
|
|
|
|
def w64(a, v):
|
|
u.mem_write(a, struct.pack("<Q", v))
|
|
|
|
def r32(a):
|
|
return int.from_bytes(u.mem_read(a, 4), "little")
|
|
|
|
def r64(a):
|
|
return int.from_bytes(u.mem_read(a, 8), "little")
|
|
|
|
def ret(value):
|
|
rsp = u.reg_read(x86.UC_X86_REG_RSP)
|
|
rip = r64(rsp)
|
|
u.reg_write(x86.UC_X86_REG_RSP, rsp + 8)
|
|
u.reg_write(x86.UC_X86_REG_RAX, value)
|
|
u.reg_write(x86.UC_X86_REG_RIP, rip)
|
|
|
|
gpu, timer, event, alarm = DATA, DATA + 0x10000, DATA + 0x20000, DATA + 0x30000
|
|
pending_a, pending_c, enable_a, enable_c = (
|
|
STUB + 0x8000,
|
|
STUB + 0x8010,
|
|
STUB + 0x8020,
|
|
STUB + 0x8030,
|
|
)
|
|
inverse = {v: k for k, v in external.items()}
|
|
periods = [0, 1, 0x8000000000000000, 0xFFFFFFFFFFFFFFFF]
|
|
state = {
|
|
"events": [],
|
|
"variant": 0,
|
|
"scripted": 0,
|
|
"linux": True,
|
|
"now_calls": 0,
|
|
"current_node": 0,
|
|
}
|
|
|
|
def node(a):
|
|
return (a - event) // 0x100 + 1 if event <= a < event + 0x300 else 0
|
|
|
|
def nodeptr(n):
|
|
return event + (n - 1) * 0x100 if n else 0
|
|
|
|
def alarmptr(n):
|
|
return alarm + (n - 1) * 0x100 if n else 0
|
|
|
|
def alarmid(a):
|
|
return (a - alarm) // 0x100 + 1 if alarm <= a < alarm + 0x200 else 0
|
|
|
|
def snapshot():
|
|
return [
|
|
v
|
|
for i in range(3)
|
|
for v in (
|
|
r32(event + i * 0x100 + 0x18),
|
|
r64(event + i * 0x100 + 0x40),
|
|
node(r64(event + i * 0x100 + 0x48)),
|
|
)
|
|
]
|
|
|
|
def start_effects(n, delay):
|
|
state["current_node"] = n
|
|
state["events"].append([9, n, delay])
|
|
ptr = nodeptr(n)
|
|
w32(ptr + 0x18, 0x5A5A0 + n)
|
|
if n == 1:
|
|
mode = (state["variant"] >> 2) % 3
|
|
if mode == 1:
|
|
w64(ptr + 0x48, 0)
|
|
if mode == 2:
|
|
w64(ptr + 0x48, nodeptr(3))
|
|
if state["variant"] & 64:
|
|
w64(nodeptr(2) + 0x10, 0)
|
|
return state["scripted"]
|
|
|
|
def code(_, pc, size, user):
|
|
if pc in inverse:
|
|
name = inverse[pc]
|
|
if name.startswith("__x86_indirect_thunk_"):
|
|
reg_id = getattr(x86, "UC_X86_REG_" + name.rsplit("_", 1)[-1].upper())
|
|
u.reg_write(x86.UC_X86_REG_RIP, u.reg_read(reg_id))
|
|
elif name == "nv_start_nano_timer":
|
|
if u.reg_read(x86.UC_X86_REG_RDI) != DATA + 0x48000:
|
|
raise RuntimeError("Unexpected RDI in nv_start_nano_timer")
|
|
n = node(u.reg_read(x86.UC_X86_REG_RSI) - 0x5000)
|
|
if n not in (1, 2, 3):
|
|
raise RuntimeError(f"Unexpected node id {n} in nv_start_nano_timer")
|
|
ret(start_effects(n, u.reg_read(x86.UC_X86_REG_RDX)))
|
|
else:
|
|
raise RuntimeError(f"Unexpected external {name}")
|
|
elif pc == address("_nv049086rm"):
|
|
ret(gpu)
|
|
elif pc == address("_nv005245rm"):
|
|
state["events"].append([7, 0, 0])
|
|
ret(gpu)
|
|
elif pc == address("_nv049665rm"):
|
|
value = 0x1234567800000000 + state["now_calls"] * 1000
|
|
state["now_calls"] += 1
|
|
state["events"].append([5, 0, value])
|
|
ret(value)
|
|
elif pc == address("_nv049822rm") and not state["linux"]:
|
|
n = node(u.reg_read(x86.UC_X86_REG_RSI) - 0x5000)
|
|
ret(start_effects(n, u.reg_read(x86.UC_X86_REG_RDX)))
|
|
elif pc in (pending_a, pending_c):
|
|
if u.reg_read(x86.UC_X86_REG_RDX) != 0:
|
|
raise RuntimeError("Unexpected non-zero RDX in pending check")
|
|
pending = [0, 1, 0x100, 0x101, 0x80000000, 0xFF][state["variant"] % 6]
|
|
state["events"].append([2, int(pc == pending_c), pending])
|
|
mutation = (state["variant"] >> 4) % 3
|
|
if mutation == 1:
|
|
w64(timer + 0x250, 0)
|
|
elif mutation == 2:
|
|
w64(timer + 0x250, alarmptr(2))
|
|
if state["variant"] & 32:
|
|
w64(timer + 0x258, nodeptr(3))
|
|
if state["variant"] & 64:
|
|
u.mem_write(timer + 0x248, bytes([0 if r32(timer + 0x248) & 255 else 1]))
|
|
ret(pending)
|
|
elif pc == address("_nv016384rm"):
|
|
state["events"].append([4, 0, u.reg_read(x86.UC_X86_REG_RDX)])
|
|
if state["variant"] & 128:
|
|
u.mem_write(timer + 0x248, bytes([0 if r32(timer + 0x248) & 255 else 1]))
|
|
ret(0x65) # executed rearm's return is ignored by 059665
|
|
elif pc in (enable_a, enable_c):
|
|
state["events"].append([6, int(pc == enable_c), 0])
|
|
ret(0x65)
|
|
elif pc == address("_nv047869rm"):
|
|
which = u.reg_read(x86.UC_X86_REG_RSI)
|
|
if which not in (0x740000, 0x7D0000):
|
|
raise RuntimeError(f"Unexpected diagnostic {which:#x}")
|
|
state["events"].append([12, int(which == 0x7D0000), state["scripted"] if which == 0x7D0000 else 0])
|
|
ret(0)
|
|
|
|
def memory_read(_, access, a, size, value, user):
|
|
if a == timer + 0x250:
|
|
state["events"].append([0, 0, alarmid(r64(a))])
|
|
elif a == timer + 0x258:
|
|
state["events"].append([1, 0, node(r64(a))])
|
|
elif a == timer + 0x248:
|
|
state["events"].append([3, 0, u.mem_read(a, 1)[0]])
|
|
elif alarm <= a < alarm + 0x200 and (a - alarm) % 0x100 == 0x38:
|
|
state["events"].append([13, alarmid(a - 0x38), r64(a)])
|
|
elif event <= a < event + 0x300:
|
|
n = node(a)
|
|
off = (a - event) % 0x100
|
|
if off == 0x38:
|
|
state["events"].append([14, n, r64(a)])
|
|
elif off == 0x10:
|
|
state["events"].append([8, n, int(r64(a) != 0)])
|
|
elif off == 0x18:
|
|
state["events"].append([10, n, r32(a)])
|
|
elif off == 0x48:
|
|
state["events"].append([15, n, node(r64(a))])
|
|
|
|
def memory_write(_, access, a, size, value, user):
|
|
if event <= a < event + 0x300:
|
|
n = node(a)
|
|
off = (a - event) % 0x100
|
|
if off == 0x40:
|
|
state["events"].append([16, n, value])
|
|
elif off == 0x18:
|
|
state["events"].append([11, n, value & 0xFFFFFFFF])
|
|
|
|
u.hook_add(UC_HOOK_CODE, code)
|
|
u.hook_add(UC_HOOK_MEM_READ, memory_read)
|
|
u.hook_add(UC_HOOK_MEM_WRITE, memory_write)
|
|
|
|
def prepare(v, s, is_linux):
|
|
state["variant"] = v
|
|
state["scripted"] = s
|
|
state["linux"] = is_linux
|
|
state["events"] = []
|
|
state["now_calls"] = 0
|
|
u.mem_write(DATA, bytes(0x50000))
|
|
w64(gpu + 0x9D8, DATA + 0x48000)
|
|
for off, ptr in (
|
|
(0x1E8, pending_a),
|
|
(0x208, pending_c),
|
|
(0x1A0, enable_a),
|
|
(0x1F8, enable_c),
|
|
):
|
|
w64(timer + off, ptr)
|
|
w64(timer + 0x250, alarmptr(1) if v & 1 else 0)
|
|
w64(timer + 0x258, nodeptr(1) if (v >> 1) % 3 else 0)
|
|
u.mem_write(timer + 0x248, bytes([255 if v & 8 else 0]))
|
|
w64(alarm + 0x38, 0x123400001234)
|
|
w64(alarm + 0x100 + 0x38, 0x987600009876)
|
|
for n in (1, 2, 3):
|
|
ptr = nodeptr(n)
|
|
w64(ptr + 0x10, ptr + 0x5000 if (v + n) % 5 else 0)
|
|
w32(ptr + 0x18, 0x100 * n + 0x21)
|
|
w64(ptr + 0x38, periods[(v + n) % 4])
|
|
w64(ptr + 0x40, 0xDEAD0000 + n)
|
|
w64(ptr + 0x48, nodeptr(2) if n == 1 and (v >> 1) % 3 == 2 else 0)
|
|
|
|
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_RSI,
|
|
x86.UC_X86_REG_RDI,
|
|
x86.UC_X86_REG_R8,
|
|
x86.UC_X86_REG_R9,
|
|
x86.UC_X86_REG_R12,
|
|
x86.UC_X86_REG_R13,
|
|
x86.UC_X86_REG_R14,
|
|
x86.UC_X86_REG_R15,
|
|
]
|
|
|
|
def call(name, params):
|
|
for reg in clear_regs:
|
|
u.reg_write(reg, 0)
|
|
for reg, val in zip((x86.UC_X86_REG_RDI, x86.UC_X86_REG_RSI, x86.UC_X86_REG_RDX), params):
|
|
u.reg_write(reg, val)
|
|
w64(STACK + 0xFF00, STOP)
|
|
u.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFF00)
|
|
u.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
|
|
u.emu_start(address(name), STOP, count=100000)
|
|
if u.reg_read(x86.UC_X86_REG_RIP) != STOP:
|
|
raise SystemExit(f"Execution of {name} did not reach STOP")
|
|
return u.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF
|
|
|
|
cases = []
|
|
for v in range(256):
|
|
for is_linux in (False, True):
|
|
prepare(v, 0x65, is_linux)
|
|
status = call("_nv059665rm", [gpu, timer, 0xA5A5A5A5])
|
|
if status != 0:
|
|
raise SystemExit(f"Expected status 0 for StateLoad variant {v}, got {status:#x}")
|
|
cases.append(dict(spec=[v, int(is_linux)], ops=state["events"], after=snapshot()))
|
|
|
|
helpers = []
|
|
for present in (False, True):
|
|
for delay in periods:
|
|
for status in (0, 0x65):
|
|
for is_linux in (False, True):
|
|
prepare(0, status, is_linux)
|
|
w64(event + 0x10, event + 0x5000 if present else 0)
|
|
result = call("_nv059564rm", [timer, event, delay])
|
|
helpers.append(
|
|
dict(
|
|
spec=[int(present), delay, status, int(is_linux)],
|
|
status=result,
|
|
ops=state["events"],
|
|
after=snapshot(),
|
|
)
|
|
)
|
|
|
|
lines = [
|
|
"// Whole original059665/059564, actualLinux049822 wrapper or explicit injected helper status.",
|
|
"const LOAD_CASES:&[LoadCase]=&[",
|
|
]
|
|
for c in cases:
|
|
lines.append(
|
|
"LoadCase{spec:"
|
|
+ str(c["spec"])
|
|
+ ",ops:&["
|
|
+ ",".join("(" + ",".join(map(str, x)) + ")" for x in c["ops"])
|
|
+ "],after:"
|
|
+ str(c["after"])
|
|
+ "},"
|
|
)
|
|
lines += ["];", "const HELPER_CASES:&[HelperCase]=&["]
|
|
for c in helpers:
|
|
lines.append(
|
|
"HelperCase{spec:"
|
|
+ str(c["spec"])
|
|
+ ",status:"
|
|
+ str(c["status"])
|
|
+ ",ops:&["
|
|
+ ",".join("(" + ",".join(map(str, x)) + ")" for x in c["ops"])
|
|
+ "],after:"
|
|
+ str(c["after"])
|
|
+ "},"
|
|
)
|
|
lines.append("];")
|
|
generated = "\n".join(lines) + "\n"
|
|
out = ROOT / "src/nvidia/src/gpu/timer/load_vectors.rs"
|
|
report = dict(
|
|
artifact_sha256=SHA,
|
|
load_cases=cases,
|
|
helper_cases=helpers,
|
|
scope="Whole original059665/059564 and actual Linux049822 wrapper. Hardware pending/rearm/enable, parent lookup, clock and OS timer primitive modeled; injected helper-return mode separately exercises original nonLinux/generic executed failure policy. No actual callbacks/GPU/event handles fabricated in production.",
|
|
)
|
|
report_path = ROOT / "reports/timer-state-load-oracle.json"
|
|
if args.check:
|
|
if not out.is_file() or out.read_text() != generated:
|
|
raise SystemExit("timer StateLoad vectors differ")
|
|
if not report_path.is_file() or json.loads(report_path.read_text()) != report:
|
|
raise SystemExit("timer StateLoad oracle report differs")
|
|
else:
|
|
out.write_text(generated)
|
|
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
|
print(len(cases), "whole original StateLoad,", len(helpers), "OS-relative cases")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|