#!/usr/bin/env python3 """Run the original GV100 KernelBus InitLocked BAR2 bring-up and write an oracle. Executed original code: the kernel half of KernelBus InitLocked, _nv039592rm (called by the class body _nv039595rm before KernelBus+110 _nv039594rm), with everything it calls directly or through the function tables the original binders fill in: the default PRAMIN window (KernelBus+3e0 _nv039556rm), BAR2 initialization _nv039463rm (+1d0 CPU aperture _nv039563rm, +140 GPU VA space _nv039566rm, +178 commit _nv039325rm), the page-level walker (_nv046237rm create, _nv046252rm reserve, _nv046260rm sparsify, _nv046247rm map) with the BAR2 walker callbacks of table _nv029065rm (_nv012114rm level allocation, _nv012116rm root update, _nv012117rm directory entry, _nv012113rm fill), the instance block writer (+428 _nv039472rm), the PRAMIN accessor _nv039504rm, the bind _nv039307rm, the aperture update _nv039638rm with its entry callback _nv013924rm, the flush _nv039553rm/_nv018613rm and _nv039391rm/_nv039387rm, the invalidate _nv040843rm with _nv040639rm, _nv040663rm and _nv040941rm, the flush pointer setup _nv039577rm and the BAR2 test _nv039656rm. The reserved-memory placement of the page levels, _nv044075rm, runs first and supplies the relative directory and table offsets. The whole object file is loaded and relocated, so no callee is selected by hand; the KernelBus, KernelGmmu, MemoryManager, KernelMemorySystem and OBJBUS tables come from running their original binders with chip HAL 0x23 and RM HAL 2, and the page-table format from the original constructor steps (_nv040763rm, _nv040773rm, the KernelGmmu functions at +1c0, +1a8, +1a0, +188, _nv040782rm and +1c8). Fixture-supplied: register access (_nv053907rm, _nv053912rm) backed by a model of the PRAMIN window and of framebuffer words, the BAR2 CPU mapping (translated through the page tables the original just wrote), allocation, memory fill and copy, diagnostics, the timeout functions (_nv059509rm start, _nv059505rm check, _nv059492rm thread reset), the multi-GPU loop helpers (_nv031390rm, _nv031395rm, _nv031424rm, _nv031426rm, _nv031478rm, _nv031482rm), the calling-context query _nv060459rm, the device ownership helper _nv014074rm, the PCI mapping _nv049745rm, framebuffer allocation _nv043691rm (the address is a case input), descriptor release, the level-2 cache service _nv041683rm, and the places that enter the BAR2 mapping cache: _nv044028rm and _nv043739rm (map) become a call of the original aperture update _nv039638rm with the address the public mapping code would pick (persistent mappings top down below the last page of the RM aperture, others bottom up); _nv043773rm (unmap) becomes a write-combine flush and the original flush of KernelBus+4a8; _nv043699rm (descriptor destruction) releases the cached test mapping with the original aperture update in sparsify mode. The order of these BAR2 accesses equals the full physical trace of the V100. The teardown register tail is taken from _nv039604rm separately. No hardware is involved. """ import bisect import hashlib import json 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_HOOK_MEM_READ, UC_HOOK_MEM_WRITE, # noqa: E402 UC_MEM_WRITE, UC_MODE_64, Uc) 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] ORIGINAL = Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary") DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b" TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt" BASES = {".text": 0x10000000, ".data": 0x20000000, ".rodata": 0x30000000, ".bss": 0x38000000} EXT, HEAP, OBJ, STACK, STOP, BAR2 = (0x08000000, 0x40000000, 0x48000000, 0x4c000000, 0x4d000000, 0x60000000) HEAP_SIZE, OBJ_SIZE, BAR2_SIZE = 0x4000000, 0x100000, 0x2000000 (GPU, BUS, MMU, MEMMGR, KMEMSYS, CHIP, RM, OBUS, DMA, CONFIG) = ( OBJ, OBJ + 0x10000, OBJ + 0x20000, OBJ + 0x30000, OBJ + 0x40000, OBJ + 0x50000, OBJ + 0x51000, OBJ + 0x60000, OBJ + 0x70000, OBJ + 0x80000) CONTINUE, GPU_1A0 = STOP + 0x100, STOP + 0x200 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, "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} # Functions the fixture replaces; everything else that runs is original code. HOOKED = ("_nv053907rm", "_nv053912rm", "_nv047869rm", "_nv046745rm", "_nv046747rm", "_nv047868rm", "_nv047867rm", "_nv046764rm", "_nv052687rm", "_nv052701rm", "_nv060459rm", "_nv060458rm", "_nv014074rm", "_nv059509rm", "_nv059505rm", "_nv059492rm", "_nv031390rm", "_nv031395rm", "_nv031424rm", "_nv031426rm", "_nv031478rm", "_nv031482rm", "_nv049745rm", "_nv043691rm", "_nv043704rm", "_nv043699rm", "_nv041683rm", "_nv044028rm", "_nv043739rm", "_nv043773rm", "_nv039358rm") # Slots the bring-up dispatches through, checked against the bindings report. EXPECTED = {"KernelBus": {"0x110": "_nv039594rm", "0x138": "_nv039638rm", "0x140": "_nv039566rm", "0x150": "_nv039447rm", "0x158": "_nv039445rm", "0x160": "_nv039455rm", "0x178": "_nv039325rm", "0x1c0": "_nv039577rm", "0x1d0": "_nv039563rm", "0x1d8": "_nv039604rm", "0x3e0": "_nv039556rm", "0x3e8": "_nv039394rm", "0x3f0": "_nv039562rm", "0x3f8": "_nv039541rm", "0x400": "_nv039463rm", "0x408": "_nv039656rm", "0x418": "_nv039307rm", "0x428": "_nv039472rm"}, "KernelGmmu": {"0x160": "_nv040639rm", "0x168": "_nv040663rm", "0x170": "_nv040941rm"}, "OBJBUS": {"0x268": "_nv018613rm"}} raw = ORIGINAL.read_bytes() assert hashlib.sha256(raw).hexdigest() == DIGEST bindings = json.loads((ROOT / "reports/gv100-engine-hal-bindings.json").read_text()) assert bindings["original_sha256"] == DIGEST tables = {entry["class_label"]: entry["hal_slots"] for entry in bindings["classes"]} for label, slots in EXPECTED.items(): for slot, function in slots.items(): assert tables[label][slot]["function"] == function, (label, slot) 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, by_name, 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 = functions[position] if start <= address < start + max(size, 1): return name return None cpu = Uc(UC_ARCH_X86, UC_MODE_64) for name, base in BASES.items(): cpu.mem_map(base, (len(sections[name]) + 0xfff) & ~0xfff) cpu.mem_write(base, bytes(sections[name])) for base, size in ((EXT, 0x10000), (HEAP, HEAP_SIZE), (OBJ, OBJ_SIZE), (STACK, 0x100000), (STOP, 0x1000), (BAR2, BAR2_SIZE)): cpu.mem_map(base, size) executed = set() state = {} def q(address): return struct.unpack("> 12) * 8, 0) assert entry & 1, hex(offset) return ((entry >> 8) << 12) + (offset & 0xfff) def pop(name, default): values = state["case"][name] return values.pop(0) if values else default def read_register(a): assert (a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0) offset = a[3] & 0xffffffff if offset == 0x1700: value = state["window"] elif offset == 0x1714: value = state["bar2_block"] elif offset == 0x1710: value = pop("bind", 0) elif offset == 0x70000: value = pop("flush", 0) elif offset == 0x100c80: value = pop("mmu", 0x208001) else: assert 0x700000 <= offset < 0x800000, hex(offset) value = state["fb"].get(((state["window"] & 0xffffff) << 16) + offset - 0x700000, 0) state["pramin_reads"] += 1 if state["pramin_reads"] == state["case"]["corrupt_pramin"]: value ^= 0x100 emit(f"r:{offset:x}:{value:x}") return value def write_register(a): assert (a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0) offset, value = a[3] & 0xffffffff, a[4] & 0xffffffff if offset == 0x1700: state["window"] = value elif offset == 0x1714: state["bar2_block"] = value elif 0x700000 <= offset < 0x800000: state["fb"][((state["window"] & 0xffffff) << 16) + offset - 0x700000] = value else: assert offset in (0x70000, 0x100cb8, 0x100cec, 0x100cbc), hex(offset) emit(f"w:{offset:x}:{value:x}") return 0 def bar2_access(emu, access, address, size, value, unused): offset = address - BAR2 assert size == 4, (hex(offset), size) if access == UC_MEM_WRITE: state["fb"][translate(offset)] = value & 0xffffffff emit(f"W:{offset:x}:{value & 0xffffffff:x}") else: value = state["fb"].get(translate(offset), 0) state["bar2_reads"] += 1 if state["bar2_reads"] == state["case"]["corrupt_bar2"]: value ^= 0x100 cpu.mem_write(address, struct.pack("> 16 & 0xffff:x}") return 0 def context(a): wd(a[1], 0) return 0 def next_gpu(a): position = d(a[1]) while position < 32 and not (a[0] & 0xffffffff) >> position & 1: position += 1 if position >= 32: return 0 wd(a[1], position + 1) return GPU def timeout_start(a): assert a[0] == GPU + 0x1e08 emit(f"ts:{a[3] & 0xffffffff:x}") return 0 def timeout_check(a): assert a[0] == GPU + 0x1e08 status = pop("check", 0) emit(f"tc:{a[2] & 0xffffffff:x}:{status:x}") return status def thread_reset(a): emit("tr") return 0 def map_pci(a): assert (a[0], a[4]) == (GPU, BUS + 0x7c48) emit(f"m:{a[1]:x}:{a[2]:x}") wq(a[4], BAR2) return 0 def descriptor_size(descriptor): return (q(descriptor + 0x30) + 0xfff) & ~0xfff def framebuffer_allocate(a): address = state["case"]["pages"].pop(0) emit(f"a:{address:x}") nested("_nv043698rm", [a[0], 2, address, q(a[0] + 0x30)], lambda unused: 0) def map_descriptor(descriptor, flags): size = descriptor_size(descriptor) if flags & 8: state["top"] -= size address = state["top"] else: address = state["bottom"] state["bottom"] += size state["mapped"][descriptor] = (address, size) emit(f"v:{address:x}:{size:x}") nested(q(BUS + 0x138), [GPU, BUS, descriptor, address, size, 1], lambda status: BAR2 + address if status & 0xffffffff == 0 else 0) def unmap_descriptor(a): """_nv043773rm with flags 0: write-combine flush, the mapping stays cached, then the original flush of KernelBus+4a8 with the aperture flag of _nv039418rm.""" assert a[2] & 0xffffffff == 0 emit("f") state["cached"].add(a[1]) nested("_nv039418rm", [BUS, 2], lambda flag: nested( q(BUS + 0x4a8), [GPU, BUS, flag & 0xffffffff], lambda unused: 0)) def destroy_descriptor(a): """Releasing a cached mapping when its descriptor goes away: sparse entry and invalidate.""" if a[0] not in state["cached"]: return 0 state["cached"].remove(a[0]) address, size = state["mapped"].pop(a[0]) nested(q(BUS + 0x138), [GPU, BUS, a[0], address, size, 5], lambda unused: 0) return None def cache_service(a): emit(f"L:{a[2] & 0xffffffff:x}") return 0 def destroy(a): emit("D") return 0 HANDLERS = { "_nv053907rm": read_register, "_nv053912rm": write_register, "_nv047869rm": diagnostic, "_nv046745rm": lambda a: 0, "_nv046747rm": lambda a: 0, "_nv047868rm": diagnostic, "_nv047867rm": diagnostic, "_nv046764rm": lambda a: emit(f"e:x{a[1] & 0xffffffff:x}") or 0, "_nv052687rm": lambda a: allocate(a[0], 0xcc), "_nv052701rm": lambda a: 0, "_nv060459rm": context, "_nv060458rm": lambda a: 0, "_nv014074rm": lambda a: 0, "_nv059509rm": timeout_start, "_nv059505rm": timeout_check, "_nv059492rm": thread_reset, "_nv031390rm": lambda a: 0, "_nv031395rm": lambda a: 1, "_nv031424rm": next_gpu, "_nv031426rm": lambda a: GPU, "_nv031478rm": lambda a: 0, "_nv031482rm": lambda a: 0, "_nv049745rm": map_pci, "_nv043691rm": framebuffer_allocate, "_nv043704rm": lambda a: 0, "_nv043699rm": destroy_descriptor, "_nv041683rm": cache_service, "_nv044028rm": lambda a: map_descriptor(a[1], a[2]), "_nv043739rm": lambda a: map_descriptor(a[1], a[2]), "_nv043773rm": unmap_descriptor, "_nv039358rm": destroy, "os_mem_set": fill, "os_mem_copy": copy, "os_flush_cpu_write_combine_buffer": lambda a: emit("f") or 0, } assert set(HOOKED) <= set(HANDLERS) def install(address, handler): def run(emu, pc, size, unused): value = handler([emu.reg_read(register) for register in ARGS]) if value is not None: leave(value) cpu.hook_add(UC_HOOK_CODE, run, begin=address, end=address) for name, handler in HANDLERS.items(): install(externals[name] if name in externals else by_name[name], handler) for name, address in externals.items(): if name.startswith("__x86_indirect_thunk_"): register = THUNKS[name.rsplit("_", 1)[1]] 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) def resume(emu, pc, size, unused): # A continuation either returns the hooked function's result or chains another call. value = state["continuations"].pop()(emu.reg_read(UC_X86_REG_RAX)) if value is not None: leave(value) cpu.hook_add(UC_HOOK_CODE, resume, begin=CONTINUE, end=CONTINUE) install(GPU_1A0, lambda a: emit("g") or 0) cpu.hook_add(UC_HOOK_MEM_READ | UC_HOOK_MEM_WRITE, bar2_access, begin=BAR2, end=BAR2 + BAR2_SIZE - 1) def record_function(emu, address, size, unused): name = function_at(address) if name and address == by_name.get(name): executed.add(name) def unexpected(emu, address, size, unused): for name, target in externals.items(): if target == address and name not in HANDLERS and not name.startswith("__x86"): raise AssertionError("unexpected external " + name) cpu.hook_add(UC_HOOK_CODE, unexpected, begin=EXT, end=EXT + 0x10000) cpu.mem_write(CHIP + 0x10, struct.pack("