#!/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. """ from __future__ import annotations import argparse import json from pathlib import Path import re import struct import sys if str(Path(__file__).resolve().parent) not in sys.path: sys.path.insert(0, str(Path(__file__).resolve().parent)) from _pf_hal_channel_elf import ( DIGEST, ROOT, SHN_UNDEF, STT_FUNC, disasm_x86_64, discover_rm_object, index_text_relocations, parse_elf64_rm_object, require, require_unicorn, write_or_check_json, ) 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 ROLE = {"rm": "RmHalspecOwner (RM HAL)", "chip": "GpuHalspecOwner (chip HAL)"} ENGINE_STATE_INIT = "_nv005718rm" OTHER_OBJECTS = (("OBJVBIOS", "0x5dc772", "0x20c8", "_nv006698rm"),) def page(size: int) -> int: return (size + 4095) & ~4095 def tag(value: int) -> str | None: if value == RM_OWNER: return "rm" if value == CHIP_OWNER: return "chip" if OBJECT_BASE <= value < OBJECT + OBJECT_BYTES: return f"object+{value - OBJECT_BASE:#x}" return None def in_family(name: str) -> bool: match = re.fullmatch(r"_nv(\d{6})rm", name) return bool(match) and (3300 <= int(match[1]) <= 3500 or 5600 <= int(match[1]) <= 6100) class Trace: def __init__(self): self.calls, self.casts, self.writes = [], [], [] self.reads, self.module_reads = {}, set() self.frames, self.previous, self.allocations = [], None, 0 self.engine_state = None def engine_object_offset(state: Trace, vtable: int) -> int: """Offset of the engine object inside the allocation.""" stored = {(offset, value) for _routine, offset, size, value in state.writes if size == 8} depth = 0 while (8 * (depth + 1), RODATA + vtable + 0x18 * (depth + 1)) in stored: depth += 1 require( (0, RODATA + vtable) in stored and depth in (2, 3), f"unexpected class metadata chain for vtable {vtable:#x}, depth={depth}", ) base = 8 * (depth - 2) if state.engine_state is not None: require( state.engine_state == f"object+{base + 8:#x}", f"engine_state mismatch: {state.engine_state} vs base={base:#x}", ) return base def resolve_stage_bodies_via_hal( engine: dict, hal_slots: dict, by_name: dict[str, dict], pristine: bytes, ) -> tuple[dict, int]: """Decode direct stage wrappers that dispatch through a HAL slot of the engine object.""" via_hal: dict[str, dict] = {} resolved = 0 for stage, body in (engine.get("bodies") or {}).items(): if body["kind"] != "direct": continue symbol = by_name[body["wrapper"]] if symbol["st_size"] > 48: continue wrapper = pristine[symbol["st_value"] : symbol["st_value"] + min(symbol["st_size"], 48)] insns = disasm_x86_64(wrapper) loads = [ op for mn, op in insns if mn == "mov" and re.search(r"qword ptr \[rsi\s*\+\s*(0x[0-9a-f]+|\d+)\]", op, re.I) ] adjusts = [op for mn, op in insns if mn in ("sub", "lea") and "rsi" in op] if len(loads) != 1 or not adjusts: continue m = re.search(r"\[rsi\s*\+\s*(0x[0-9a-f]+|\d+)\]", loads[0], re.I) if not m: continue displacement = int(m.group(1), 0) slot = f"{displacement + 8:#x}" bound = hal_slots.get(slot) via_hal[stage] = { "wrapper": body["wrapper"], "object_slot": slot, "function": bound["function"] if bound else None, } resolved += bound is not None return via_hal, resolved def find_creation_routine(creator: str, call_edges: dict[str, set[str]]) -> str: """The routine that allocates the object: the vtable-storing routine or its caller.""" if ALLOCATE in call_edges.get(creator, set()): return creator found = sorted( caller for caller, callees in call_edges.items() if caller != creator and ALLOCATE in callees and creator in callees ) require(len(found) == 1, f"expected 1 creation routine for {creator}, found {found}") return found[0] def build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser( description="Resolve GV100 HAL function tables for engine classes from 580.178.04 nv-kernel.o_binary." ) p.add_argument( "--check", action="store_true", help="Verify reports/gv100-engine-hal-bindings.json without overwriting.", ) p.add_argument( "--rm-object", default=None, help="Path to 580.178.04 nv-kernel.o_binary (overrides auto-discovery).", ) p.add_argument( "--worklist", default=str(ROOT / "reports/gpu-stage-engine-worklist.json"), help="Path to gpu-stage-engine-worklist.json.", ) p.add_argument( "--output", default=str(ROOT / "reports/gv100-engine-hal-bindings.json"), help="Output JSON report path.", ) return p def main(argv: list[str] | None = None) -> int: opt = build_parser().parse_args(argv) unicorn, x86 = require_unicorn() rm_object = discover_rm_object(opt.rm_object) parsed = parse_elf64_rm_object(rm_object) symbols = parsed["symbols"] by_name = parsed["defined"] text_index = parsed["section_index"](".text") pristine = parsed["section_bytes"](".text") data_bytes = parsed["section_bytes"](".data") rodata_bytes = parsed["section_bytes"](".rodata") bss_bytes = parsed["section_size"](".bss") bases = { text_index: TEXT, parsed["section_index"](".data"): DATA, parsed["section_index"](".rodata"): RODATA, parsed["section_index"](".bss"): BSS, } by_value = { s["st_value"]: s["name"] for s in symbols if s["st_shndx"] == text_index and s["name"].startswith("_nv") } entries = { s["st_value"]: s["name"] for s in symbols if s["st_shndx"] == text_index and s["name"] and s["st_type"] == STT_FUNC } rodata_refs, call_edges = index_text_relocations(parsed) # Link the whole text once. Undefined symbols get one stub address each. code = bytearray(pristine) externals: dict[str, int] = {} for offset, sym_idx, kind, addend in parsed["iter_relocations"](".rela.text"): target = symbols[sym_idx] section = target["st_shndx"] if section == SHN_UNDEF: slot = externals.setdefault(target["name"], len(externals)) value = EXTERNAL + 16 * slot + 4 + addend if kind in (2, 4) else EXTERNAL + 16 * slot elif section in bases: value = bases[section] + target["st_value"] + addend else: continue if kind in (2, 4): struct.pack_into(" Trace: state = Trace() cpu.mem_write(OBJECT, bytes(OBJECT_BYTES)) cpu.mem_write(SELECT, bytes(0x4000)) cpu.mem_write(STACK, bytes(0x20000)) cpu.mem_write(RM_OWNER + 0x10, struct.pack(" None: stack = emu.reg_read(x86.UC_X86_REG_RSP) emu.reg_write(x86.UC_X86_REG_RIP, struct.unpack(" 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 ( x86.UC_X86_REG_RDI, x86.UC_X86_REG_RSI, x86.UC_X86_REG_RDX, x86.UC_X86_REG_RCX, ) ] caller = state.frames[-1][0] if name == ALLOCATE: state.allocations += 1 emu.mem_write(arguments[2], struct.pack(" dict: slots, properties, conventions = {}, {}, {} binders, property_binders = set(), set() reached = {call["callee"]: call for call in state.calls} require(len(reached) == len(state.calls), f"{top}: a routine was called twice") base = 0 if vtable is None else engine_object_offset(state, vtable) def relative(name: str) -> str: offset = int(name.split("+")[1], 16) - base return f"object-{-offset:#x}" if offset < 0 else f"object+{offset:#x}" for routine, offset, size, value in state.writes: if offset < base: continue key = f"{offset - base:#x}" if size == 8 and TEXT <= value < TEXT + len(pristine): slots[key] = { "function": by_value.get(value - TEXT, f"text+{value - TEXT:#x}"), "binder": routine, } properties.pop(key, None) binders.add(routine) continue if size == 8 and any(first <= value < last for first, last in mapped): continue if routine == top or routine not in reached: continue if gpu and routine in ( "_nv005685rm", "_nv005758rm", "_nv006052rm", "_nv006053rm", "_nv006055rm", "_nv006056rm", "_nv005722rm", ): continue properties[key] = {"bytes": size, "value": f"{value:#x}", "binder": routine} slots.pop(key, None) property_binders.add(routine) for routine in sorted(binders | property_binders): call = reached.get(routine) if call is None: conventions[routine] = { "object_argument": "object+0x0", "order": "creation routine", "selectors_read": sorted(state.reads.get(routine, ())), "evidence": "[A] stores made by the object-creation routine itself while it " "executed from its entry", } continue read = sorted(state.reads.get(routine, ())) kinds = {item.split("+")[0] for item in read} carried = {call[register] for register in ("rsi", "rdx", "rcx")} & {"rm", "chip"} if gpu: order = "object only" else: require(kinds <= carried, f"{routine}: selector mismatch {kinds} vs {carried}") order = {("chip", "rm"): "chip, RM", ("rm", "chip"): "RM, chip"}.get( (call["rsi"], call["rdx"]), f"rsi={call['rsi'] or 'not a selector'}, rdx={call['rdx'] or 'not a selector'}", ) entry = { "object_argument": relative(call["rdi"]), "rsi": ROLE.get(call["rsi"], "not a selector owner"), "rdx": ROLE.get(call["rdx"], "not a selector owner"), "order": order, "selectors_read": read, "call_site": { "caller": call["caller"], "call_instruction": call["call_instruction"], }, } if gpu: entry["rsi"] = entry["rdx"] = "not used" entry["evidence"] = ( "[A] the GPU object's creation routine executed from its entry; this routine " "received the object in rdi and read the selector words through the object's " "own sub-objects (+38 GpuHalspecOwner, +50 RmHalspecOwner, whose addresses " "_nv005722rm stores at +80 and +88)" ) else: entry["evidence"] = ( f"[A] {top} executed from its entry with the cast stub returning a tagged owner " "per class id; register values read at the call instruction. selectors_read " "lists the owner words this routine's own instructions loaded. A register " "whose owner the routine never reads may be a leftover of the caller" ) if call["rcx"] in ("rm", "chip"): entry["rcx"] = ROLE[call["rcx"]] if routine in state.module_reads: entry["reads_module_data"] = True conventions[routine] = entry order_key = lambda item: int(item[0], 16) # noqa: E731 return { "engine_object_offset_in_allocation": f"{base:#x}", "binders": sorted(binders), "hal_slots": dict(sorted(slots.items(), key=order_key)), "property_binders": sorted(property_binders), "hal_properties": dict(sorted(properties.items(), key=order_key)), "argument_conventions": conventions, } worklist = json.loads(Path(opt.worklist).read_text()) classes: dict[str, list[int]] = {} for engine in worklist["engines"]: root = engine.get("class_vtable_rodata_offset") if root: classes.setdefault(root, []).append(engine["engine_ordinal0"]) report_classes = [] total_slots = 0 for root, ordinals in sorted(classes.items()): creators = sorted(rodata_refs.get(int(root, 16), set())) require(len(creators) == 1, f"expected 1 creator for vtable {root}, found {creators}") top = find_creation_routine(creators[0], call_edges) state = trace(top) assembled = assemble(top, state, vtable=int(root, 16)) total_slots += len(assembled["hal_slots"]) label = worklist["engines"][ordinals[0]]["class_label"] report_classes.append( { "class_label": label, "engine_ordinals0": ordinals, "class_vtable_rodata_offset": root, "object_creators": creators, "creation_routine": top, "selector_casts": state.casts, "engine_object_offset_in_allocation": assembled["engine_object_offset_in_allocation"], "binders": assembled["binders"], "hal_slots": assembled["hal_slots"], "property_binders": assembled["property_binders"], "hal_properties": assembled["hal_properties"], "argument_conventions": assembled["argument_conventions"], } ) print( f"{label or '?':20} creation={top} binders={assembled['binders']} " f"slots={len(assembled['hal_slots'])} properties={len(assembled['hal_properties'])}", flush=True, ) state = trace(GPU_CREATOR, gpu=True) assembled = assemble(GPU_CREATOR, state, gpu=True) selector_words = { name: struct.unpack("