mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 14:38:47 +00:00
301 lines
13 KiB
Python
301 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""Run the original GV100 OBJMC construct and init stage bodies and write an oracle.
|
|
|
|
Executed original code: the GV100 HAL binder _nv006001rm, the ConstructEngine
|
|
body _nv043560rm with its bound HAL _nv043558rm, StatePreInitUnlocked
|
|
_nv043631rm, StateInitLocked _nv043628rm, StateInitUnlocked _nv043629rm and
|
|
the functions they call directly as part of their own logic. Registry reads,
|
|
the lock query, other objects' methods and diagnostics are fixture-supplied.
|
|
"""
|
|
import bisect
|
|
from _binary_path import resolve_580_binary
|
|
import collections
|
|
import hashlib
|
|
import itertools
|
|
import json
|
|
from pathlib import Path
|
|
import struct
|
|
|
|
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_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 = resolve_580_binary()
|
|
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
TEXT, RODATA, DATA, STACK, STOP = 0x10000000, 0x20000000, 0x30000000, 0x40000000, 0x50000000
|
|
GPU, MC, CHIP, RM = DATA, DATA + 0x10000, DATA + 0x20000, DATA + 0x21000
|
|
OBJ_1EC0, OBJ_20E8, OBJ_2120, OBJ_2068 = (DATA + 0x22000, DATA + 0x23000, DATA + 0x24000,
|
|
DATA + 0x25000)
|
|
INDIRECT, SLOT_1B0 = STOP + 0x100, STOP + 0x200
|
|
FILL = 0x77
|
|
# The binder only stores pointers, so the function it selects is listed.
|
|
ROOTS = ("_nv043560rm", "_nv043631rm", "_nv043628rm", "_nv043629rm", "_nv006001rm",
|
|
"_nv043558rm")
|
|
HOOKED = ("_nv049786rm", "_nv054113rm", "_nv031034rm", "_nv031133rm", "_nv044918rm",
|
|
"_nv047869rm", "_nv046747rm", "_nv046745rm")
|
|
KEYS = (b"DisableGrAuto", b"EnableCoreVoltage", b"RmOverrideIdleSlowdownSettings",
|
|
b"RmEnablePreException", b"RMSkipRCOnExceptions")
|
|
|
|
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 = bytearray(elf.get_section_by_name(".text").data())
|
|
rodata = elf.get_section_by_name(".rodata").data()
|
|
text_section, rodata_section = (elf.get_section_index(name) for name in (".text", ".rodata"))
|
|
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())
|
|
|
|
offsets = [entry[0] for entry in relocations]
|
|
executed, pending = [], list(ROOTS)
|
|
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
|
|
elif target["st_shndx"] == rodata_section:
|
|
address = RODATA + target["st_value"]
|
|
else:
|
|
assert target["st_shndx"] == text_section, (name, target.name)
|
|
address = TEXT + target["st_value"]
|
|
# Follow direct calls and tail calls only, not stored pointers.
|
|
if kind in (2, 4) and text[offset - 1] in (0xe8, 0xe9):
|
|
entry = target["st_value"] + addend + 4
|
|
callee = next((symbol for symbol in starts if symbol[0] == entry), None)
|
|
if callee and callee[2] not in HOOKED:
|
|
pending.append(callee[2])
|
|
value = address + addend
|
|
if kind in (2, 4):
|
|
value -= TEXT + offset
|
|
else:
|
|
assert kind == 11, kind
|
|
struct.pack_into("<i", text, offset, value)
|
|
|
|
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
|
|
for address, data in ((TEXT, bytes(text)), (RODATA, bytes(rodata))):
|
|
cpu.mem_map(address, (len(data) + 4095) & ~4095)
|
|
cpu.mem_write(address, data)
|
|
for address, size in ((DATA, 0x30000), (STACK, 0x10000), (STOP, 0x1000)):
|
|
cpu.mem_map(address, size)
|
|
case, trace = {}, []
|
|
branches = collections.Counter()
|
|
|
|
|
|
def leave(emu, value=0):
|
|
rsp = emu.reg_read(UC_X86_REG_RSP)
|
|
emu.reg_write(UC_X86_REG_RSP, rsp + 8)
|
|
emu.reg_write(UC_X86_REG_RAX, value)
|
|
emu.reg_write(UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(rsp, 8))[0])
|
|
|
|
|
|
def leaf(name):
|
|
def run(emu, address, size, unused):
|
|
a, b, c, d = (emu.reg_read(register) for register in (
|
|
UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX))
|
|
low = [value & 0xffffffff for value in (a, b, c, d)]
|
|
value = 0
|
|
if name == "_nv049786rm":
|
|
assert a == GPU
|
|
key = bytes(emu.mem_read(b, 40)).split(b"\0")[0]
|
|
assert key in KEYS, key
|
|
status, word = case["registry"][key.decode()]
|
|
trace.append(f"reg:{key.decode()}")
|
|
if status == 0:
|
|
emu.mem_write(c, struct.pack("<I", word))
|
|
value = status
|
|
elif name == "_nv054113rm":
|
|
trace.append("lock")
|
|
value = 0xffffff00 | case["lock"]
|
|
elif name == "_nv031034rm":
|
|
assert a == GPU
|
|
trace.append(f"nv031034:{low[1]:x}:{low[2]:x}")
|
|
value = case["nv031034"]
|
|
elif name == "_nv031133rm":
|
|
assert a == GPU
|
|
trace.append(f"nv031133:{low[1]:x}:{low[2]:x}:{low[3]:x}")
|
|
value = 0x33
|
|
elif name == "_nv044918rm":
|
|
assert (a, b) == (GPU, OBJ_1EC0)
|
|
trace.append("nv044918")
|
|
value = 0xffff
|
|
elif name == "_nv047869rm":
|
|
trace.append(f"log:{low[0]:x}:{low[1]:x}")
|
|
elif name == "_nv046745rm":
|
|
trace.append(f"assert:{low[0]:x}")
|
|
else:
|
|
raise AssertionError(f"{name} is not reached with the GV100 bindings")
|
|
leave(emu, value)
|
|
return run
|
|
|
|
|
|
def thunk(emu, address, size, unused):
|
|
target = emu.reg_read(UC_X86_REG_RAX)
|
|
if target == SLOT_1B0:
|
|
assert (emu.reg_read(UC_X86_REG_RDI), emu.reg_read(UC_X86_REG_RSI)) == (GPU, OBJ_20E8)
|
|
trace.append("gpu_20e8_1b0")
|
|
leave(emu, 0x33)
|
|
else:
|
|
emu.reg_write(UC_X86_REG_RIP, target)
|
|
|
|
|
|
cpu.hook_add(UC_HOOK_CODE, thunk, begin=INDIRECT, end=INDIRECT)
|
|
for hooked in HOOKED:
|
|
entry = TEXT + by_name[hooked]["st_value"]
|
|
cpu.hook_add(UC_HOOK_CODE, leaf(hooked), 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), 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("<Q", STOP))
|
|
cpu.emu_start(TEXT + by_name[name]["st_value"], STOP, count=200000)
|
|
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, name
|
|
return cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff
|
|
|
|
|
|
def byte(address):
|
|
return cpu.mem_read(address, 1)[0]
|
|
|
|
|
|
def row(tag, inputs, outputs):
|
|
rows.append(" ".join([tag] + [f"{value:x}" for value in inputs]) + ";"
|
|
+ " ".join(f"{value:x}" for value in outputs) + ";" + " ".join(trace))
|
|
|
|
|
|
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
|
|
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
|
|
call("_nv006001rm", MC, CHIP, RM)
|
|
names = {symbol[0]: symbol[2] for symbol in starts}
|
|
table = bytes(cpu.mem_read(MC, 0x1000))
|
|
bound = {"0x120": names[struct.unpack_from("<Q", table, 0x120)[0] - TEXT]}
|
|
assert bound == {"0x120": "_nv043558rm"}, bound
|
|
|
|
|
|
def reset():
|
|
"""Every object byte outside the bound table holds the fill value."""
|
|
cpu.mem_write(DATA, bytes([FILL]) * 0x30000)
|
|
cpu.mem_write(MC, table[:0x1b8])
|
|
for slot in (0x1ec0, 0x20e8, 0x2120):
|
|
cpu.mem_write(GPU + slot, bytes(8))
|
|
cpu.mem_write(GPU + 0x2068, struct.pack("<Q", OBJ_2068))
|
|
cpu.mem_write(OBJ_20E8 + 0x1b0, struct.pack("<Q", SLOT_1B0))
|
|
trace.clear()
|
|
|
|
|
|
rows = []
|
|
# ConstructEngine: _nv043561rm and the bound slot 0x120 both return 0.
|
|
reset()
|
|
row("c", (), (call("_nv043560rm", GPU, MC),))
|
|
assert rows == ["c;0;"], rows
|
|
branches["construct.success"] += 1
|
|
|
|
# StatePreInitUnlocked.
|
|
for nv031034, (status, word) in itertools.product(
|
|
(0, 2, 0x56), ((0x57, 0), (0, 0), (0, 1), (0, 0xffffffff), (0, 0x100))):
|
|
reset()
|
|
case.update(nv031034=nv031034, registry={"DisableGrAuto": (status, word)})
|
|
result = call("_nv043631rm", GPU, MC)
|
|
row("p", (nv031034, status, word), (result, byte(MC + 0x1b9)))
|
|
if nv031034:
|
|
branches["pre_init.nv031034_nonzero"] += 1
|
|
elif status:
|
|
branches["pre_init.DisableGrAuto_absent"] += 1
|
|
elif word == 0:
|
|
branches["pre_init.DisableGrAuto_zero"] += 1
|
|
else:
|
|
branches["pre_init.DisableGrAuto_nonzero"] += 1
|
|
|
|
# StateInitLocked and its tail call _nv043627rm.
|
|
for lock, has_1ec0, has_20e8, has_2120, mc_1b8 in itertools.product(
|
|
(0, 1), (0, 1), (0, 1), (0, 1), (0, 1, 0x80)):
|
|
reset()
|
|
case.update(lock=lock)
|
|
for present, slot, target in ((has_1ec0, 0x1ec0, OBJ_1EC0), (has_20e8, 0x20e8, OBJ_20E8),
|
|
(has_2120, 0x2120, OBJ_2120)):
|
|
cpu.mem_write(GPU + slot, struct.pack("<Q", target if present else 0))
|
|
cpu.mem_write(MC + 0x1b8, bytes([mc_1b8]))
|
|
result = call("_nv043628rm", GPU, MC)
|
|
row("l", (lock, has_1ec0, has_20e8, has_2120, mc_1b8), (result, byte(MC + 0x1bb)))
|
|
if not lock:
|
|
branches["init_locked.lock_not_held"] += 1
|
|
continue
|
|
branches["init_locked.lock_held"] += 1
|
|
branches[f"init_locked.gpu_1ec0_{'present' if has_1ec0 else 'absent'}"] += 1
|
|
branches[f"init_locked.gpu_20e8_{'present' if has_20e8 else 'absent'}"] += 1
|
|
branches["init_locked.mc_1bb_set" if has_2120 and mc_1b8
|
|
else "init_locked.mc_1bb_untouched"] += 1
|
|
|
|
# StateInitUnlocked.
|
|
UNLOCKED_OUT = ((GPU, 0x98d), (GPU, 0x99c), (GPU, 0x99e), (OBJ_2068, 0x337), (MC, 0x1b8),
|
|
(MC, 0x1c4), (MC, 0x1c5), (MC, 0x1c6), (MC, 0x1c7))
|
|
ABSENT = (0x57, 0)
|
|
for lock, gpu_90f, voltage, slowdown, pre_exception, skip_rc in itertools.chain(
|
|
itertools.product((0,), (0, 1, 0xa5), (ABSENT, (0, 0), (0, 1), (0, 2), (0, 0xffffffff)),
|
|
(ABSENT, (0, 0), (0, 0x40), (0, 0x4000), (0, 0x80), (0, 0x8000),
|
|
(0, 0x3f), (0, 0x3f00), (0, 0xffffffff), (0, 0x12345678)),
|
|
(ABSENT, (0, 0), (0, 1), (0, 0x80000000)),
|
|
(ABSENT, (0x1a, 1), (0, 0), (0, 1), (0, 2))),
|
|
((1, 0xa5, (0, 1), (0, 0xffffffff), (0, 1), (0, 1)),
|
|
(1, 0, ABSENT, ABSENT, ABSENT, ABSENT))):
|
|
reset()
|
|
case.update(lock=lock, registry={
|
|
"EnableCoreVoltage": voltage, "RmOverrideIdleSlowdownSettings": slowdown,
|
|
"RmEnablePreException": pre_exception, "RMSkipRCOnExceptions": skip_rc})
|
|
cpu.mem_write(GPU + 0x90f, bytes([gpu_90f]))
|
|
result = call("_nv043629rm", GPU, MC)
|
|
row("u", (lock, gpu_90f, *voltage, *slowdown, *pre_exception, *skip_rc),
|
|
[result] + [byte(base + offset) for base, offset in UNLOCKED_OUT])
|
|
if lock:
|
|
branches["init_unlocked.lock_held"] += 1
|
|
continue
|
|
branches["init_unlocked.lock_not_held"] += 1
|
|
for key, (status, word), classes in (
|
|
("EnableCoreVoltage", voltage, {0: "zero", 1: "one"}),
|
|
("RmOverrideIdleSlowdownSettings", slowdown, {}),
|
|
("RmEnablePreException", pre_exception, {0: "zero"}),
|
|
("RMSkipRCOnExceptions", skip_rc, {1: "one"})):
|
|
if status:
|
|
label = "absent"
|
|
elif key == "RmOverrideIdleSlowdownSettings":
|
|
label = "enables_1b8" if word & 0x8080 else "leaves_1b8"
|
|
else:
|
|
label = classes.get(word, "other")
|
|
branches[f"init_unlocked.{key}_{label}"] += 1
|
|
|
|
out = ROOT / "target/gpu-stage"
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
oracle = "\n".join(rows) + "\n"
|
|
(out / "original-mc-init.txt").write_text(oracle)
|
|
report = {"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
|
|
"executed": sorted(executed),
|
|
"fixture_supplied": list(HOOKED) + ["GPU+20e8 object slot 0x1b0"],
|
|
"hooked_but_never_reached": ["_nv046747rm"],
|
|
"bindings": bound, "cases": len(rows),
|
|
"cases_by_body": {name: sum(1 for line in rows if line.startswith(tag))
|
|
for tag, name in (("c", "_nv043560rm"), ("p", "_nv043631rm"),
|
|
("l", "_nv043628rm"), ("u", "_nv043629rm"))},
|
|
"branch_counts": dict(sorted(branches.items())),
|
|
"oracle": "target/gpu-stage/original-mc-init.txt",
|
|
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
|
|
"scope": "Original GV100 OBJMC ConstructEngine, StatePreInitUnlocked, StateInitLocked "
|
|
"and StateInitUnlocked with the binder-selected function table. The registry, "
|
|
"the lock query, other objects' methods and diagnostics are fixture-supplied; "
|
|
"no hardware executed."}
|
|
(ROOT / "reports/gpu-mc-init-original.json").write_text(json.dumps(report, indent=2) + "\n")
|
|
print(f"{len(rows)} original MC init cases; executed {len(executed)} functions")
|