mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
238 lines
9.7 KiB
Python
238 lines
9.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Run original GR HAL selection in private CPU RAM; never access hardware."""
|
|
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, STOP = 0x10000000, 0x18000000, 0x30000000, 0x40000000, 0x50000000
|
|
PARTS = ["_nv005883rm", "_nv005886rm", "_nv005887rm", "_nv005888rm", "_nv005889rm", "_nv005890rm"]
|
|
|
|
|
|
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, info, 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_gr_hal(rm_object: Path):
|
|
"""Verify SHA-256 and relocate the 6 GR HAL selection 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)
|
|
text_idx = idx_by_name[".text"]
|
|
ro_idx = idx_by_name[".rodata"]
|
|
syms = {name: (shndx, val, size) for name, _info, shndx, val, size in symbols if name}
|
|
text = bytearray(text_bytes)
|
|
start = syms["_nv005883rm"][1]
|
|
spans = [(syms[n][1], syms[n][1] + syms[n][2]) for n in PARTS]
|
|
maps = {text_idx: TEXT, ro_idx: RO}
|
|
names = {
|
|
TEXT + val: name
|
|
for name, info, shndx, val, _size in symbols
|
|
if shndx == text_idx and (info & 0xF) == 2
|
|
}
|
|
for off, r_info, r_addend in rela_text:
|
|
if not any(a <= off < b for a, b in spans):
|
|
continue
|
|
sym_name, _sinfo, sym_shndx, sym_val, _ssize = symbols[r_info >> 32]
|
|
kind = r_info & 0xFFFFFFFF
|
|
if sym_shndx not in maps:
|
|
raise SystemExit(f"Unexpected relocation section for {sym_name!r}: {sym_shndx}")
|
|
value = maps[sym_shndx] + sym_val + r_addend
|
|
if kind in (2, 4):
|
|
value -= TEXT + off
|
|
if kind == 1:
|
|
struct.pack_into("<Q", text, off, value & ((1 << 64) - 1))
|
|
elif kind in (2, 4, 10, 11):
|
|
struct.pack_into("<I", text, off, value & 0xFFFFFFFF)
|
|
else:
|
|
raise SystemExit(f"Unsupported relocation kind {kind} at {off:#x}")
|
|
return start, spans, bytes(text), ro, names
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Run or verify original GR HAL selection in private Unicorn RAM."
|
|
)
|
|
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)
|
|
start, spans, text, ro, names = load_relocated_gr_hal(rm_object)
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning, module="unicorn")
|
|
try:
|
|
from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc
|
|
from unicorn.x86_const import (
|
|
UC_X86_REG_RDI,
|
|
UC_X86_REG_RDX,
|
|
UC_X86_REG_RIP,
|
|
UC_X86_REG_RSI,
|
|
UC_X86_REG_RSP,
|
|
)
|
|
except ImportError as exc:
|
|
raise SystemExit("Unicorn (`unicorn`) is required to run GR HAL selection") from exc
|
|
|
|
uc = Uc(UC_ARCH_X86, UC_MODE_64)
|
|
for base, size in [(TEXT, len(text)), (RO, len(ro)), (DATA, 0x10000), (STACK, 0x10000), (STOP, 4096)]:
|
|
uc.mem_map(base, (size + 4095) & ~4095)
|
|
uc.mem_write(TEXT, text)
|
|
uc.mem_write(RO, ro)
|
|
obj, runtime, chip = DATA, DATA + 0x8000, DATA + 0x9000
|
|
|
|
def guard(emu, address, size, user):
|
|
if address != STOP and not any(TEXT + a <= address < TEXT + b for a, b in spans):
|
|
raise RuntimeError(f"Execution escaped GR HAL selection spans at {address:#x}")
|
|
|
|
uc.hook_add(UC_HOOK_CODE, guard)
|
|
rows = []
|
|
for fill in (0, 0xA5):
|
|
uc.mem_write(DATA, bytes([fill]) * 0x10000)
|
|
# Same factor encoding used by the selected GV100 physical-PF legacy graph.
|
|
uc.mem_write(runtime, bytes(0x1000))
|
|
uc.mem_write(chip, bytes(0x1000))
|
|
uc.mem_write(runtime + 0x10, struct.pack("<H", 3))
|
|
uc.mem_write(chip + 0x10, struct.pack("<H", 35))
|
|
uc.mem_write(STACK + 0xFFF8, struct.pack("<Q", STOP))
|
|
for reg, value in (
|
|
(UC_X86_REG_RDI, obj),
|
|
(UC_X86_REG_RSI, runtime),
|
|
(UC_X86_REG_RDX, chip),
|
|
(UC_X86_REG_RSP, STACK + 0xFFF8),
|
|
):
|
|
uc.reg_write(reg, value)
|
|
uc.emu_start(TEXT + start, STOP, count=20000)
|
|
if uc.reg_read(UC_X86_REG_RIP) != STOP:
|
|
raise SystemExit("GR HAL selection did not reach STOP")
|
|
data = bytes(uc.mem_read(obj, 0x45F8))
|
|
selected = []
|
|
for offset in range(0, len(data) - 7, 8):
|
|
address = struct.unpack_from("<Q", data, offset)[0]
|
|
if address in names:
|
|
selected.append(
|
|
{
|
|
"offset": hex(offset),
|
|
"symbol": names[address],
|
|
"ELF_text_offset": hex(address - TEXT),
|
|
}
|
|
)
|
|
rows.append(
|
|
{
|
|
"initial_fill": hex(fill),
|
|
"methods": selected,
|
|
"result_sha256": hashlib.sha256(data).hexdigest(),
|
|
}
|
|
)
|
|
if rows[0]["methods"] != rows[1]["methods"]:
|
|
raise SystemExit("Selected GR HAL methods varied with initial object fill")
|
|
if len(rows[0]["methods"]) != 633:
|
|
raise SystemExit(f"Expected 633 selected GR HAL methods, got {len(rows[0]['methods'])}")
|
|
|
|
evidence = json.loads((ROOT / "reports/native-gr-bindings-complete-rea/index.json").read_text())
|
|
report = {
|
|
"scope": "Actual original005883 plus005886/887/888/889/890 HAL setter execution in Unicorn private RAM. Parameter factor codes runtime3/chip35. Selected methods only; no GR object ownership, hardware initialization, context execution or Rust parity proved.",
|
|
"artifact_sha256": SHA,
|
|
"REA_evidence": [r for r in evidence if r["name"] in PARTS],
|
|
"original_executions": len(rows),
|
|
"actual_function_invocations": len(rows) * len(PARTS),
|
|
"actual_functions": PARTS,
|
|
"selected_method_count": len(rows[0]["methods"]),
|
|
"cases": rows,
|
|
}
|
|
report_path = ROOT / "reports/native-gr-hal-selection.json"
|
|
if args.check:
|
|
if not report_path.is_file() or json.loads(report_path.read_text()) != report:
|
|
raise SystemExit(f"GR HAL selection report differs: {report_path}")
|
|
else:
|
|
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"original_executions": len(rows),
|
|
"actual_function_invocations": len(rows) * len(PARTS),
|
|
"actual_functions": PARTS,
|
|
"selected_method_count": len(rows[0]["methods"]),
|
|
}
|
|
)
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|