mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
266 lines
9.3 KiB
Python
266 lines
9.3 KiB
Python
"""Pure-stdlib ELF64 and report-check helpers for PF ROM source, cache, and ACPI oracles."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import warnings
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
|
|
|
|
def require(cond: bool, msg: str) -> None:
|
|
if not cond:
|
|
raise RuntimeError(msg)
|
|
|
|
|
|
def discover_rm_object(explicit: str | None = None) -> Path:
|
|
if explicit:
|
|
return Path(explicit).expanduser().resolve()
|
|
env_obj = os.environ.get("NV_RS_RM_OBJECT")
|
|
if env_obj:
|
|
return Path(env_obj).expanduser().resolve()
|
|
candidates: list[Path] = []
|
|
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 _canonical_json(obj) -> str:
|
|
normalized = json.loads(json.dumps(obj))
|
|
return json.dumps(normalized, sort_keys=True, separators=(",", ":"))
|
|
|
|
|
|
def write_or_check_json(path: Path, report: dict, check: bool, label: str) -> None:
|
|
if check:
|
|
if not path.is_file():
|
|
raise SystemExit(f"Missing {label}: {path}")
|
|
try:
|
|
existing = json.loads(path.read_text())
|
|
except json.JSONDecodeError as exc:
|
|
raise SystemExit(f"Invalid JSON in {label}: {path}: {exc}") from exc
|
|
if _canonical_json(existing) != _canonical_json(report):
|
|
raise SystemExit(f"{label} differs: {path}")
|
|
else:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(report, indent=2) + "\n")
|
|
|
|
|
|
def write_or_check_text(path: Path, text: str, check: bool, label: str) -> None:
|
|
if check:
|
|
if not path.is_file() or path.read_text() != text:
|
|
raise SystemExit(f"{label} differs: {path}")
|
|
else:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(text)
|
|
|
|
|
|
def parse_elf64_rm_object(rm_object: Path, *, verify_digest: bool = True) -> dict:
|
|
"""Parse an ELF64 little-endian relocatable RM object using Python stdlib only."""
|
|
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 verify_digest and digest != DIGEST:
|
|
raise SystemExit(f"SHA-256 mismatch for {rm_object}: expected {DIGEST}, got {digest}")
|
|
|
|
if len(raw) < 64 or raw[:4] != b"\x7fELF" or raw[4] != 2 or raw[5] != 1:
|
|
raise SystemExit(f"RM object is not a little-endian ELF64 file: {rm_object}")
|
|
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_hdr = headers[e_shstrndx]
|
|
shstr = raw[shstr_hdr[4] : shstr_hdr[4] + shstr_hdr[5]]
|
|
|
|
def _cstr(buf: bytes, off: int) -> str:
|
|
end = buf.index(0, off)
|
|
return buf[off:end].decode("utf-8", errors="replace")
|
|
|
|
sections: dict[str, tuple[int, tuple]] = {}
|
|
for idx, hdr in enumerate(headers):
|
|
sections[_cstr(shstr, hdr[0])] = (idx, hdr)
|
|
|
|
_, sym_hdr = sections[".symtab"]
|
|
str_hdr = headers[sym_hdr[6]]
|
|
strtab = raw[str_hdr[4] : str_hdr[4] + str_hdr[5]]
|
|
sym_entsize = sym_hdr[9] or 24
|
|
sym_count = sym_hdr[5] // sym_entsize
|
|
|
|
symbols: list[dict] = []
|
|
defined: dict[str, dict] = {}
|
|
for i in range(sym_count):
|
|
off = sym_hdr[4] + i * sym_entsize
|
|
st_name, st_info, _st_other, st_shndx, st_value, st_size = struct.unpack_from(
|
|
"<IBBHQQ", raw, off
|
|
)
|
|
name = _cstr(strtab, st_name) if st_name else ""
|
|
sym = {
|
|
"name": name,
|
|
"st_type": st_info & 0xF,
|
|
"st_shndx": st_shndx,
|
|
"st_value": st_value,
|
|
"st_size": st_size,
|
|
}
|
|
symbols.append(sym)
|
|
if name:
|
|
defined[name] = sym
|
|
|
|
def section_bytes(name: str) -> bytes:
|
|
_, hdr = sections[name]
|
|
return raw[hdr[4] : hdr[4] + hdr[5]]
|
|
|
|
def section_index(name: str) -> int:
|
|
return sections[name][0]
|
|
|
|
def iter_relocations(rela_name: str):
|
|
_, hdr = sections[rela_name]
|
|
entsize = hdr[9] or 24
|
|
count = hdr[5] // entsize
|
|
for i in range(count):
|
|
r_offset, r_info, r_addend = struct.unpack_from(
|
|
"<QQq", raw, hdr[4] + i * entsize
|
|
)
|
|
yield r_offset, (r_info >> 32), (r_info & 0xFFFFFFFF), r_addend
|
|
|
|
return {
|
|
"digest": digest,
|
|
"symbols": symbols,
|
|
"defined": defined,
|
|
"section_bytes": section_bytes,
|
|
"section_index": section_index,
|
|
"iter_relocations": iter_relocations,
|
|
}
|
|
|
|
|
|
def link_rom_functions(
|
|
parsed: dict,
|
|
names: list[str],
|
|
*,
|
|
text_base: int,
|
|
rodata_base: int,
|
|
bss_base: int = 0x70000000,
|
|
data_base: int | None = None,
|
|
thunk_rax_addr: int,
|
|
acpi_method_addr: int | None = None,
|
|
) -> tuple[bytearray, bytes]:
|
|
"""Relocate selected .text spans with .text/.rodata/.bss/(optional .data) and hooks."""
|
|
symbols = parsed["symbols"]
|
|
syms = parsed["defined"]
|
|
text = bytearray(parsed["section_bytes"](".text"))
|
|
rodata = parsed["section_bytes"](".rodata")
|
|
section_bases = {
|
|
parsed["section_index"](".text"): text_base,
|
|
parsed["section_index"](".rodata"): rodata_base,
|
|
parsed["section_index"](".bss"): bss_base,
|
|
}
|
|
if data_base is not None:
|
|
section_bases[parsed["section_index"](".data")] = data_base
|
|
spans = [(syms[n]["st_value"], syms[n]["st_size"]) for n in names]
|
|
|
|
for off, sym_idx, r_type, addend in parsed["iter_relocations"](".rela.text"):
|
|
if not any(a <= off < a + size for a, size in spans):
|
|
continue
|
|
sym = symbols[sym_idx]
|
|
if acpi_method_addr is not None and sym["name"] == "nv_acpi_rom_method":
|
|
value = acpi_method_addr + addend
|
|
elif sym["name"] == "__x86_indirect_thunk_rax":
|
|
value = thunk_rax_addr + addend
|
|
else:
|
|
require(
|
|
sym["st_shndx"] in section_bases,
|
|
f"unexpected section {(sym['name'], sym['st_shndx'])}",
|
|
)
|
|
value = section_bases[sym["st_shndx"]] + sym["st_value"] + addend
|
|
if r_type in (2, 4):
|
|
value -= text_base + off
|
|
else:
|
|
require(r_type == 11, f"unexpected relocation type {r_type}")
|
|
struct.pack_into("<i", text, off, value)
|
|
return text, rodata
|
|
|
|
|
|
def fnv64(content: bytes) -> int:
|
|
result = 0xCBF29CE484222325
|
|
for value in content:
|
|
result = ((result ^ value) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF
|
|
return result
|
|
|
|
|
|
def build_sample_rom_image(kind: int) -> bytearray | bytes | None:
|
|
if kind == 0:
|
|
return None
|
|
if kind == 1:
|
|
return b""
|
|
data = bytearray(512 if kind != 7 else 0x80001)
|
|
struct.pack_into("<H", data, 0, 0xAA55)
|
|
struct.pack_into("<H", data, 0x18, 0x40)
|
|
struct.pack_into("<II", data, 0x40, 0x52494350, 0x1DB510DE)
|
|
data[0x4F] = 3
|
|
data[0x50] = 1
|
|
data[0x55] = 0x80
|
|
if kind != 5:
|
|
data[0x80:0x8C] = bytes([0xFF, 0xB8, ord("B"), ord("I"), ord("T"), 0, 0, 0, 12, 8, 2, 0])
|
|
data[0x8B] = (-sum(data[0x80:0x8B])) & 255
|
|
struct.pack_into("<BBHI", data, 0x8C, ord("B"), 1, 22, 0x100)
|
|
struct.pack_into("<BBHI", data, 0x94, ord("i"), 1, 11, 0x180)
|
|
struct.pack_into("<I", data, 0x100, 0x12340001)
|
|
struct.pack_into("<I", data, 0x180, 0x12340002)
|
|
struct.pack_into("<H", data, 0x36, 0x1A0)
|
|
data[0x1A0:0x1A4] = bytes([0x40, 23, 5, 8])
|
|
struct.pack_into("<I", data, 0x1A6, 0x4EDCBDCB if kind != 4 else 0x12345678)
|
|
if kind == 6:
|
|
struct.pack_into("<H", data, 0, 0x1234)
|
|
data[511] = (-sum(data[:511]) + (1 if kind == 3 else 0)) & 255
|
|
if kind in (8, 9):
|
|
prefix = bytearray(16)
|
|
struct.pack_into("<III", prefix, 0, 0x4947564E, 0x80100, 0)
|
|
struct.pack_into("<I", prefix, 12, 16)
|
|
data = prefix + data
|
|
if kind == 9:
|
|
struct.pack_into("<H", data, 16, 0x1234)
|
|
return data
|
|
|
|
|
|
def require_unicorn():
|
|
warnings.filterwarnings("ignore", category=UserWarning, module="unicorn")
|
|
try:
|
|
import unicorn
|
|
from unicorn import x86_const
|
|
except ImportError as exc:
|
|
raise SystemExit(
|
|
f"Unicorn Python bindings are required to execute this binary oracle: {exc}"
|
|
) from exc
|
|
return unicorn, x86_const
|