Files
nvdriver/tools/check_gpu_acr_inputs_binary.py

314 lines
15 KiB
Python

#!/usr/bin/env python3
"""Run the original GV100 bodies behind the cross-object inputs of OBJACR Load and Unload.
Executed original code (function pointers stored as the GV100 binders and
creators store them; reports/gv100-engine-hal-bindings.json and section 9 of
analysis/closed-driver-580/acr-load-implementation-notes.md):
_nv031156rm the GPU check OBJACR+150 calls first, with GPU+2c8 =
_nv031157rm and the attach test _nv030927rm.
_nv039060rm the Jtag (GPU+1e70) function at +100.
_nv060173rm the OBJVBIOS (GPU+20c8) function at +238.
_nv051199rm the function at +178 of the Lpwr child (Lpwr+11b8).
_nv041589rm with KernelMemorySystem+160 = _nv041625rm and +170 =
_nv041610rm: the flush buffer the halt request programs.
_nv031481rm the interrupt service of the PMU idle wait, with
_nv030927rm and the vector test _nv060224rm.
Fixture-supplied: register read _nv053907rm and write _nv053912rm, the
diagnostics, the PCI lookup _nv030949rm, the memory descriptor services
_nv043694rm, _nv043691rm, _nv043721rm, _nv043704rm and _nv043699rm, the
GPU lookup _nv031398rm, the stall service _nv037739rm and the function at
+170 of the Lpwr child. No hardware is involved.
"""
import bisect
from _binary_path import resolve_580_binary
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_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 = resolve_580_binary()
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
TEXT, DATA, STACK, STOP = 0x10000000, 0x30000000, 0x40000000, 0x50000000
GPU, KMS, INTR, CHILD, VBIOS, JTAG, OUT, HANDLE, OTHER = (DATA + 0x10000 * index for index in range(9))
ROOTS = ("_nv031156rm", "_nv031157rm", "_nv030927rm", "_nv039060rm", "_nv060173rm", "_nv051199rm",
"_nv041589rm", "_nv041625rm", "_nv041610rm", "_nv031481rm", "_nv060224rm")
HOOKED = ("_nv053907rm", "_nv053912rm", "_nv047869rm", "_nv046745rm", "_nv049554rm",
"_nv030949rm", "_nv043694rm", "_nv043691rm", "_nv043721rm", "_nv043704rm",
"_nv043699rm", "_nv031398rm", "_nv037739rm", "_nv043744rm", "_nv049620rm")
FILL = 0x77777777
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())
text_section = elf.get_section_index(".text")
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]
entries = {symbol[0]: symbol[2] for symbol in starts}
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 = STOP + 0x100
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):
callee = entries.get(target["st_value"] + addend + 4)
if callee and callee not in HOOKED:
pending.append(callee)
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, size in ((TEXT, (len(text) + 4095) & ~4095), (DATA, 0x90000), (STACK, 0x10000),
(STOP, 0x1000)):
cpu.mem_map(address, size)
cpu.mem_write(TEXT, bytes(text))
case, trace = {}, []
ARGS = (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX, UC_X86_REG_R8,
UC_X86_REG_R9)
CHILD_170 = STOP + 0x200
def q(address, value=None):
if value is None:
return struct.unpack("<Q", cpu.mem_read(address, 8))[0]
cpu.mem_write(address, struct.pack("<Q", value))
return value
def leaf(name):
def run(emu, address, size, unused):
full = [emu.reg_read(register) for register in ARGS]
low = [value & 0xffffffff for value in full]
rsp = emu.reg_read(UC_X86_REG_RSP)
value = 0
if name == "_nv053907rm":
assert (full[0], low[1], low[2]) == (GPU + 0x4120, 0, 0), full
value = case["reads"].pop(0)
trace.append(f"r:{low[3]:x}:{value:x}")
elif name == "_nv053912rm":
assert (full[0], low[1], low[2]) == (GPU + 0x4120, 0, 0), full
trace.append(f"w:{low[3]:x}:{low[4]:x}")
elif name == "_nv030949rm":
assert full[0] == GPU
value = case["bridge"]
trace.append(f"pci:{value:x}")
elif name == "_nv043694rm":
# (out, gpu, bytes, alignment, contiguous, space, cache, flags on the stack)
flags = struct.unpack("<Q", emu.mem_read(rsp + 8, 8))[0] & 0xffffffff
assert (full[0], full[1]) == (KMS + 0x440, GPU), full
trace.append("mc:" + ":".join(f"{word:x}" for word in (*low[2:6], flags)))
value = case["create"].pop(0)
if value == 0:
cpu.mem_write(HANDLE, bytes(0x100))
q(KMS + 0x440, HANDLE)
elif name == "_nv043691rm":
assert full[0] == HANDLE
tag = struct.unpack("<I", emu.mem_read(HANDLE + 0xa0, 4))[0]
value = case["allocate"].pop(0)
trace.append(f"ma:{tag:x}:{value:x}")
elif name == "_nv043721rm":
assert (full[0], low[1], low[2]) == (HANDLE, 1, 0), full
value = case["address"].pop(0)
trace.append(f"mp:{value:x}")
elif name in ("_nv043704rm", "_nv043699rm"):
assert full[0] == HANDLE
trace.append("mf" if name == "_nv043704rm" else "md")
elif name == "_nv031398rm":
value = {0: GPU, 3: OTHER}.get(low[0], 0) if low[0] in case["present"] else 0
trace.append(f"gpu:{low[0]:x}")
elif name == "_nv037739rm":
assert full[1] == q(full[0] + 0x2110) and full[2] == OUT, full
trace.append(f"svc:{0 if full[0] == GPU else 3}:{low[3]:x}")
elif name in ("_nv043744rm", "_nv049620rm", "_nv049554rm"):
trace.append("x:" + name)
elif name == "_nv046745rm":
trace.append(f"a:{low[0]:x}")
else:
trace.append(f"log:{low[0]:x}:{low[1]:x}")
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])
return run
def child_170(emu, address, size, unused):
rsp = emu.reg_read(UC_X86_REG_RSP)
trace.append("c170")
emu.reg_write(UC_X86_REG_RSP, rsp + 8)
emu.reg_write(UC_X86_REG_RAX, case["child"])
emu.reg_write(UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(rsp, 8))[0])
cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, unused: emu.reg_write(
UC_X86_REG_RIP, emu.reg_read(UC_X86_REG_RAX)), begin=STOP + 0x100, end=STOP + 0x100)
cpu.hook_add(UC_HOOK_CODE, child_170, begin=CHILD_170, end=CHILD_170)
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(ARGS, 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=400000)
assert cpu.reg_read(UC_X86_REG_RIP) == STOP
return cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff
def address_of(name):
return TEXT + by_name[name]["st_value"]
rows, counts = [], {}
def reset(**values):
cpu.mem_write(DATA, bytes(0x90000))
trace.clear()
case.clear()
case.update(reads=[], bridge=0, create=[], allocate=[], address=[], present=(), child=0)
case.update(values)
# GPU+2c8 as binder _nv005978rm stores it; KernelMemorySystem+160 and +170
# as binder _nv005925rm; the children.
q(GPU + 0x2c8, address_of("_nv031157rm"))
q(GPU + 0x1ec8, KMS)
q(KMS + 0x160, address_of("_nv041625rm"))
q(KMS + 0x170, address_of("_nv041610rm"))
q(GPU + 0x2110, INTR)
q(OTHER + 0x2110, INTR + 0x8000)
q(CHILD + 0x170, CHILD_170)
def row(kind, inputs, status, extra=()):
assert not case["reads"] and not case["create"] and not case["allocate"]
counts[kind] = counts.get(kind, 0) + 1
rows.append(";".join((kind, " ".join(f"{value:x}" for value in inputs), f"{status:x}",
" ".join(f"{value:x}" for value in extra), " ".join(trace))))
# ---------------------------------------------------------------- _nv031156rm
BYTES = (0x915, 0x917, 0x918, 0x919, 0x926, 0x963, 0x949, 0x90c)
for flags in itertools.product((0, 1), repeat=len(BYTES)):
for attach, mode, child, bridge in itertools.product(
(0, 0x100, 0xff0000, 0xff0000ff), (0, 1, 2, 3), (None, 0, 1), (0, 1)):
if bridge and mode != 3:
continue
# The untaken combinations of the early exits are covered with one mode.
if (flags[1] or flags[2] or flags[3] or flags[4] or not flags[0]) and (mode or child):
continue
reset(bridge=bridge)
for offset, value in zip(BYTES, flags):
cpu.mem_write(GPU + offset, bytes([value]))
cpu.mem_write(GPU + 0x908, struct.pack("<I", attach))
cpu.mem_write(GPU + 0x69e4, struct.pack("<I", mode))
if child is not None:
q(GPU + 0x2430, VBIOS)
cpu.mem_write(VBIOS + 0x100, bytes([child]))
cpu.mem_write(OUT, struct.pack("<I", FILL))
status = call("_nv031156rm", GPU, 0, OUT)
stored = struct.unpack("<I", cpu.mem_read(OUT, 4))[0]
row("G", (*flags, attach, mode, 2 if child is None else child, bridge), status,
(stored,))
# ------------------------------------------------- _nv039060rm and _nv060173rm
for value in (0xa, 0, 8, 2, 0xffffffff, 0xfffffff7, 0x12345678):
reset(reads=[value])
row("J", (value,), call("_nv039060rm", GPU, JTAG, 0, 0) & 0xff)
for index, value in itertools.product((0, 1, 6, 7, 0x3f, 0xff), (0, 0x22082045, 0x1000, 0xffffffff)):
reset(reads=[value])
row("V", (index, value), call("_nv060173rm", GPU, VBIOS, index))
# ---------------------------------------------------------------- _nv051199rm
for byte, child in ((0, 0), (0, 0x56), (1, 0), (1, 0x56), (2, 0), (0xff, 0x65)):
reset(child=child)
cpu.mem_write(CHILD + 0x3c4, bytes([byte]))
row("P", (byte, child), call("_nv051199rm", GPU, CHILD))
# ------------------------------------------- _nv041589rm (the flush buffer)
for word_e00 in (0, 1, 0x100, 0xffff):
for existing in (0x5fbf5000, 0xfffffff000, 0x1000):
for register in (0x5fbf50, 0, 0xffffffff):
reset(reads=[] if word_e00 else [register])
cpu.mem_write(GPU + 0xe00, struct.pack("<H", word_e00))
q(KMS + 0x440, HANDLE)
q(KMS + 0x448, existing)
row("F", (word_e00, 1, existing, register), call("_nv041589rm", GPU, KMS))
for create, allocate, address in ((0, 0, 0x5fbf5000), (0, 0, 0x12345000), (0, 0, 0xffffffe000),
(0, 0, 0xfffffff000), (0x51, 0, 0), (0x1a, 0, 0)):
reads = [] if word_e00 or create else [0x5fbf50]
reset(reads=reads, create=[] if word_e00 else [create],
allocate=[] if word_e00 or create else [allocate],
address=[] if word_e00 or create else [address])
cpu.mem_write(GPU + 0xe00, struct.pack("<H", word_e00))
status = call("_nv041589rm", GPU, KMS)
row("F", (word_e00, 0, address, 0x5fbf50, create), status,
(q(KMS + 0x440) and 1, q(KMS + 0x448)))
# ---------------------------------------------------------------- _nv031481rm
for mask, present, attach, entries, other, repeat in itertools.product(
(0, 1, 8, 9, 0x80000001, 0xffffffff), ((), (0,), (0, 3)), (0, 0x100, 0xff0000),
(0, 1, 0x51), (0, 7), (0, 1, 0x101)):
reset(present=present)
cpu.mem_write(GPU + 0x908, struct.pack("<I", attach))
cpu.mem_write(INTR + 0x448, struct.pack("<I", entries))
cpu.mem_write(INTR + 0x8448, struct.pack("<I", other))
call("_nv031481rm", mask, OUT, repeat)
row("S", (mask, sum(1 << index for index in present), attach, entries, other, repeat), 0)
assert set(counts) == set("GJVPFS"), counts
out = ROOT / "target/gpu-stage"
out.mkdir(parents=True, exist_ok=True)
oracle = "\n".join(rows) + "\n"
(out / "original-acr-inputs.txt").write_text(oracle)
report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2, "executed": sorted(executed),
"fixture_supplied": list(HOOKED) + ["function at +170 of the Lpwr child"],
"stored_by_harness": {
"GPU+0x2c8": "_nv031157rm (binder _nv005978rm)",
"KernelMemorySystem+0x160": "_nv041625rm (binder _nv005925rm)",
"KernelMemorySystem+0x170": "_nv041610rm (binder _nv005925rm)"},
"cases": len(rows), "cases_by_kind": counts,
"oracle": "target/gpu-stage/original-acr-inputs.txt",
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
"scope": "Original GV100 bodies behind the cross-object services of OBJACR Load and "
"Unload. Register values and the listed services are fixture-supplied; no "
"hardware executed."}
(ROOT / "reports/gpu-acr-inputs-original.json").write_text(json.dumps(report, indent=2) + "\n")
print(f"{len(rows)} original cases {counts}; oracle sha256 {report['oracle_sha256']}")