mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
- Updated tools/post_reboot.sh to check kernel oops taint bit and stuck driver tasks instead of <86400s uptime - Level 7 hardware regression passed on 0000:b3:00.0 (module 37e6fa430835eee2b426019db3ad70eeb7a9e9070c09c84bd9b973cf56cbe529, 107 inventory words, 0 static mismatches, CUDA baseline verified before and after) - Updated .gitignore to exclude build archives (*.a, *.rlib), __pycache__, and raw trace dumps
566 lines
29 KiB
Python
566 lines
29 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.
|
|
"""
|
|
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("<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)
|
|
STOP = EXTERNAL + 16 * len(externals) + 0x100
|
|
|
|
|
|
def page(size):
|
|
return (size + 4095) & ~4095
|
|
|
|
|
|
cpu = Uc(UC_ARCH_X86, 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)
|
|
disassembler = Cs(CS_ARCH_X86, CS_MODE_64)
|
|
|
|
|
|
def direct_callees(name):
|
|
"""Direct call and jump targets of one routine that are routine entries."""
|
|
symbol = by_name[name]
|
|
start = symbol["st_value"]
|
|
found = set()
|
|
for instruction in disassembler.disasm(pristine[start:start + symbol["st_size"]], TEXT + start):
|
|
if instruction.mnemonic in ("call", "jmp") and instruction.op_str.startswith("0x"):
|
|
# The linked copy holds the real displacement.
|
|
linked = next(disassembler.disasm(
|
|
bytes(code[instruction.address - TEXT:instruction.address - TEXT + instruction.size]),
|
|
instruction.address))
|
|
target = int(linked.op_str, 16) - TEXT
|
|
if target in entries:
|
|
found.add(entries[target])
|
|
return found
|
|
|
|
|
|
def tag(value):
|
|
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):
|
|
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 trace(top, gpu=False):
|
|
"""Execute one object-creation routine. Returns what its family stored into the object."""
|
|
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:
|
|
# (out, parent, flags, chip architecture 0x14, implementation 0, HID revision 0),
|
|
# then on the stack: Tegra type 0 (PCIe), RM variant 3, display IP version 0.
|
|
frame = struct.pack("<QQQQ", STOP, 0, 3, 0) + bytes(64)
|
|
registers = ((UC_X86_REG_RCX, 0x14), (UC_X86_REG_R8, 0), (UC_X86_REG_R9, 0))
|
|
else:
|
|
frame = struct.pack("<Q", STOP) + bytes(64)
|
|
registers = ((UC_X86_REG_RCX, 0), (UC_X86_REG_R8, 0), (UC_X86_REG_R9, 0))
|
|
cpu.mem_write(rsp, frame)
|
|
for register, value in ((UC_X86_REG_RDI, STACK + 0x1f000), (UC_X86_REG_RSI, PARENT),
|
|
(UC_X86_REG_RDX, 0), (UC_X86_REG_RSP, rsp),
|
|
(UC_X86_REG_RBP, STACK + 0x18000), *registers):
|
|
cpu.reg_write(register, value)
|
|
|
|
def leave(emu, result=0):
|
|
stack = emu.reg_read(UC_X86_REG_RSP)
|
|
emu.reg_write(UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(stack, 8))[0])
|
|
emu.reg_write(UC_X86_REG_RSP, stack + 8)
|
|
emu.reg_write(UC_X86_REG_RAX, result)
|
|
|
|
def step(emu, address, size, _user):
|
|
stack = emu.reg_read(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
|
|
(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("<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(UC_HOOK_CODE, step),
|
|
cpu.hook_add(UC_HOOK_MEM_WRITE, stored, begin=OBJECT, end=OBJECT + OBJECT_BYTES - 1),
|
|
cpu.hook_add(UC_HOOK_MEM_READ, selector_read, begin=SELECT, end=SELECT + 0x3fff),
|
|
cpu.hook_add(UC_HOOK_MEM_READ, module_read, begin=DATA, end=BSS + page(bss_bytes) - 1)]
|
|
if gpu:
|
|
hooks.append(cpu.hook_add(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 UcError as error:
|
|
raise RuntimeError(f"{top}: {error} at {cpu.reg_read(UC_X86_REG_RIP):#x}") from error
|
|
finally:
|
|
for hook in hooks:
|
|
cpu.hook_del(hook)
|
|
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, top
|
|
assert cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff == 0, (top, "creation failed")
|
|
assert state.allocations == 1, (top, state.allocations)
|
|
return state
|
|
|
|
|
|
ROLE = {"rm": "RmHalspecOwner (RM HAL)", "chip": "GpuHalspecOwner (chip HAL)"}
|
|
MAPPED = ((DATA, BSS + page(bss_bytes)), (OBJECT, OBJECT + OBJECT_BYTES),
|
|
(SELECT, SELECT + 0x4000), (STACK, STACK + 0x20000), (PARENT, PARENT + 0x10000),
|
|
(RODATA, RODATA + len(rodata_bytes)))
|
|
|
|
|
|
ENGINE_STATE_INIT = "_nv005718rm"
|
|
|
|
|
|
def engine_object_offset(state, vtable):
|
|
"""Offset of the engine object inside the allocation.
|
|
|
|
Stage wrappers and HAL bodies receive the object whose OBJENGSTATE
|
|
sub-object sits at +8. For every class but one that object is the
|
|
allocation itself. The allocation of _nv006725rm is a derived object
|
|
whose engine object starts at +8: its initializer _nv005744rm hands
|
|
allocation+8 to _nv005743rm, which hands allocation+0x10 to the
|
|
OBJENGSTATE initializer _nv005718rm. Offsets are reported relative to
|
|
the engine object, as HAL bodies see them.
|
|
|
|
The class metadata is a chain of 0x18-byte records, own class first and
|
|
Object last, and the initializer stores record k at allocation+8k. The
|
|
OBJENGSTATE record is the one before Object.
|
|
"""
|
|
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
|
|
assert (0, RODATA + vtable) in stored and depth in (2, 3), (vtable, depth)
|
|
base = 8 * (depth - 2)
|
|
if state.engine_state is not None:
|
|
assert state.engine_state == f"object+{base + 8:#x}", (state.engine_state, base)
|
|
return base
|
|
|
|
|
|
def assemble(top, state, gpu=False, vtable=None):
|
|
"""Slots, properties and per-routine argument conventions of one traced creation."""
|
|
slots, properties, conventions = {}, {}, {}
|
|
binders, property_binders = set(), set()
|
|
reached = {call["callee"]: call for call in state.calls}
|
|
assert len(reached) == len(state.calls), (top, "a routine was called twice")
|
|
base = 0 if vtable is None else engine_object_offset(state, vtable)
|
|
|
|
def relative(name):
|
|
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
|
|
# Structure set-up is not a HAL property: metadata, ancestor and
|
|
# parent pointers, and the creation routine's own bookkeeping stores.
|
|
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 # the selector owners themselves, reported under `selectors`
|
|
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:
|
|
# The creation routine stores function pointers itself.
|
|
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:
|
|
assert kinds <= carried, (routine, kinds, 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}
|
|
|
|
|
|
def creation_routine(creator):
|
|
"""The routine that allocates the object: the vtable-storing routine or its caller."""
|
|
if ALLOCATE in direct_callees(creator):
|
|
return creator
|
|
callers = subprocess.run(["grep", "-rl", creator + "(", str(FUNCTIONS)],
|
|
capture_output=True, text=True).stdout.split()
|
|
found = []
|
|
for caller in callers:
|
|
name = re.search(r"name: (_nv\d+rm)", Path(caller).read_text())
|
|
if name and name[1] != creator and name[1] in by_name and \
|
|
{ALLOCATE, creator} <= direct_callees(name[1]):
|
|
found.append(name[1])
|
|
assert len(found) == 1, (creator, found)
|
|
return found[0]
|
|
|
|
|
|
worklist = json.loads((ROOT / "reports/gpu-stage-engine-worklist.json").read_text())
|
|
classes = {}
|
|
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()):
|
|
address = int(root, 16) + RODATA_BASE
|
|
found = subprocess.run(["grep", "-rl", f"{address:08x}", str(FUNCTIONS)],
|
|
capture_output=True, text=True).stdout.split()
|
|
creators = []
|
|
for path in found:
|
|
creator = re.search(r"name: (_nv\d+rm)", Path(path).read_text())
|
|
creators.append(creator[1] if creator else Path(path).name)
|
|
assert len(creators) == 1, (root, creators)
|
|
top = creation_routine(creators[0])
|
|
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)
|
|
# The GPU object itself is not an engine. _nv006647rm allocates it; its
|
|
# initializer _nv005722rm runs binders _nv005978rm, _nv005980rm, _nv005982rm
|
|
# and _nv005984rm, and its constructor _nv003368rm the property initializer
|
|
# _nv005825rm.
|
|
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))}
|
|
assert selector_words == {"chip": CHIP_INDEX, "tegra": TEGRA_INDEX, "rm": RM_INDEX,
|
|
"display_ip": DISP_IP_INDEX}, 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)
|
|
# Objects the GPU owns that are not in the engine work list. OBJVBIOS (class id
|
|
# 0x5dc772, GPU+20c8) is created by _nv006698rm.
|
|
OTHER_OBJECTS = (("OBJVBIOS", "0x5dc772", "0x20c8", "_nv006698rm"),)
|
|
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)
|
|
# Some stage wrappers jump through a HAL slot of the object itself instead of
|
|
# the class vtable: `mov rax, [rsi + d]` with the engine-state pointer in rsi,
|
|
# then a call with rsi - 8. The object slot is therefore d + 8.
|
|
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 = {}
|
|
for stage, body in (engine.get("bodies") or {}).items():
|
|
if body["kind"] != "direct":
|
|
continue
|
|
symbol = by_name[body["wrapper"]]
|
|
wrapper = pristine[symbol["st_value"]:symbol["st_value"] + min(symbol["st_size"], 48)]
|
|
loads = [instruction.op_str for instruction in disassembler.disasm(wrapper, 0)
|
|
if instruction.mnemonic == "mov" and "qword ptr [rsi + " in instruction.op_str]
|
|
adjusts = [instruction.op_str for instruction in disassembler.disasm(wrapper, 0)
|
|
if instruction.mnemonic in ("sub", "lea") and "rsi" in instruction.op_str]
|
|
if symbol["st_size"] > 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")
|