"""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(" len(raw): raise ValueError("ELF64 section header table truncated") sh0 = struct.unpack_from(" 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(" 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( "> 32] if target is None: continue if kind == 1: struct.pack_into("= 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:]}")