mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
738 lines
30 KiB
Python
738 lines
30 KiB
Python
#!/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("<i", code, offset, value - (TEXT + offset))
|
|
elif kind == 10:
|
|
struct.pack_into("<I", code, offset, value & 0xFFFFFFFF)
|
|
elif kind == 11:
|
|
struct.pack_into("<i", code, offset, value)
|
|
elif kind == 1:
|
|
struct.pack_into("<Q", code, offset, value & 0xFFFFFFFFFFFFFFFF)
|
|
stop = EXTERNAL + 16 * len(externals) + 0x100
|
|
|
|
cpu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_64)
|
|
for address, size in (
|
|
(TEXT, page(len(code))),
|
|
(DATA, page(len(data_bytes))),
|
|
(BSS, page(bss_bytes)),
|
|
(RODATA, page(len(rodata_bytes))),
|
|
(OBJECT, OBJECT_BYTES),
|
|
(SELECT, 0x4000),
|
|
(STACK, 0x20000),
|
|
(PARENT, 0x10000),
|
|
(EXTERNAL, page(16 * len(externals) + 0x200)),
|
|
):
|
|
cpu.mem_map(address, size)
|
|
cpu.mem_write(TEXT, bytes(code))
|
|
cpu.mem_write(DATA, data_bytes)
|
|
cpu.mem_write(RODATA, rodata_bytes)
|
|
|
|
mapped = (
|
|
(DATA, BSS + page(bss_bytes)),
|
|
(OBJECT, OBJECT + OBJECT_BYTES),
|
|
(SELECT, SELECT + 0x4000),
|
|
(STACK, STACK + 0x20000),
|
|
(PARENT, PARENT + 0x10000),
|
|
(RODATA, RODATA + len(rodata_bytes)),
|
|
)
|
|
|
|
def trace(top: str, gpu: bool = False) -> 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("<HH", RM_INDEX, DISP_IP_INDEX))
|
|
cpu.mem_write(CHIP_OWNER + 0x10, struct.pack("<HH", CHIP_INDEX, TEGRA_INDEX))
|
|
rsp = STACK + 0xFF00
|
|
if gpu:
|
|
frame = struct.pack("<QQQQ", stop, 0, 3, 0) + bytes(64)
|
|
registers = ((x86.UC_X86_REG_RCX, 0x14), (x86.UC_X86_REG_R8, 0), (x86.UC_X86_REG_R9, 0))
|
|
else:
|
|
frame = struct.pack("<Q", stop) + bytes(64)
|
|
registers = ((x86.UC_X86_REG_RCX, 0), (x86.UC_X86_REG_R8, 0), (x86.UC_X86_REG_R9, 0))
|
|
cpu.mem_write(rsp, frame)
|
|
for register, value in (
|
|
(x86.UC_X86_REG_RDI, STACK + 0x1F000),
|
|
(x86.UC_X86_REG_RSI, PARENT),
|
|
(x86.UC_X86_REG_RDX, 0),
|
|
(x86.UC_X86_REG_RSP, rsp),
|
|
(x86.UC_X86_REG_RBP, STACK + 0x18000),
|
|
*registers,
|
|
):
|
|
cpu.reg_write(register, value)
|
|
|
|
def leave(emu, result: int = 0) -> None:
|
|
stack = emu.reg_read(x86.UC_X86_REG_RSP)
|
|
emu.reg_write(x86.UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(stack, 8))[0])
|
|
emu.reg_write(x86.UC_X86_REG_RSP, stack + 8)
|
|
emu.reg_write(x86.UC_X86_REG_RAX, result)
|
|
|
|
def step(emu, address, _size, _user):
|
|
stack = emu.reg_read(x86.UC_X86_REG_RSP)
|
|
while state.frames and stack > 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("<Q", OBJECT_BASE))
|
|
leave(emu)
|
|
return
|
|
if name == CAST:
|
|
definition = arguments[1]
|
|
class_id = None
|
|
if RODATA <= definition < RODATA + len(rodata_bytes) or DATA <= definition < DATA + len(data_bytes):
|
|
class_id = struct.unpack("<I", emu.mem_read(definition + 4, 4))[0]
|
|
owner, result = OWNER_CLASSES.get(class_id, (None, OTHER_CAST))
|
|
if owner:
|
|
state.casts.append(
|
|
{
|
|
"caller": caller,
|
|
"call_instruction": f"{site - TEXT:#x}",
|
|
"class_id": f"{class_id:#x}",
|
|
"class": owner,
|
|
}
|
|
)
|
|
leave(emu, result)
|
|
return
|
|
tags = [tag(value) for value in arguments]
|
|
if name == ENGINE_STATE_INIT:
|
|
state.engine_state = tags[0]
|
|
selected = any(item in ("rm", "chip") for item in tags)
|
|
if (gpu and name in GPU_FAMILY) or (not gpu and selected and in_family(name)):
|
|
state.calls.append(
|
|
{
|
|
"caller": caller,
|
|
"call_instruction": f"{site - TEXT:#x}",
|
|
"callee": name,
|
|
"rdi": tags[0],
|
|
"rsi": tags[1],
|
|
"rdx": tags[2],
|
|
"rcx": tags[3],
|
|
}
|
|
)
|
|
state.frames.append((name, stack))
|
|
return
|
|
leave(emu)
|
|
|
|
def stored(_emu, _access, address, size, value, _user):
|
|
state.writes.append(
|
|
(state.frames[-1][0], address - OBJECT_BASE, size, value & ((1 << (8 * size)) - 1))
|
|
)
|
|
|
|
def selector_read(_emu, _access, address, _size, _value, _user):
|
|
owner = "rm" if address < CHIP_OWNER else "chip" if address < OTHER_CAST else "other"
|
|
state.reads.setdefault(state.frames[-1][0], set()).add(f"{owner}+{address & 0xfff:#x}")
|
|
|
|
def gpu_selector_read(_emu, _access, address, _size, _value, _user):
|
|
offset = address - OBJECT_BASE
|
|
for owner, base in (("chip", GPU_CHIP_OWNER), ("rm", GPU_RM_OWNER)):
|
|
if base + 0x10 <= offset < base + 0x14:
|
|
state.reads.setdefault(state.frames[-1][0], set()).add(
|
|
f"{owner}+{offset - base:#x}"
|
|
)
|
|
|
|
def module_read(_emu, _access, _address, _size, _value, _user):
|
|
state.module_reads.add(state.frames[-1][0])
|
|
|
|
hooks = [
|
|
cpu.hook_add(unicorn.UC_HOOK_CODE, step),
|
|
cpu.hook_add(
|
|
unicorn.UC_HOOK_MEM_WRITE, stored, begin=OBJECT, end=OBJECT + OBJECT_BYTES - 1
|
|
),
|
|
cpu.hook_add(unicorn.UC_HOOK_MEM_READ, selector_read, begin=SELECT, end=SELECT + 0x3FFF),
|
|
cpu.hook_add(
|
|
unicorn.UC_HOOK_MEM_READ, module_read, begin=DATA, end=BSS + page(bss_bytes) - 1
|
|
),
|
|
]
|
|
if gpu:
|
|
hooks.append(
|
|
cpu.hook_add(
|
|
unicorn.UC_HOOK_MEM_READ,
|
|
gpu_selector_read,
|
|
begin=OBJECT_BASE,
|
|
end=OBJECT_BASE + 0x100,
|
|
)
|
|
)
|
|
try:
|
|
cpu.emu_start(TEXT + by_name[top]["st_value"], stop, count=50000000)
|
|
except unicorn.UcError as error:
|
|
raise RuntimeError(f"{top}: {error} at {cpu.reg_read(x86.UC_X86_REG_RIP):#x}") from error
|
|
finally:
|
|
for hook in hooks:
|
|
cpu.hook_del(hook)
|
|
require(cpu.reg_read(x86.UC_X86_REG_RIP) == stop, f"{top} did not reach STOP")
|
|
require(cpu.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF == 0, f"{top}: creation failed")
|
|
require(state.allocations == 1, f"{top}: unexpected allocations {state.allocations}")
|
|
return state
|
|
|
|
def assemble(top: str, state: Trace, gpu: bool = False, vtable: int | None = None) -> 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("<H", cpu.mem_read(OBJECT_BASE + offset, 2))[0]
|
|
for name, offset in (
|
|
("chip", GPU_CHIP_OWNER + 0x10),
|
|
("tegra", GPU_CHIP_OWNER + 0x12),
|
|
("rm", GPU_RM_OWNER + 0x10),
|
|
("display_ip", GPU_RM_OWNER + 0x12),
|
|
)
|
|
}
|
|
require(
|
|
selector_words
|
|
== {
|
|
"chip": CHIP_INDEX,
|
|
"tegra": TEGRA_INDEX,
|
|
"rm": RM_INDEX,
|
|
"display_ip": DISP_IP_INDEX,
|
|
},
|
|
f"unexpected GPU selector words: {selector_words}",
|
|
)
|
|
gpu_object = {
|
|
"creation_routine": GPU_CREATOR,
|
|
"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"GPU object binders={gpu_object['binders']} slots={len(gpu_object['hal_slots'])} "
|
|
f"properties={len(gpu_object['hal_properties'])}",
|
|
flush=True,
|
|
)
|
|
|
|
other_objects = []
|
|
for label, class_id, gpu_offset, creator in OTHER_OBJECTS:
|
|
state = trace(creator)
|
|
assembled = assemble(creator, state)
|
|
other_objects.append(
|
|
{
|
|
"class_label": label,
|
|
"class_id": class_id,
|
|
"gpu_offset": gpu_offset,
|
|
"object_creators": [creator],
|
|
"creation_routine": creator,
|
|
"selector_casts": state.casts,
|
|
"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} binders={assembled['binders']} slots={len(assembled['hal_slots'])} "
|
|
f"properties={len(assembled['hal_properties'])}",
|
|
flush=True,
|
|
)
|
|
|
|
by_ordinal = {engine["engine_ordinal0"]: engine for engine in worklist["engines"]}
|
|
resolved_wrappers = 0
|
|
for entry in report_classes:
|
|
engine = by_ordinal[entry["engine_ordinals0"][0]]
|
|
via_hal, count = resolve_stage_bodies_via_hal(engine, entry["hal_slots"], by_name, pristine)
|
|
entry["stage_bodies_via_hal"] = via_hal
|
|
resolved_wrappers += count
|
|
|
|
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,
|
|
}
|
|
write_or_check_json(
|
|
Path(opt.output),
|
|
report,
|
|
opt.check,
|
|
"GV100 engine HAL bindings report",
|
|
indent=1,
|
|
)
|
|
print(f"{len(report_classes)} classes, {total_slots} HAL slots")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|