Files
nvdriver/tools/rmapi_binary_emulator.py

415 lines
16 KiB
Python

"""Loader and call machinery shared by the RM API instruction oracles.
The whole original object is mapped and relocated, so no callee is chosen by
hand. Undefined symbols (the open kernel interface layer) get one address each;
a harness installs fixtures on the ones its path reaches and every other one
raises. No hardware and no kernel are involved.
"""
import bisect
import hashlib
import os
from pathlib import Path
import struct
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
try:
from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc, UcError # noqa: E402
from unicorn.x86_const import ( # noqa: E402
UC_X86_REG_R8,
UC_X86_REG_R9,
UC_X86_REG_R10,
UC_X86_REG_R11,
UC_X86_REG_R12,
UC_X86_REG_R13,
UC_X86_REG_R14,
UC_X86_REG_R15,
UC_X86_REG_RAX,
UC_X86_REG_RBP,
UC_X86_REG_RBX,
UC_X86_REG_RCX,
UC_X86_REG_RDI,
UC_X86_REG_RDX,
UC_X86_REG_RIP,
UC_X86_REG_RSI,
UC_X86_REG_RSP,
)
_UNICORN_IMPORT_ERROR = None
ARGS = (
UC_X86_REG_RDI,
UC_X86_REG_RSI,
UC_X86_REG_RDX,
UC_X86_REG_RCX,
UC_X86_REG_R8,
UC_X86_REG_R9,
)
THUNKS = {
"rax": UC_X86_REG_RAX,
"rbx": UC_X86_REG_RBX,
"rcx": UC_X86_REG_RCX,
"rdx": UC_X86_REG_RDX,
"rsi": UC_X86_REG_RSI,
"rdi": UC_X86_REG_RDI,
"r8": UC_X86_REG_R8,
"r9": UC_X86_REG_R9,
"r10": UC_X86_REG_R10,
"r11": UC_X86_REG_R11,
"r12": UC_X86_REG_R12,
"r13": UC_X86_REG_R13,
"r14": UC_X86_REG_R14,
"r15": UC_X86_REG_R15,
}
except ImportError as _exc:
_UNICORN_IMPORT_ERROR = _exc
UC_ARCH_X86 = UC_HOOK_CODE = UC_MODE_64 = Uc = UcError = None
ARGS = ()
THUNKS = {}
ROOT = Path(__file__).resolve().parents[1]
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
SHT_NOBITS = 8
def _candidate_originals() -> list[Path]:
candidates: list[Path] = []
for var in ("NV_KERNEL_O_BINARY", "NV_RS_RM_OBJECT"):
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"),
]
)
return candidates
def _matches_digest(path: Path) -> bool:
try:
hasher = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1 << 20), b""):
hasher.update(chunk)
return hasher.hexdigest() == DIGEST
except OSError:
return False
def _resolve_original() -> Path:
for var in ("NV_KERNEL_O_BINARY", "NV_RS_RM_OBJECT"):
override = os.environ.get(var)
if override:
return Path(override).expanduser()
candidates = _candidate_originals()
first_existing = None
for path in candidates:
if not path.is_file():
continue
if first_existing is None:
first_existing = path
if _matches_digest(path):
return path
return first_existing or candidates[0]
def read_elf64_sections(raw: bytes) -> tuple[dict[str, int], dict[str, tuple[int, int, bytes]]]:
"""Parse ELF64 little-endian section headers using only stdlib `struct`.
Returns `(index_by_name, sections_by_name)` where each entry in
`sections_by_name` is `(sh_type, sh_size, data_bytes)`.
"""
if len(raw) < 64 or raw[:4] != b"\x7fELF" or raw[4] != 2 or raw[5] != 1:
raise ValueError("Not a little-endian ELF64 object")
e_shoff = struct.unpack_from("<Q", raw, 40)[0]
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", raw, 58)
if e_shoff == 0 or e_shentsize < 64:
raise ValueError("ELF64 object has no valid section header table")
if e_shoff + e_shentsize > len(raw):
raise ValueError("ELF64 section header table truncated")
sh0 = struct.unpack_from("<IIQQQQIIQQ", raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5] # sh_size
if e_shstrndx == 0xFFFF:
e_shstrndx = sh0[6] # sh_link
if e_shoff + e_shnum * e_shentsize > len(raw):
raise ValueError("ELF64 section header table exceeds file length")
if e_shstrndx >= e_shnum:
raise ValueError(f"Invalid ELF64 shstrndx {e_shstrndx} >= {e_shnum}")
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]
index_by_name: dict[str, int] = {}
sections_by_name: dict[str, tuple[int, int, bytes]] = {}
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")
index_by_name[name] = number
data = b"" if sh_type == SHT_NOBITS else raw[sh_offset : sh_offset + sh_size]
sections_by_name[name] = (sh_type, sh_size, data)
return index_by_name, sections_by_name
def read_elf64_section(path: Path, section_name: str) -> bytes:
"""Read a single named section from an ELF64 file without pyelftools."""
_, sections = read_elf64_sections(path.read_bytes())
if section_name not in sections:
raise KeyError(f"Section {section_name!r} not found in {path}")
return sections[section_name][2]
ORIGINAL = _resolve_original()
BASES = {".text": 0x10000000, ".data": 0x20000000, ".rodata": 0x30000000, ".bss": 0x38000000}
EXT, HEAP, STACK, STOP = 0x08000000, 0x40000000, 0x4c000000, 0x4d000000
HEAP_SIZE = 0xb000000
CONTINUE = STOP + 0x100
MASK = (1 << 64) - 1
class Emulator:
def __init__(self):
if _UNICORN_IMPORT_ERROR is not None:
raise RuntimeError(
"Unicorn (`unicorn`) is required to run Emulator"
) from _UNICORN_IMPORT_ERROR
raw = ORIGINAL.read_bytes()
got_digest = hashlib.sha256(raw).hexdigest()
if got_digest != DIGEST:
raise ValueError(
f"SHA-256 mismatch for {ORIGINAL}: expected {DIGEST}, got {got_digest}"
)
index, sec_map = read_elf64_sections(raw)
sections = {}
for name in BASES:
_stype, sh_size, data = sec_map[name]
sections[name] = bytearray(sh_size) if name == ".bss" else bytearray(data)
symbol_bytes = sec_map[".symtab"][2]
strings = sec_map[".strtab"][2]
relocations = {name: sec_map[".rela" + name][2] for name in (".text", ".data", ".rodata")}
section_base = {index[name]: base for name, base in BASES.items()}
symbols, self.by_name, self.externals, functions = [], {}, {}, []
for name_offset, info, _other, section, value, size in struct.iter_unpack(
"<IBBHQQ", symbol_bytes
):
name = strings[name_offset : strings.index(b"\0", name_offset)].decode()
address = None
if section == 0 and name:
address = self.externals.setdefault(
name, EXT + 0x100 + 16 * len(self.externals)
)
elif section in section_base:
address = section_base[section] + value
if name:
self.by_name[name] = address
if info & 15 == 2 and section == index[".text"]:
functions.append((address, size, name))
symbols.append(address)
functions.sort()
self.functions = functions
self.starts = [entry[0] for entry in functions]
self.entry_names = {}
for address, _size, name in functions:
# Prefer the primary symbol over a ".cold" partition at the same address.
if address not in self.entry_names or not name.endswith(".cold"):
self.entry_names[address] = name
for name, blob in relocations.items():
data, base = sections[name], BASES[name]
for offset, info, addend in struct.iter_unpack("<QQq", blob):
kind, target = info & 0xffffffff, symbols[info >> 32]
if target is None:
continue
if kind == 1:
struct.pack_into("<Q", data, offset, (target + addend) & MASK)
elif kind in (2, 4):
struct.pack_into("<i", data, offset, target + addend - (base + offset))
elif kind == 10:
struct.pack_into("<I", data, offset, target + addend)
elif kind == 11:
struct.pack_into("<i", data, offset, target + addend)
else:
raise ValueError(f"Unsupported x86_64 relocation kind {kind} in {name}")
self.cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for name, base in BASES.items():
self.cpu.mem_map(base, (len(sections[name]) + 0xfff) & ~0xfff)
self.cpu.mem_write(base, bytes(sections[name]))
for base, size in ((EXT, 0x10000), (HEAP, HEAP_SIZE), (STACK, 0x100000), (STOP, 0x1000)):
self.cpu.mem_map(base, size)
self.pristine = {name: bytes(sections[name]) for name in (".data", ".bss")}
self.heap = HEAP
self.calls = []
self.handlers = {}
self.continuations = []
for name, address in self.externals.items():
if name.startswith("__x86_indirect_thunk_"):
register = THUNKS[name.rsplit("_", 1)[1]]
self.cpu.hook_add(
UC_HOOK_CODE,
lambda emu, pc, size, register: emu.reg_write(
UC_X86_REG_RIP, emu.reg_read(register)
),
register,
begin=address,
end=address,
)
self.cpu.hook_add(UC_HOOK_CODE, self._unexpected, begin=EXT, end=EXT + 0x10000)
self.cpu.hook_add(UC_HOOK_CODE, self._resume, begin=CONTINUE, end=CONTINUE)
# Memory helpers.
def q(self, address):
return struct.unpack("<Q", self.cpu.mem_read(address, 8))[0]
def d(self, address):
return struct.unpack("<I", self.cpu.mem_read(address, 4))[0]
def b(self, address):
return self.cpu.mem_read(address, 1)[0]
def wq(self, address, value):
self.cpu.mem_write(address, struct.pack("<Q", value & MASK))
def wd(self, address, value):
self.cpu.mem_write(address, struct.pack("<I", value & 0xffffffff))
def wb(self, address, value):
self.cpu.mem_write(address, bytes([value & 0xff]))
def read(self, address, size):
return bytes(self.cpu.mem_read(address, size))
def write(self, address, data):
self.cpu.mem_write(address, bytes(data))
def text(self, address, limit=256):
return self.read(address, limit).split(b"\0")[0].decode(errors="replace")
def allocate(self, size, fill=0):
address = self.heap
next_heap = self.heap + ((size + 0x1f) & ~0xf)
if next_heap >= HEAP + HEAP_SIZE:
raise MemoryError("fixture heap exhausted")
self.heap = next_heap
self.cpu.mem_write(address, bytes([fill]) * size)
return address
def reset(self):
"""Restore .data and .bss and empty the fixture heap."""
for name, content in self.pristine.items():
self.cpu.mem_write(BASES[name], content)
self.heap = HEAP
self.calls.clear()
self.continuations.clear()
def function_at(self, address):
position = bisect.bisect_right(self.starts, address) - 1
if position >= 0:
start, size, name = self.functions[position]
if start <= address < start + max(size, 1):
return name
return None
# Control flow.
def leave(self, value=0):
rsp = self.cpu.reg_read(UC_X86_REG_RSP)
self.cpu.reg_write(UC_X86_REG_RSP, rsp + 8)
self.cpu.reg_write(UC_X86_REG_RAX, value & MASK)
self.cpu.reg_write(UC_X86_REG_RIP, self.q(rsp))
def call(self, target, *arguments, stack=()):
for register, argument in zip(ARGS, arguments):
self.cpu.reg_write(register, argument & MASK)
rsp = (STACK + 0xf0000 - 8 * len(stack)) & ~0xf
rsp -= 8
self.cpu.reg_write(UC_X86_REG_RSP, rsp)
# The object code keeps locals on a second stack addressed through RBP.
self.cpu.reg_write(UC_X86_REG_RBP, STACK + 0x80000)
self.wq(rsp, STOP)
for number, value in enumerate(stack):
self.wq(rsp + 8 + 8 * number, value)
start = target if isinstance(target, int) else self.by_name[target]
try:
self.cpu.emu_start(start, STOP)
except UcError as error:
pc = self.cpu.reg_read(UC_X86_REG_RIP)
raise RuntimeError(
f"{error} at {pc:#x} {self.function_at(pc)} after {self.calls[-16:]}"
) from error
rip = self.cpu.reg_read(UC_X86_REG_RIP)
if rip != STOP:
raise RuntimeError(
f"Execution of {target!r} stopped at {rip:#x} instead of STOP ({STOP:#x})"
)
return self.cpu.reg_read(UC_X86_REG_RAX)
def nested(self, target, arguments, after):
"""Enter an original function from a fixture and resume the caller afterwards."""
rsp = self.cpu.reg_read(UC_X86_REG_RSP) - 8
self.cpu.reg_write(UC_X86_REG_RSP, rsp)
self.wq(rsp, CONTINUE)
for register, argument in zip(ARGS, arguments):
self.cpu.reg_write(register, argument & MASK)
self.cpu.reg_write(
UC_X86_REG_RIP, target if isinstance(target, int) else self.by_name[target]
)
self.continuations.append(after)
def _resume(self, emu, pc, size, unused):
value = self.continuations.pop()(emu.reg_read(UC_X86_REG_RAX))
if value is not None:
self.leave(value)
def address_of(self, name):
return self.externals[name] if name in self.externals else self.by_name[name]
def install(self, name, handler):
"""Replace `name` (a symbol or an address) by a fixture taking the six register
arguments. Returning None means the fixture redirected control itself."""
address = name if isinstance(name, int) else self.address_of(name)
if not isinstance(name, int):
self.handlers[name] = handler
def run(emu, pc, size, unused):
value = handler([emu.reg_read(register) for register in ARGS])
if value is not None:
self.leave(value)
return self.cpu.hook_add(UC_HOOK_CODE, run, begin=address, end=address)
def stack_argument(self, number):
"""Argument `number` (0-based, after the six register arguments) inside a fixture."""
return self.q(self.cpu.reg_read(UC_X86_REG_RSP) + 8 + 8 * number)
def trace_calls(self):
def record(emu, address, size, unused):
name = self.entry_names.get(address)
if name:
self.calls.append(name)
del self.calls[:-256]
self.cpu.hook_add(
UC_HOOK_CODE, record, begin=BASES[".text"], end=BASES[".text"] + 0x8000000
)
def _unexpected(self, emu, address, size, unused):
for name, target in self.externals.items():
if target == address and name not in self.handlers and not name.startswith("__x86"):
raise AssertionError(f"unexpected external {name} after {self.calls[-12:]}")