#!/usr/bin/env python3 """Run the original GV100 clock-gating table loaders and write an oracle. Executed original code: the Graphics routine _nv033505rm that the Graphics PreInitLocked body _nv033667rm calls, the Graphics functions it reaches at +d10 (_nv033245rm), +1478 (_nv033738rm) and +1480 (_nv033764rm), the table loaders _nv030976rm and _nv030310rm, the GPU-object loader at GPU+5c8 (_nv030977rm), and the GPU-object functions they call at +740 (_nv030423rm with _nv030556rm), +748 (_nv030728rm with _nv030732rm), +750 (_nv030519rm), +758 (_nv030891rm), +760 (_nv030902rm) and +768 (_nv030894rm). The function pointers are stored by the original binders: _nv005980rm and _nv005982rm for the GPU object, _nv005887rm, _nv005888rm and _nv005890rm for Graphics, chip HAL 0x23 and RM HAL 2. The tables are read by the original instructions from the object's .data and .rodata images with their relocations applied. Fixture-supplied services: register read _nv053907rm and write _nv053912rm, the feature query _nv031034rm and record _nv031133rm, the Graphics lookup _nv000333rm with the function at +40 of the vtable of its +17a8 object, the routines _nv042890rm, _nv042924rm and _nv042925rm, the functions at +118 and +178 of the object at +11d8 of the GPU+22c8 object, and the Graphics functions at +c78 (GV100 _nv032989rm) and +1038 (GV100 _nv031785rm). No hardware is involved. The same data is compared with the Rust constants in src/nvidia/src/gpu/clock_gating_tables.rs; --write-tables regenerates them. """ import bisect import hashlib import itertools import json from pathlib import Path import re import struct import sys from elftools.elf.elffile import ELFFile from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc from unicorn.x86_const import (UC_X86_REG_R8, UC_X86_REG_R9, 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) 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" TABLES = ROOT / "src/nvidia/src/gpu/clock_gating_tables.rs" TEXT, SDATA, DATA, STACK, STOP, RODATA = (0x10000000, 0x20000000, 0x30000000, 0x40000000, 0x50000000, 0x60000000) (GPU, GR, CHIP, RM, OWNER, CHILD, CONTEXT, KGR, REGISTERS, VTABLE) = ( DATA, DATA + 0x10000, DATA + 0x20000, DATA + 0x21000, DATA + 0x22000, DATA + 0x25000, DATA + 0x26000, DATA + 0x27000, DATA + 0x2a000, DATA + 0x2b000) (INDIRECT_RAX, INDIRECT_R8, GR_WRITE, CHILD_118, CHILD_178, GR_C78, GR_1038) = ( STOP + 0x100, STOP + 0x110, STOP + 0x200, STOP + 0x210, STOP + 0x220, STOP + 0x230, STOP + 0x240) # Section offsets of the descriptor arrays the three lookups walk, and lengths. BLCG_AT, BLCG_COUNT = 0x46c40, 0x15 # _nv030423rm SLCG_AT, SLCG_COUNT = 0x47720, 0x1e # _nv030728rm ENGINES_AT, ENGINES_COUNT = 0x4ce0f00, 0x12 # _nv030519rm, .rodata # The binders only store pointers, so the functions they select are listed. ROOTS = ("_nv033505rm", "_nv005980rm", "_nv005982rm", "_nv005887rm", "_nv005888rm", "_nv005890rm", "_nv033245rm", "_nv033738rm", "_nv033764rm", "_nv030977rm", "_nv030976rm", "_nv030310rm", "_nv030423rm", "_nv030728rm", "_nv030519rm", "_nv030891rm", "_nv030902rm", "_nv030894rm") HOOKED = ("_nv053907rm", "_nv053912rm", "_nv031034rm", "_nv031133rm", "_nv000333rm", "_nv042890rm", "_nv042924rm", "_nv042925rm") GPU_SLOTS = {0x5c8: "_nv030977rm", 0x740: "_nv030423rm", 0x748: "_nv030728rm", 0x750: "_nv030519rm", 0x758: "_nv030891rm", 0x760: "_nv030902rm", 0x768: "_nv030894rm"} GR_SLOTS = {0xd10: "_nv033245rm", 0x1478: "_nv033738rm", 0x1480: "_nv033764rm", 0xc78: "_nv032989rm", 0x1038: "_nv031785rm"} assert hashlib.sha256(ORIGINAL.read_bytes()).hexdigest() == DIGEST bindings = json.loads((ROOT / "reports/gv100-engine-hal-bindings.json").read_text()) assert bindings["original_sha256"] == 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()) data = bytearray(elf.get_section_by_name(".data").data()) text_section = elf.get_section_index(".text") data_section = elf.get_section_index(".data") rodata_section = elf.get_section_index(".rodata") rodata_header = elf.get_section_by_name(".rodata") stream.seek(rodata_header["sh_offset"] + ENGINES_AT) engine_bytes = stream.read(8 * ENGINES_COUNT) starts = sorted((symbol["st_value"], symbol["st_size"], symbol.name) for symbol in symbols if symbol["st_shndx"] == text_section and symbol["st_size"]) relocations = sorted((relocation["r_offset"], relocation["r_info_type"], relocation["r_info_sym"], relocation["r_addend"]) for relocation in elf.get_section_by_name(".rela.text").iter_relocations()) data_relocations = {relocation["r_offset"]: (relocation["r_info_type"], relocation["r_info_sym"], relocation["r_addend"]) for relocation in elf.get_section_by_name(".rela.data").iter_relocations()} def descriptors(at, count, width): """The (id, entries) list of one descriptor array, read from the object's data.""" tables = [] for index in range(count): offset = at + 24 * index ident, pad, pointer, length, tail = struct.unpack_from(" = (u32, &'static [E]);\n\n" f"/// The {BLCG_COUNT:#x} descriptors _nv030423rm (GPU+740) searches: table identifier, then\n" "/// (register, value) pairs.\n" "#[rustfmt::skip]\n" "pub const BLCG: &[Table<(u32, u32)>] = &[\n" + rows(BLCG) + "];\n\n" f"/// The {SLCG_COUNT:#x} descriptors _nv030728rm (GPU+748) searches: table identifier, then\n" "/// (register, first value, second value) triples.\n" "#[rustfmt::skip]\n" "pub const SLCG: &[Table<(u32, u32, u32)>] = &[\n" + rows(SLCG) + "];\n\n" f"/// The {ENGINES_COUNT:#x} (table identifier, engine descriptor) pairs _nv030519rm (GPU+750)\n" "/// searches.\n" "#[rustfmt::skip]\n" "pub const ENGINE_DESCRIPTORS: &[(u32, u32)] = &[\n" + "".join( f" ({ident:#x}, {descriptor:#x}),\n" for ident, descriptor in ENGINES) + "];\n") if "--write-tables" in sys.argv: TABLES.write_text(rust_tables()) source = TABLES.read_text() for name, expected in ( ("BLCG", [w for ident, rows, _at in BLCG for w in (ident, *itertools.chain(*rows))]), ("SLCG", [w for ident, rows, _at in SLCG for w in (ident, *itertools.chain(*rows))]), ("ENGINE_DESCRIPTORS", [w for pair in ENGINES for w in pair])): block = re.search(rf"pub const {name}: [^=]*= &\[\n(.*?)\n\];", source, re.S)[1] found = [int(word.replace("_", ""), 16) for word in re.findall(r"0x[0-9a-f_]+", block)] assert found == expected, f"{TABLES} {name} differs from the original object" # The nesting must match too, so the full text is compared as generated. assert source == rust_tables(), f"{TABLES} is not the generated text" # Relocate the executed code. Data references go to the section images below. offsets = [entry[0] for entry in relocations] entries = {symbol[0]: symbol[2] for symbol in starts} executed, pending = [], list(ROOTS) bases = {text_section: TEXT, data_section: SDATA, rodata_section: RODATA} while pending: name = pending.pop() if name in executed or name in HOOKED: continue executed.append(name) start, size = by_name[name]["st_value"], by_name[name]["st_size"] for offset, kind, index, addend in relocations[bisect.bisect_left(offsets, start): bisect.bisect_left(offsets, start + size)]: target = symbols[index] if target.name == "__x86_indirect_thunk_rax": address = INDIRECT_RAX elif target.name == "__x86_indirect_thunk_r8": address = INDIRECT_R8 else: assert target["st_shndx"] in bases, (name, target.name) address = bases[target["st_shndx"]] + target["st_value"] # Follow direct calls and tail calls only, not stored pointers. if (target["st_shndx"] == text_section and kind in (2, 4) and text[offset - 1] in (0xe8, 0xe9)): callee = entries.get(target["st_value"] + addend + 4) if callee and callee not in HOOKED: pending.append(callee) value = address + addend if kind in (2, 4): value -= TEXT + offset else: assert kind == 11, kind struct.pack_into("> 4 & 1)[case["skip"]] trace.append(f"f178:{low[2]:x}:{value:x}") elif name == "GR_C78": assert (a, b) == (GPU, GR), full value = case["c78"] trace.append(f"c78:{value:x}") elif name == "GR_1038": assert (a, b) == (GPU, GR), full trace.append("x1038") else: raise AssertionError(name) leave(emu, value) return run cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, unused: emu.reg_write( UC_X86_REG_RIP, emu.reg_read(UC_X86_REG_RAX)), begin=INDIRECT_RAX, end=INDIRECT_RAX) cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, unused: emu.reg_write( UC_X86_REG_RIP, emu.reg_read(UC_X86_REG_R8)), begin=INDIRECT_R8, end=INDIRECT_R8) for hooked in HOOKED: entry = TEXT + by_name[hooked]["st_value"] cpu.hook_add(UC_HOOK_CODE, leaf(hooked), begin=entry, end=entry) for label, entry in (("GR_WRITE", GR_WRITE), ("CHILD_118", CHILD_118), ("CHILD_178", CHILD_178), ("GR_C78", GR_C78), ("GR_1038", GR_1038)): cpu.hook_add(UC_HOOK_CODE, leaf(label), begin=entry, end=entry) def call(name, *arguments): for register, argument in zip((UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX), arguments): cpu.reg_write(register, argument) rsp = STACK + 0xffc8 cpu.reg_write(UC_X86_REG_RSP, rsp) cpu.reg_write(UC_X86_REG_RBP, STACK + 0x8000) cpu.mem_write(rsp, struct.pack("