#!/usr/bin/env python3 """Resolve the GV100 HAL function tables of the engine classes. For each engine in reports/gpu-stage-engine-worklist.json the object-creation routine is found through the class vtable address it stores. The creation routine itself is then executed from its first instruction, in private emulator memory, so that every HAL binder and property initializer runs with the arguments its real caller gives it. Argument convention. A creation routine obtains two selector owners from its parent by dynamic cast: RmHalspecOwner (class id 0x34a6d6, RM variant index at +0x10, display IP index at +0x12) and GpuHalspecOwner (class id 0x74bc71, chip index at +0x10, Tegra chip index at +0x12). Which of the two it passes in rsi and which in rdx differs from class to class, and binders of a parent class receive a sub-object, not the object. Nothing here assumes an order: the cast routine is replaced by a stub that reads the class id out of the class definition the caller passes and returns a distinct tagged owner, and the register values are read at the instruction that calls each binder. The earlier revision of this tool ran every routine as (object, chip, RM) and was wrong for the classes listed in reports/gv100-engine-hal-bindings-correction.json. Static original-instruction evidence. Only routines of the object-creation families (constructors _nv0033xx.._nv0035xx, initializers and binders _nv0056xx.._nv0061xx) that receive a selector owner are executed; every other callee, including the parent constructors' implementation bodies, the allocator and the cast routine, is replaced by a stub that returns 0. No engine body runs. """ import hashlib import json from pathlib import Path import re import struct import subprocess from capstone import CS_ARCH_X86, CS_MODE_64, Cs from elftools.elf.elffile import ELFFile from unicorn import (UC_ARCH_X86, UC_HOOK_CODE, UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE, UC_MODE_64, Uc, UcError) 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") FUNCTIONS = Path("/home/geodd/nvidia-driver/analysis-580.178.04/decompiled/kernel-rm-all/functions") DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b" RODATA_BASE = 0x0111d660 # address base of .rodata in the analysis database TEXT, DATA, BSS, OBJECT, SELECT, STACK, PARENT, EXTERNAL, RODATA = ( 0x10000000, 0x20000000, 0x28000000, 0x30000000, 0x38000000, 0x40000000, 0x48000000, 0x58000000, 0x60000000) OBJECT_BYTES, OBJECT_BASE = 0x200000, OBJECT + 0x1000 RM_OWNER, CHIP_OWNER, OTHER_CAST = SELECT, SELECT + 0x1000, SELECT + 0x2000 # Selector indices of a Tesla V100 at object-creation time. See `selectors` in the report. CHIP_INDEX, TEGRA_INDEX, RM_INDEX, DISP_IP_INDEX = 0x23, 0, 2, 20 ALLOCATE, CAST = "_nv005671rm", "_nv005245rm" OWNER_CLASSES = {0x34a6d6: ("RmHalspecOwner", RM_OWNER), 0x74bc71: ("GpuHalspecOwner", CHIP_OWNER)} # The GPU object owns both selector owners as sub-objects (+38 chip, +50 RM), # so its routines take only the object. These are its creation family. GPU_CREATOR = "_nv006647rm" GPU_FAMILY = {"_nv005722rm", "_nv003368rm", "_nv005685rm", "_nv005758rm", "_nv006052rm", "_nv006053rm", "_nv006055rm", "_nv006056rm", "_nv005978rm", "_nv005980rm", "_nv005982rm", "_nv005984rm", "_nv005825rm"} GPU_CHIP_OWNER, GPU_RM_OWNER = 0x38, 0x50 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_index = elf.get_section_index(".text") pristine = bytes(elf.get_section_by_name(".text").data()) data_bytes = bytes(elf.get_section_by_name(".data").data()) rodata_bytes = bytes(elf.get_section_by_name(".rodata").data()) bases = {text_index: TEXT, elf.get_section_index(".data"): DATA, elf.get_section_index(".rodata"): RODATA, elf.get_section_index(".bss"): BSS} bss_bytes = elf.get_section_by_name(".bss")["sh_size"] by_value = {symbol["st_value"]: symbol.name for symbol in symbols if symbol["st_shndx"] == text_index and symbol.name.startswith("_nv")} entries = {symbol["st_value"]: symbol.name for symbol in symbols if symbol["st_shndx"] == text_index and symbol.name and symbol["st_info"]["type"] == "STT_FUNC"} # Link the whole text once. Undefined symbols get one stub address each. code = bytearray(pristine) externals = {} callees = {} # function -> set of direct call and tail-call targets starts = sorted(entries) for relocation in elf.get_section_by_name(".rela.text").iter_relocations(): kind, addend, offset = (relocation["r_info_type"], relocation["r_addend"], relocation["r_offset"]) target = symbols[relocation["r_info_sym"]] section = target["st_shndx"] if section == "SHN_UNDEF": value = EXTERNAL + 16 * externals.setdefault(target.name, len(externals)) + 4 + addend \ if kind in (2, 4) else EXTERNAL + 16 * externals.setdefault(target.name, len(externals)) elif section in bases: value = bases[section] + target["st_value"] + addend else: continue if kind in (2, 4): struct.pack_into(" state.frames[-1][1]: state.frames.pop() site, state.previous = state.previous, address if EXTERNAL <= address < EXTERNAL + 0x10000000: if address == STOP: emu.emu_stop() else: leave(emu) return name = entries.get(address - TEXT) if name is None: return if site is None: state.frames.append((name, stack)) return arguments = [emu.reg_read(register) for register in (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX)] caller = state.frames[-1][0] if name == ALLOCATE: state.allocations += 1 emu.mem_write(arguments[2], struct.pack(" 48 or len(loads) != 1 or not adjusts: continue displacement = int(re.search(r"\[rsi \+ (0x[0-9a-f]+|\d+)\]", loads[0])[1], 0) slot = f"{displacement + 8:#x}" bound = entry["hal_slots"].get(slot) via_hal[stage] = {"wrapper": body["wrapper"], "object_slot": slot, "function": bound["function"] if bound else None} resolved_wrappers += bound is not None entry["stage_bodies_via_hal"] = via_hal report = { "original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2, "stage_wrappers_resolved_through_hal": resolved_wrappers, "scope": "Function pointers and plain property values the selected GV100 binders store into " "each engine object, by object offset. A property store may be a constant for " "every chip; only the value for these selectors is recorded. Each object-creation " "routine ran from its entry in isolated emulator memory, so every binder and " "property initializer received the arguments its real caller passes; binders of a " "parent class are recorded at the offset of the sub-object they received. Callees " "outside the creation families were replaced by stubs returning 0, so a store " "made by a constructor implementation body is not captured. No engine body was " "executed.", "argument_convention_method": { "summary": "No argument order is assumed. The dynamic-cast routine _nv005245rm is " "stubbed; the stub reads the class id at +4 of the class definition in rsi " "and returns a tagged owner. Registers are read at each call instruction " "and stores are attributed to the routine that executed them.", "RmHalspecOwner": {"class_id": "0x34a6d6", "rm_variant_index_offset": "0x10", "display_ip_index_offset": "0x12"}, "GpuHalspecOwner": {"class_id": "0x74bc71", "chip_index_offset": "0x10", "tegra_chip_index_offset": "0x12"}, "evidence": [ "[S] class ids and field order: generated/g_gpu_halspec_nvoc.h of the matching " "public source (RmHalspecOwner{rmVariantHal, dispIpHal}, " "GpuHalspecOwner{chipHal, tegraChipHal})", "[A] _nv005685rm (GPU+38) calls _nv006052rm on +0x10 and _nv006056rm on +0x12; " "_nv005758rm (GPU+50) calls _nv006055rm on +0x10 and _nv006053rm on +0x12", "[A] _nv005722rm stores GPU+38 at GPU+80 and GPU+50 at GPU+88", ]}, "selectors": { "chip_index": f"{CHIP_INDEX:#x}", "tegra_chip_index": TEGRA_INDEX, "rm_variant_index": RM_INDEX, "display_ip_index_at_creation": DISP_IP_INDEX, "evidence": [ "[A] executed here: _nv006052rm(architecture 0x14, implementation 0, HID revision 0) " "stores 0x23; _nv006056rm(Tegra type 0) stores 0; _nv006055rm(RM variant 3) stores " "2; _nv006053rm(display IP version 0) stores 20", "[A] _nv031364rm pushes a literal 0 as the display IP version argument of " "_nv006647rm (call at text+0x3c26f). _nv030825rm sets the index again later and " "re-runs only the binders of the display objects, none of which is in this report", ], "note": "Routines whose selectors_read includes rm+0x12 depend on the display IP index. " "The earlier revision of this tool left that word 0."}, "gpu_object": gpu_object, "other_objects": other_objects, "classes": report_classes, "total_slots": total_slots, } (ROOT / "reports/gv100-engine-hal-bindings.json").write_text(json.dumps(report, indent=1) + "\n") print(f"{len(report_classes)} classes, {total_slots} HAL slots")