"""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) from elftools.elf.elffile import ELFFile # noqa: E402 from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc, UcError # noqa: E402 from unicorn.x86_const import (UC_X86_REG_R8, UC_X86_REG_R9, UC_X86_REG_R10, # noqa: E402 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) ROOT = Path(__file__).resolve().parents[1] DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b" _DEFAULT_ORIGINALS = ( Path("/home/geodd/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"), ) 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: override = os.environ.get("NV_KERNEL_O_BINARY") if override: return Path(override) first_existing = None for path in _DEFAULT_ORIGINALS: if not path.is_file(): continue if first_existing is None: first_existing = path if _matches_digest(path): return path return first_existing or _DEFAULT_ORIGINALS[0] 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 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} MASK = (1 << 64) - 1 class Emulator: def __init__(self): raw = ORIGINAL.read_bytes() assert hashlib.sha256(raw).hexdigest() == DIGEST with ORIGINAL.open("rb") as stream: elf = ELFFile(stream) index = {section.name: number for number, section in enumerate(elf.iter_sections())} sections = {name: bytearray(elf.get_section_by_name(name).data()) if name != ".bss" else bytearray(elf.get_section_by_name(name)["sh_size"]) for name in BASES} symbol_bytes = elf.get_section_by_name(".symtab").data() strings = elf.get_section_by_name(".strtab").data() relocations = {name: elf.get_section_by_name(".rela" + name).data() 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( "> 32] if target is None: continue if kind == 1: struct.pack_into("= 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 assert self.cpu.reg_read(UC_X86_REG_RIP) == STOP, target 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:]}")