Files
nvdriver/tools/_pf_rom_bit_dcb_elf.py

214 lines
7.3 KiB
Python

"""Pure-stdlib ELF64 and report-check helpers for PF ROM BIT and DCB oracle generators."""
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,
thunk_rax_addr: int,
) -> tuple[bytearray, bytes]:
"""Relocate selected .text spans with .text/.rodata/indirect_thunk_rax targets."""
symbols = parsed["symbols"]
syms = parsed["defined"]
text = bytearray(parsed["section_bytes"](".text"))
rodata = parsed["section_bytes"](".rodata")
tx = parsed["section_index"](".text")
rd = parsed["section_index"](".rodata")
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 sym["name"] == "__x86_indirect_thunk_rax":
value = thunk_rax_addr + addend
else:
require(
sym["st_shndx"] in (tx, rd),
f"unexpected section {(sym['name'], sym['st_shndx'])}",
)
value = (text_base if sym["st_shndx"] == tx else rodata_base) + sym["st_value"] + addend
if r_type == 2:
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 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