#!/usr/bin/env python3 """Run the original base GPU StatePostLoad pass _nv031219rm and write an oracle. Only _nv031219rm executes; it has no cold block. Every callee, including the allocator, the GPU iterator and every control, is fixture-supplied: the oracle records call order, arguments, the control parameter blocks and the GPU fields the pass writes. It proves the pass's control flow, not the behavior of any callee or engine. """ import hashlib import json from pathlib import Path import random import struct from capstone import CS_ARCH_X86, CS_MODE_64, Cs from elftools.elf.elffile import ELFFile from unicorn import UC_ARCH_X86, UC_HOOK_BLOCK, UC_HOOK_CODE, UC_MODE_64, Uc from unicorn.x86_const import ( UC_X86_REG_RAX, UC_X86_REG_RBP, UC_X86_REG_RCX, UC_X86_REG_RDI, UC_X86_REG_RDX, UC_X86_REG_RIP, UC_X86_REG_RSI, UC_X86_REG_RSP, UC_X86_REG_R8, UC_X86_REG_R9, ) 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" TEXT, DATA, STACK, STOP = 0x10000000, 0x30000000, 0x40000000, 0x50000000 GPU, OBJECT, DESCRIPTORS, ENGINES, VTABLE = DATA, DATA + 0x8000, DATA + 0x9000, DATA + 0xa000, \ DATA + 0xf000 HEAP, OTHERS = DATA + 0x10000, DATA + 0x40000 INDIRECT = STOP + 0x100 SLOTS = {name: STOP + 0x200 + 0x10 * index for index, name in enumerate( ("method", "postload", "ctrl", "reboot"))} HOOKED = ("_nv049674rm", "_nv030522rm", "_nv026840rm", "_nv026839rm", "_nv054117rm", "_nv054115rm", "_nv013524rm", "_nv036619rm", "_nv042363rm", "_nv052687rm", "_nv052701rm", "_nv052705rm", "_nv031400rm", "_nv031424rm", "_nv000117rm", "_nv042370rm", "_nv030360rm", "_nv031135rm", "_nv047869rm", "_nv046745rm", "_nv046747rm", "_nv046751rm", "_nv046752rm") TIME = 0x1111000011110001 CLIENT, SUBDEVICE, CA4, C9C = 0xc1d00001, 0xc1d00003, 0x4100, 3 MAX_PEERS = 34 assert hashlib.sha256(ORIGINAL.read_bytes()).hexdigest() == DIGEST with ORIGINAL.open("rb") as stream: elf = ELFFile(stream) symbols = list(elf.get_section_by_name(".symtab").iter_symbols()) by_name = {symbol.name: symbol for symbol in symbols} text = bytearray(elf.get_section_by_name(".text").data()) text_section = elf.get_section_index(".text") assert "_nv031219rm.cold" not in by_name RANGES = [(by_name[name]["st_value"], by_name[name]["st_value"] + by_name[name]["st_size"]) for name in ("_nv031219rm",)] for relocation in elf.get_section_by_name(".rela.text").iter_relocations(): offset = relocation["r_offset"] if not any(start <= offset < end for start, end in RANGES): continue kind = relocation["r_info_type"] target = symbols[relocation["r_info_sym"]] if target.name == "__x86_indirect_thunk_rax": address = INDIRECT else: assert target["st_shndx"] == text_section, target.name address = TEXT + target["st_value"] assert kind in (2, 4), kind struct.pack_into("> 12) & 0xf) + ((code >> 8) & 0xf) words = (code, low(c), low(d))[:1 + count] trace.append("d:" + ":".join(f"{word:x}" for word in words)) elif name == "_nv046745rm": trace.append(f"a:{low(a):x}") elif name == "_nv046747rm": trace.append(f"s:{low(a):x}:{low(b):x}") elif name == "_nv046751rm": trace.append(f"l:{low(a):x}:{low(b):x}") elif name == "_nv046752rm": trace.append(f"c:{low(a):x}:{low(b):x}:{low(c):x}") leave(emu, value) return run def control(a, b, c, d, e, f): """The GPU+4298 control of this GPU or of a listed GPU object.""" subject = a - 0x4260 identity = gpu_id(subject) assert (low(b), low(c)) == (read32(subject + 0x423c), read32(subject + 0x4244)) handles = f"{low(b):x}:{low(c):x}" command = low(d) if command == 0x2080400b: assert (identity, low(f)) == (0, 1) trace.append(f"vgpucfg:{handles}:{read8(e):x}") return case["svcfg"] if command == 0x2080013f: assert (identity, low(f), e) == (0, 0x88, read64(GPU + 0x4360)) assert heap[buffer(e) - 1] == 0x88 and bytes(cpu.mem_read(e, 0x88)) == bytes(0x88) trace.append(f"board:{handles}:{buffer(e):x}") return case["board"] if command == 0x20800ab5: assert low(f) == 0x504 and heap[buffer(e) - 1] == 0x504 count = read32(e) token = f"set:{identity:x}:{handles}:{buffer(e):x}:{count:x}" for slot in range(count): entry = e + 4 + 0x28 * slot words = [read32(entry + offset) for offset in (0, 4, 8, 0xc, 0x10, 0x20, 0x24)] status = bytes(cpu.mem_read(entry + 0x14, 9)).hex() assert bytes(cpu.mem_read(entry + 0x1d, 3)) == bytes(3) token += "/" + ":".join(f"{word:x}" for word in words[:5]) + f":{status}:" + \ ":".join(f"{word:x}" for word in words[5:]) rest = 4 + 0x28 * count assert bytes(cpu.mem_read(e + rest, 0x504 - rest)) == bytes(0x504 - rest) trace.append(token) return gpu_row(subject)[4] assert (command, low(f)) == (0x20800ab6, 0x84), hex(command) count = read32(e) rest = 4 + 4 * count assert bytes(cpu.mem_read(e + rest, 0x84 - rest)) == bytes(0x84 - rest) trace.append(f"remove:{identity:x}:{handles}:{count:x}:" + ":".join(f"{read32(e + 4 + 4 * slot):x}" for slot in range(count))) return gpu_row(subject)[5] def thunk(emu, address, size, unused): target = emu.reg_read(UC_X86_REG_RAX) name = next(name for name, slot in SLOTS.items() if slot == target) a, b, c, d, e, f = arguments(emu) if name == "method": assert (a, b, low(c)) == (GPU, OBJECT, 2) trace.append("method") value = case["s1d8"] elif name == "postload": assert a == GPU key = engine_key(b) trace.append(f"postload:{key:x}:{low(c):x}") value = descriptor_row(key)[2] last.update(key=key) elif name == "ctrl": value = control(a, b, c, d, e, f) else: assert a == GPU trace.append("reboot") value = case["reboot"] leave(emu, value) def visit(emu, address, size, unused): visited.add(address - TEXT) def block(emu, address, size, unused): offset = address - TEXT assert (address in ENTRIES or address in (INDIRECT, STOP) or any(start <= offset < end for start, end in RANGES)), hex(address) cpu.hook_add(UC_HOOK_BLOCK, block) for start, end in RANGES: cpu.hook_add(UC_HOOK_CODE, visit, begin=TEXT + start, end=TEXT + end - 1) cpu.hook_add(UC_HOOK_CODE, thunk, begin=INDIRECT, end=INDIRECT) for hooked in HOOKED: assert by_name[hooked]["st_shndx"] == text_section entry = TEXT + by_name[hooked]["st_value"] ENTRIES[entry] = hooked cpu.hook_add(UC_HOOK_CODE, leaf(hooked), begin=entry, end=entry) SCALARS = ("flags", "perf", "e00", "g23b0", "o260", "s1d8", "g543e", "rec", "clr", "hyper1", "hyper2", "vcfg", "svcfg", "allocfail", "attach", "amask", "p2pfail", "p2pst", "limit", "types", "board", "fabric", "reboot", "g97e") # Engine rows: descriptor, present, PostLoad status, lock status, word 4c. ENGINE_ROWS = [(0x10000100, 1, 0, 0, 0x4c01), (0x10000200, 0, 0, 0, 0x4c02), (0x10000300, 1, 0x56, 0, 0x4c03)] # GPU rows: self, byte 52f3, word ca4, word c9c, control ab5 status, control ab6 status. GPU_ROWS = [(0, 1, 0x4200, 1, 0, 0), (0, 0, 0x4300, 2, 0, 0), (1, 0, CA4, C9C, 0, 0), (0, 1, 0x4400, 4, 0, 0)] DEFAULT = dict(flags=0, perf=0, e00=0, g23b0=1, o260=1, s1d8=0, g543e=0, rec=0, clr=0, hyper1=0, hyper2=0, vcfg=1, svcfg=0, allocfail=0, attach=0, amask=0x1d, p2pfail=0, p2pst=0x40, limit=0xffffffff, types=0, board=0, fabric=0, reboot=0, g97e=0, D=ENGINE_ROWS, G=GPU_ROWS) rows = [] def run(**changes): case.clear() case.update(DEFAULT) case.update(changes) assert set(case) == set(SCALARS) | {"D", "G"} assert len(case["G"]) <= MAX_PEERS and sum(row[0] for row in case["G"]) <= 1 trace.clear() engines.clear() calls.clear() last.clear() heap.clear() own = next((row for row in case["G"] if row[0]), (1, 0, CA4, C9C, 0, 0)) write32(GPU + 0xe00, case["e00"]) write64(GPU + 0x23b0, OBJECT if case["g23b0"] else 0) write8(OBJECT + 0x260, case["o260"]) write8(GPU + 0x543e, case["g543e"]) write8(GPU + 0x52f3, own[1]) write32(GPU + 0xca4, own[2]) write32(GPU + 0xc9c, own[3]) write32(GPU + 0x6990, case["rec"]) write32(GPU + 0x6994, 0x70000009) write8(GPU + 0x97e, case["g97e"]) write8(GPU + 0x6901, 1) write64(GPU + 0x4360, 0) for index, (_own, byte_52f3, word_ca4, word_c9c, _set, _remove) in enumerate(case["G"]): write8(OTHERS + 0x8000 * index + 0x52f3, byte_52f3) write32(OTHERS + 0x8000 * index + 0xca4, word_ca4) write32(OTHERS + 0x8000 * index + 0xc9c, word_c9c) write32(GPU + 0xdc0, len(case["D"])) for index, (descriptor, present, _status, _lock, word_4c) in enumerate(case["D"]): write32(DESCRIPTORS + 4 * index, descriptor) if present: pointer = ENGINES + 0x100 * index write64(pointer, VTABLE) write32(pointer + 0x4c, word_4c) engines[descriptor] = pointer rsp = STACK + 0xffc8 cpu.reg_write(UC_X86_REG_RDI, GPU) cpu.reg_write(UC_X86_REG_RSI, case["flags"]) cpu.reg_write(UC_X86_REG_RSP, rsp) cpu.reg_write(UC_X86_REG_RBP, STACK + 0x8000) write64(rsp, STOP) cpu.emu_start(TEXT + RANGES[0][0], STOP, count=400000) assert cpu.reg_read(UC_X86_REG_RIP) == STOP assert cpu.reg_read(UC_X86_REG_RSP) == rsp + 8 assert cpu.reg_read(UC_X86_REG_RBP) == STACK + 0x8000 outputs = [cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff, read32(GPU + 0x6990), read32(GPU + 0x6994), read8(GPU + 0x97e), read8(GPU + 0x6901), buffer(read64(GPU + 0x4360))] fields = [f"{name}={case[name]:x}" for name in SCALARS] fields.append("D=" + ",".join(":".join(f"{value:x}" for value in row) for row in case["D"])) fields.append("G=" + ",".join(":".join(f"{value:x}" for value in row) for row in case["G"])) rows.append(" ".join(fields) + ";" + " ".join(f"{value:x}" for value in outputs) + ";" + " ".join(trace)) # Scalar cases: every base mode with each single change applied on top. FAIL_ENGINE = [(0x10000100, 1, 0x51, 0, 0x4c01)] + ENGINE_ROWS[1:] FAIL_LAST = ENGINE_ROWS[:2] + [(0x10000300, 1, 0x1e, 0, 0x4c03)] FAIL_LOCK = [(0x10000100, 1, 0x56, 0x40, 0x4c01)] + ENGINE_ROWS[1:] OWN = (1, 0, CA4, C9C, 0, 0) LOADED = [(0, 1, 0x4200, 1, 0, 0), (0, 1, 0x4300, 2, 0, 0)] SET_FAILS_FIRST = [(0, 1, 0x4200, 1, 0x1f, 0), OWN, (0, 1, 0x4400, 4, 0, 0)] SET_FAILS_OWN = [(0, 1, 0x4200, 1, 0, 0), (0, 0, 0x4300, 2, 0, 0), (1, 0, CA4, C9C, 0x1f, 0), (0, 1, 0x4400, 4, 0, 0)] SET_FAILS_LAST = [(0, 1, 0x4200, 1, 0, 0x65), (0, 0, 0x4300, 2, 0, 0), (1, 1, CA4, C9C, 0, 0x66), (0, 1, 0x4400, 4, 0x1f, 0)] SAME_ID = [(0, 1, CA4, 1, 0, 0), OWN] FULL = [(0, 1, 0x5000 + index, index, 0, 0) for index in range(31)] + [(1, 0, CA4, 31, 0, 0)] FULL_FAILS = FULL[:-1] + [(1, 0, CA4, 31, 0x1f, 0)] CHANGES = [ {}, {"perf": 0x40}, {"g23b0": 0}, {"o260": 0}, {"s1d8": 0x51}, {"D": []}, {"D": FAIL_ENGINE}, {"D": FAIL_ENGINE, "clr": 1}, {"D": FAIL_LAST}, {"D": FAIL_LOCK}, {"hyper1": 1}, {"hyper1": 1, "vcfg": 0}, {"hyper1": 1, "vcfg": 0x80}, {"hyper1": 1, "svcfg": 0x51}, {"hyper2": 1}, {"hyper1": 1, "hyper2": 1}, {"hyper2": 1, "fabric": 0x51}, {"fabric": 0x51}, {"fabric": 0x51, "reboot": 1}, {"board": 0x56}, {"reboot": 1}, {"reboot": 1, "g97e": 1}, {"reboot": 0x100}, {"reboot": 0x280, "g97e": 1}, {"allocfail": 1}, {"allocfail": 2}, {"allocfail": 3}, {"allocfail": 4}, {"attach": 0x51}, {"types": 0x51}, {"G": []}, {"G": [OWN]}, {"G": LOADED}, {"G": SAME_ID}, {"G": [(1, 1, CA4, C9C, 0, 0)] + LOADED}, {"p2pfail": 1}, {"p2pfail": 2}, {"p2pfail": 4}, {"p2pfail": 5, "p2pst": 0x1f}, {"G": SET_FAILS_FIRST}, {"G": SET_FAILS_OWN}, {"G": SET_FAILS_LAST}, {"G": SET_FAILS_LAST, "limit": 9}, {"G": SET_FAILS_LAST, "limit": 13}, {"G": [OWN], "limit": 1}, {"limit": 0}, {"limit": 3}, {"limit": 4}, {"G": FULL}, {"G": FULL_FAILS}, {"G": FULL, "p2pfail": 40}, ] for flags in (0, 1): for e00 in (0, 1, 0x100, 0x10000, 0x10100): for g543e in (0, 1): for rec in (0, 0x77): for change in CHANGES: base = dict(flags=flags, e00=e00, g543e=g543e, rec=rec) base.update(change) run(**base) scalar_cases = len(rows) generator = random.Random(580178) GOOD, BAD = (0, 0, 0x56), (0, 0, 0, 0, 0x56, 0x51, 0x1e) for _ in range(2500): clean = generator.randrange(3) != 0 pool = [0x10000100 + 0x100 * index for index in range(8)] generator.shuffle(pool) descriptors = [] for index, descriptor in enumerate(pool[:generator.randrange(0, 7)]): descriptors.append(( descriptor, int(generator.randrange(4) != 0), generator.choice(GOOD if clean else BAD), 0 if clean else generator.choice((0, 0, 0, 0, 0, 0x40)), 0x4c00 + index)) quiet = generator.randrange(3) != 0 peers = [(0, generator.randrange(2), generator.choice((CA4, 0x4200 + 0x100 * index)), generator.randrange(32), 0 if quiet else generator.choice((0, 0, 0, 0, 0x1f)), generator.choice((0, 0, 0x65))) for index in range(generator.randrange(0, 7))] if generator.randrange(5) != 0: peers.insert(generator.randrange(len(peers) + 1), (1, generator.randrange(2), CA4, generator.randrange(32), 0 if quiet else generator.choice((0, 0, 0, 0x1f)), generator.choice((0, 0, 0x65)))) values = dict( flags=generator.randrange(4), perf=generator.choice((0, 0, 0, 0x40)), e00=generator.choice((0, 0, 1, 0x100, 0x100, 0x100, 0x10000, 0x10100, 0x101)), g23b0=generator.randrange(2), o260=generator.randrange(2), s1d8=0 if clean else generator.choice((0, 0, 0, 0x51)), g543e=int(generator.randrange(4) != 0), rec=generator.choice((0, 0, 0, 0x77)), clr=generator.randrange(2), hyper1=generator.randrange(2), hyper2=generator.randrange(2), vcfg=generator.choice((0, 1)), svcfg=0 if clean else generator.choice((0, 0, 0, 0x51)), allocfail=generator.choice((0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4)), attach=generator.choice((0, 0, 0, 0, 0, 0, 0, 0, 0, 0x51)), amask=generator.getrandbits(8), p2pfail=0 if quiet else generator.randrange(12), p2pst=generator.choice((0x40, 0x1f)), limit=generator.choice((0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, generator.randrange(24))), types=generator.choice((0, 0, 0, 0, 0x51)), board=generator.choice((0, 0, 0x56)), fabric=generator.choice((0, 0, 0, 0x51)), reboot=generator.choice((0, 1, 0x100)), g97e=generator.randrange(2)) run(D=descriptors, G=peers, **values) engine_cases = len(rows) - scalar_cases # Instructions of the executed range that no case executed. decoder = Cs(CS_ARCH_X86, CS_MODE_64) decoded = [(address, mnemonic) for start, end in RANGES for address, _size, mnemonic, _operands in decoder.disasm_lite(bytes(text[start:end]), start)] instructions = [address for address, _mnemonic in decoded] unvisited = [address for address in instructions if address not in visited] assert visited <= set(instructions) assert all(mnemonic == "nop" for address, mnemonic in decoded if address not in visited), \ [hex(address) for address in unvisited] out = ROOT / "target/gpu-stage" out.mkdir(parents=True, exist_ok=True) oracle = "\n".join(rows) + "\n" (out / "original-base-post-load.txt").write_text(oracle) report = { "original_sha256": DIGEST, "executed": ["_nv031219rm"], "fixture_supplied": sorted(HOOKED) + ["GPU+448", "GPU+4298 (this GPU and listed GPU objects)", "GPU+23b0 object +1d8", "engine vtable +70"], "scalar_cases": scalar_cases, "engine_list_cases": engine_cases, "instructions": len(instructions), "instructions_executed": len(visited), "instructions_not_executed": [f"text+{address:x}" for address in unvisited], "random_seed": 580178, "oracle": "target/gpu-stage/original-base-post-load.txt", "oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(), "scope": "Original control flow of the base StatePostLoad pass: the GPU+23b0 object method, " "the per-engine PostLoad loop with the first-failure record, control 0x2080400b, the " "P2P capability propagation over the attached GPUs with its removal pass, " "_nv042370rm, the GPU+4360 allocation with control 0x2080013f and the tail. All " "callees including the allocator, the GPU iterator and the controls are " "fixture-supplied, so no callee, engine or hardware behavior is exercised.", } (ROOT / "reports/gpu-base-post-load-original.json").write_text(json.dumps(report, indent=2) + "\n") print(f"{scalar_cases} scalar and {engine_cases} engine-list original base PostLoad cases")