Files
nvdriver/tools/check_gpu_wpr_blob_binary.py

974 lines
44 KiB
Python

#!/usr/bin/env python3
"""Run the original GV100 WPR image build and write an oracle.
The light-secure Falcon manager composes one image (WPR headers, LSB headers,
boot descriptors and ucode images) that the SEC2 HS ACR later authenticates.
This harness executes the original code that builds it for a GV100 with its
five clients and captures every byte written to the mapped allocation.
Executed original code (chip HAL 0x23, RM HAL 2), with the object's real
relocations for .text, .rodata and .data:
OBJLSFM InitLocked _nv043236rm with _nv043182rm (header producer),
_nv043197rm (client lookup and signature check), the function
table entries +100 _nv043212rm and +118 _nv043233rm;
Load _nv043238rm with _nv043186rm; the image writer
_nv043215rm with _nv043231rm.
OBJACR _nv016949rm (region request), the function at +1a8.
Falcon _nv028614rm (image preparation), +118 _nv028385rm,
_nv028571rm (image write), _nv028607rm behind the interface
function _nv028829rm (boot descriptor), +198 _nv028454rm,
the attach and configuration functions _nv021629rm,
_nv028533rm, _nv028412rm, _nv030167rm, _nv030464rm.
OBJBSP creator _nv005713rm, +1c8 _nv046468rm, the ucode getter
_nv046958rm with +3d8 _nv046969rm and its record getters.
PMU class creator _nv005744rm, +308 _nv052063rm with _nv052061rm, the
ucode getter, +3d8 _nv052308rm, the argument functions
_nv052149rm and _nv052146rm, and +50 _nv052190rm of the
embedded object at +a00 (bound by _nv006032rm).
OBJSEC2 creator _nv005735rm, ConstructEngine _nv055607rm (which calls
+200 _nv055614rm, _nv055612rm), the ucode getter _nv055780rm,
_nv055734rm.
FECS, GPCCS the binders _nv005875rm and _nv005879rm with the property
initialisers _nv005777rm and _nv005781rm, the configuration
functions _nv027357rm and _nv029624rm, the image builders
_nv027605rm and _nv029864rm.
Descriptors _nv017872rm, _nv017874rm, _nv017879rm, _nv017881rm and the
unpacker beneath them, on the packed records in .rodata.
GPU object _nv030179rm and _nv030823rm (chip identification from the
traced BOOT0 and BOOT42 words), the chip predicates.
Function tables are filled by the original binders and creators. The FECS and
GPCCS objects are laid out by this harness exactly as their creators
_nv006485rm and _nv006495rm store them, and each Falcon is bound with
_nv005876rm and attached with _nv021629rm as _nv028792rm does.
Fixture-supplied: register read _nv053907rm and write _nv053912rm,
diagnostics, the allocator, memory fill and copy performed as such, the
registry lookup _nv049786rm (no value found), the memory-descriptor services
(_nv044028rm and _nv044029rm map and unmap, _nv043717rm, _nv043696rm,
_nv043699rm, _nv043721rm), the multi-GPU services _nv031390rm and
_nv031478rm, the graphics lookup _nv000333rm, the name registration
_nv043743rm, the bit-vector helpers _nv017883rm and _nv017897rm, the services
_nv031521rm and _nv030258rm of the SEC2 constructor, the function at +270 of
the GPU+20c8 object, the function at +118 of the GPU+1e78 object, the function
at +40 of the vtable of the PMU+b08 object, the netlist views in the FECS and
GPCCS objects (code and data regions of the original netlist descriptor), the
order in which the five Falcons were registered, and the memory descriptor
stored by OBJACR InitLocked in the region record. No hardware is involved.
"""
import bisect
from _binary_path import resolve_580_binary
import hashlib
import json
from pathlib import Path
import random
import struct
import sys
import warnings
warnings.simplefilter("ignore")
from elftools.elf.elffile import ELFFile # noqa: E402
from unicorn import (UC_ARCH_X86, UC_HOOK_BLOCK, UC_HOOK_CODE, UC_HOOK_MEM_WRITE, # noqa: E402
UC_MODE_64, Uc)
from unicorn.x86_const import (UC_X86_REG_R8, UC_X86_REG_R9, UC_X86_REG_RAX, # noqa: E402
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"
TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt"
EXTRACT = ROOT / "target/trace/b3-bar12-rle.txt"
RODATA_ADDRESS = 0x111d660 # address of .rodata in the analysis database
TEXT, RODATA, DATAS, BSS, DATA, STACK, STOP, HEAP = (
0x10000000, 0x20000000, 0x28000000, 0x2c000000, 0x30000000, 0x40000000, 0x50000000,
0x60000000)
INDIRECT, EXTERNAL, SERVICE = STOP + 0x100, STOP + 0x200, STOP + 0xc000
DATA_BYTES, HEAP_BYTES = 0x400000, 0x1000000
(GPU, CHIP, RM, NVDEC, PMUX, SEC2, GRAPHICS, FECS, GPCCS, ACR, LSFM, F_NVDEC, F_PMU, F_SEC2,
F_FECS, F_GPCCS, VBIOS, FUSE, SCRATCH, MEMORY) = (DATA + 0x20000 * index for index in range(20))
PMU = PMUX + 8
(KERNEL_GRAPHICS, SYSTEM, MANAGER, FACTORY, MEMMGR, REGION, PMU_CHILD, SUBS) = (
MEMORY + 0x1000 * index for index in range(8))
BLOB, BLOB_BYTES = DATA + DATA_BYTES, 0x200000
ARGUMENTS = (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX, UC_X86_REG_R8,
UC_X86_REG_R9)
# Class vtables and self pointers the creators _nv006485rm and _nv006495rm store.
GRAPHICS_FALCONS = (("FECS", FECS, (0x4db66c0, 0x4db66d8, 0x4db6838), "_nv005875rm",
"_nv005777rm"),
("GPCCS", GPCCS, (0x4db69e0, 0x4db69f8, 0x4db6b58), "_nv005879rm",
"_nv005781rm"))
DIAGNOSTICS = ("_nv047869rm", "_nv047868rm", "_nv046745rm", "_nv046747rm")
HOOKED = ("_nv053907rm", "_nv053912rm", "_nv052687rm", "_nv052701rm", "_nv059714rm",
"_nv052705rm", "_nv049786rm", "_nv049765rm", "_nv044028rm", "_nv044029rm",
"_nv043717rm", "_nv043696rm", "_nv043699rm", "_nv043721rm", "_nv031390rm",
"_nv031478rm", "_nv000333rm", "_nv043743rm", "_nv017883rm", "_nv017897rm",
"_nv031521rm", "_nv030258rm") + DIAGNOSTICS
# Register values of the traced V100 (target/trace/b3-bar0.txt).
BOOT0, BOOT42 = 0x140000a1, 0x140a1000
PHYSICAL = dict(base=0x7fde80000, r10ac08=0, r21644=1, r10a108=0x400e0100, r87108=0x20420100)
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}
sections = {}
for name, base in ((".text", TEXT), (".rodata", RODATA), (".data", DATAS)):
sections[elf.get_section_index(name)] = (base, bytearray(
elf.get_section_by_name(name).data()), name)
bss_index, bss_size = elf.get_section_index(".bss"), elf.get_section_by_name(".bss")["sh_size"]
text_index = elf.get_section_index(".text")
starts = sorted((symbol["st_value"], symbol["st_size"], symbol.name) for symbol in symbols
if symbol["st_shndx"] == text_index and symbol["st_size"])
relocations = {name: [(entry["r_offset"], entry["r_info_type"], entry["r_info_sym"],
entry["r_addend"])
for entry in elf.get_section_by_name(".rela" + name).iter_relocations()]
for name in (".text", ".rodata", ".data")}
entries = {start: name for start, size, name in starts}
start_offsets = [start for start, size, name in starts]
external = {}
def address_of(symbol):
index = symbol["st_shndx"]
if index in sections:
return sections[index][0] + symbol["st_value"]
if index == bss_index:
return BSS + symbol["st_value"]
if symbol.name == "__x86_indirect_thunk_rax":
return INDIRECT
return external.setdefault(symbol.name, EXTERNAL + 8 * len(external))
for base, data, name in sections.values():
for offset, kind, index, addend in relocations[name]:
value = address_of(symbols[index]) + addend
assert len(external) < (SERVICE - EXTERNAL) // 8
if kind in (2, 4):
struct.pack_into("<I", data, offset, (value - (base + offset)) & 0xffffffff)
elif kind in (10, 11):
struct.pack_into("<I", data, offset, value & 0xffffffff)
else:
assert kind == 1, kind
struct.pack_into("<Q", data, offset, value & 0xffffffffffffffff)
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for base, data, name in sections.values():
cpu.mem_map(base, (len(data) + 4095) & ~4095)
cpu.mem_write(base, bytes(data))
cpu.mem_map(BSS, (bss_size + 4095) & ~4095)
for base, size in ((DATA, DATA_BYTES + BLOB_BYTES), (STACK, 0x100000), (STOP, 0x10000),
(HEAP, HEAP_BYTES)):
cpu.mem_map(base, size)
case, hooks, executed, heap, diagnostics = {}, {}, set(), [HEAP], [0]
reads, writes, subs, services = [], [], {}, []
def q(address, value):
cpu.mem_write(address, struct.pack("<Q", value))
def d(address, value):
cpu.mem_write(address, struct.pack("<I", value & 0xffffffff))
def b(address, value):
cpu.mem_write(address, bytes([value]))
def byte(address):
return cpu.mem_read(address, 1)[0]
def word(address):
return struct.unpack("<I", cpu.mem_read(address, 4))[0]
def half(address):
return struct.unpack("<H", cpu.mem_read(address, 2))[0]
def pointer(address):
return struct.unpack("<Q", cpu.mem_read(address, 8))[0]
def text(name):
return TEXT + by_name[name]["st_value"]
def function_at(address):
index = bisect.bisect_right(start_offsets, address - TEXT) - 1
return starts[index][2] if index >= 0 else hex(address)
def rodata(address):
"""Emulator address of an object at an analysis-database address."""
return RODATA + address - RODATA_ADDRESS
def analysis(address):
return address - RODATA + RODATA_ADDRESS
def leave(emu, value):
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 & 0xffffffffffffffff)
emu.reg_write(UC_X86_REG_RIP, pointer(rsp))
def hook(*names):
def register(function):
for name in names:
hooks[text(name) if name.startswith("_nv") else name] = (name, function)
return function
return register
def service(name):
def register(function):
address = SERVICE + 16 * sum(1 for key in hooks if isinstance(key, int)
and key >= SERVICE)
hooks[address] = (name, function)
return address
return register
@hook("_nv053907rm")
def register_read(a, low):
assert (a[0], low[1], low[2]) == (GPU + 0x4120, 0, 0), a
value = case["registers"][low[3]]
reads.append((low[3], value))
return value
@hook("_nv053912rm")
def register_write(a, low):
raise AssertionError(("the build writes no register", hex(low[3]), hex(low[4])))
@hook(*DIAGNOSTICS)
def diagnostic(a, low):
diagnostics[0] += 1
return 0
@hook("_nv049765rm")
def state_assertion(a, low):
return 0
@hook("_nv052687rm")
def allocate(a, low):
address = heap[0]
heap[0] += (low[0] + 0x3f) & ~0x1f
assert heap[0] < HEAP + HEAP_BYTES
# Allocations are not zeroed by the service; a pattern exposes a missing fill.
cpu.mem_write(address, b"\xa5" * low[0])
return address
@hook("_nv052701rm", "_nv059714rm")
def release(a, low):
return 0
@hook("_nv052705rm")
def fill(a, low):
cpu.mem_write(a[0], bytes([low[1] & 0xff]) * low[2])
return a[0]
@hook("_nv049786rm")
def registry(a, low):
return 0x56
@hook("_nv044028rm")
def map_region(a, low):
assert (a[0], a[1], low[2]) == (MEMMGR, REGION, 0x16), a
return BLOB
@hook("_nv044029rm")
def unmap_region(a, low):
assert (a[0], a[1], low[2]) == (MEMMGR, REGION, 0x16), a
return 0
@hook("_nv043717rm")
def descriptor_for_gpu(a, low):
assert a[1] == GPU
return a[0]
@hook("_nv043696rm")
def sub_descriptor(a, low):
"""A descriptor for bytes [offset, offset + size) of its parent."""
assert (a[1], a[2]) == (REGION, GPU), a
handle = SUBS + 0x40 * len(subs)
assert handle < SUBS + 0x1000
subs[handle] = (low[3], a[4])
q(a[0], handle)
case["subs"].append((low[3], a[4]))
return 0
@hook("_nv043699rm")
def sub_descriptor_free(a, low):
assert a[0] in subs, a
return 0
@hook("_nv043721rm")
def descriptor_address(a, low):
assert (low[1], a[2]) == (1, 0) and a[0] in subs, a
return case["inputs"]["base"] + subs[a[0]][0]
@hook("_nv031390rm")
def multi_gpu(a, low):
assert a[0] == GPU
return case["inputs"]["sli"]
@hook("_nv031478rm")
def gpu_section(a, low):
assert (a[0], low[1], low[2]) == (GPU, 0, 0), a
return 0
@hook("_nv000333rm")
def kernel_graphics(a, low):
assert a[0] == GPU
return KERNEL_GRAPHICS
@hook("_nv043743rm", "_nv017883rm", "_nv017897rm", "_nv030258rm")
def bookkeeping(a, low):
return 0
@hook("_nv031521rm")
def sec2_construct_service(a, low):
return 0
def copy(a, low):
cpu.mem_write(a[0], bytes(cpu.mem_read(a[1], low[2])))
if BLOB <= a[0] < BLOB + BLOB_BYTES:
writes.append(["c", a[0] - BLOB, low[2]])
return a[0]
hooks[address_of(by_name["os_mem_copy"])] = ("os_mem_copy", copy)
@service("GPU+20c8 object +270")
def vbios_270(a, low):
assert (a[0], a[1]) == (GPU, VBIOS)
return case["inputs"]["vb"]
@service("GPU+1e78 object +118")
def fuse_118(a, low):
assert (a[0], a[1], low[2]) == (GPU, FUSE, 0xff000020), a
d(a[3], 0)
return 0
@service("PMU+b08 object, vtable +40")
def pmu_child(a, low):
assert a[0] == PMU_CHILD
services.append("pmu+b08")
return case["inputs"]["pmu_child"]
def hooked(emu, address, size, unused):
a = [emu.reg_read(register) for register in ARGUMENTS]
leave(emu, hooks[address][1](a, [value & 0xffffffff for value in a]))
def unresolved(emu, address, size, unused):
assert address in hooks, [name for name, value in external.items() if value == address]
def block(emu, address, size, unused):
if address - TEXT in entries:
executed.add(entries[address - TEXT])
def store(emu, access, address, size, value, unused):
offset = address - BLOB
if writes and writes[-1][0] == "s" and writes[-1][1] + writes[-1][2] == offset:
writes[-1][2] += size
else:
writes.append(["s", offset, size])
def install_hooks():
"""One code hook per fixture address; imports without a fixture trap."""
for address in hooks:
if address not in installed:
installed[address] = cpu.hook_add(UC_HOOK_CODE, hooked, begin=address, end=address)
def track(enabled):
"""Function-entry tracking costs a callback per block; it is switched on
for the setup, the traced case and the first case of each kind."""
if enabled and not tracking:
tracking.append(cpu.hook_add(UC_HOOK_BLOCK, block))
elif not enabled and tracking:
cpu.hook_del(tracking.pop())
installed, tracking = {}, []
cpu.hook_add(UC_HOOK_CODE, unresolved, begin=EXTERNAL, end=SERVICE - 1)
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=INDIRECT, end=INDIRECT)
cpu.hook_add(UC_HOOK_MEM_WRITE, store, begin=BLOB, end=BLOB + BLOB_BYTES - 1)
def call(name, *arguments):
for register, argument in zip(ARGUMENTS, arguments):
cpu.reg_write(register, argument)
rsp = STACK + 0xfff00
cpu.reg_write(UC_X86_REG_RSP, rsp)
cpu.reg_write(UC_X86_REG_RBP, STACK + 0x80000)
q(rsp, STOP)
executed.add(name)
install_hooks()
cpu.emu_start(text(name), STOP, count=400000000)
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, name
return cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff
# ---------------------------------------------------------------- setup
case.update(inputs=dict(vb=0, sli=0, pmu_child=0, base=0), registers={}, subs=[])
track(True)
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
q(GPU + 0x80, CHIP)
q(GPU + 0x88, RM)
# Chip identification as the GPU constructor performs it.
q(BSS + by_name["_nv029075rm"]["st_value"], SYSTEM)
q(SYSTEM + 0x258, MANAGER)
q(MANAGER + 0x48 + 35 * 8, FACTORY)
assert call("_nv030179rm", GPU, BOOT0, BOOT42, 0) == 0
call("_nv030823rm", GPU)
identity = {"GPU+0x9e8": word(GPU + 0x9e8), "GPU+0xd00": word(GPU + 0xd00),
"GPU+0xd04": word(GPU + 0xd04), "GPU+0xde0": word(GPU + 0xde0),
"GPU+0xde4": word(GPU + 0xde4)}
assert identity == {"GPU+0x9e8": 0x23, "GPU+0xd00": 0x140, "GPU+0xd04": 0, "GPU+0xde0": BOOT0,
"GPU+0xde4": BOOT42}, identity
call("_nv005980rm", GPU)
call("_nv005982rm", GPU)
# Engine objects by their creators, properties by the property initialisers.
for creator, properties, target in (("_nv005713rm", "_nv005811rm", NVDEC),
("_nv005735rm", "_nv005840rm", SEC2)):
call(creator, target, CHIP, RM)
call(properties, target, CHIP, RM)
call("_nv005744rm", PMUX, CHIP, RM)
# Argument order as the callers pass it (reports/gv100-engine-hal-bindings.json,
# argument_conventions): the PMU and OBJLSFM property initializers take
# (object, RM owner, chip owner); the other routines here take the chip owner first.
call("_nv005852rm", PMU, RM, CHIP)
call("_nv006032rm", PMU + 0xa00, CHIP, RM)
for binder, properties, target in (("_nv006000rm", "_nv005835rm", LSFM),
("_nv005947rm", "_nv005809rm", ACR)):
call(binder, target, CHIP, RM)
call(properties, target, *((RM, CHIP) if properties == "_nv005835rm" else (CHIP, RM)))
# The interface constructor _nv003365rm creates the Falcon through
# _nv028792rm; here that step is the binder and the attach function.
hooks[text("_nv028792rm")] = ("_nv028792rm", lambda a, low: 0)
for label, target, vtables, binder, properties in GRAPHICS_FALCONS:
q(target + 0x68, target)
q(target + 0x58, target + 8)
q(target + 0x60, target + 0x28)
call("_nv005720rm", target + 8, CHIP, RM)
call("_nv005738rm", target + 0x28, CHIP, RM)
for offset, table in zip((0, 8, 0x28), vtables):
q(target + offset, RODATA + table)
call(binder, target, CHIP, RM)
call("_nv003365rm", target + 8, CHIP)
call(properties, target, CHIP, RM)
for owner in (NVDEC + 0xe8, SEC2 + 0xe8, PMU + 0xe8):
call("_nv003365rm", owner, CHIP)
cpu.hook_del(installed.pop(text("_nv028792rm")))
del hooks[text("_nv028792rm")]
OWNERS = {"FECS": (F_FECS, FECS + 8), "GPCCS": (F_GPCCS, GPCCS + 8),
"NVDEC": (F_NVDEC, NVDEC + 0xe8), "PMU": (F_PMU, PMU + 0xe8),
"SEC2": (F_SEC2, SEC2 + 0xe8)}
for falcon, owner in OWNERS.values():
call("_nv005876rm", falcon, CHIP, RM)
assert call("_nv021629rm", falcon, owner) == 0
q(owner + 0x18, falcon)
for offset, target in ((0x2080, NVDEC), (0x20c8, VBIOS), (0x2120, PMU), (0x2308, SEC2),
(0x2310, LSFM), (0x2318, ACR), (0x1e78, FUSE), (0x1e20, GPU),
(0x1fb8, GRAPHICS), (0x1ed0, MEMMGR)):
q(GPU + offset, target)
d(GPU + 0xcac, 0x20)
q(GRAPHICS + 0x15e8, FECS)
q(GRAPHICS + 0x15f0, GPCCS)
q(VBIOS + 0x270, vbios_270)
q(FUSE + 0x118, fuse_118)
q(PMU_CHILD, PMU_CHILD + 0x100)
q(PMU_CHILD + 0x140, pmu_child)
q(PMU + 0xb08, PMU_CHILD)
# Falcon configuration. The registration order FECS, GPCCS, NVDEC, PMU, SEC2 is
# the one the physical transcript shows: the image writer reads 0x10ac08 once
# per Falcon it passes while looking a client up, and the transcript has 3, 2,
# 1, 4 and 5 reads for the clients in image order (lines 140597 to 140613).
assert call("_nv027357rm", GPU, FECS, 0x5ee8dc00) == 0
assert call("_nv029624rm", GPU, GPCCS, 0x4781e800) == 0
assert call("_nv046468rm", GPU, NVDEC) == 0
assert call("_nv052063rm", GPU, PMU) == 0
assert call("_nv055607rm", GPU, SEC2) == 0
FALCONS = [pointer(GPU + 0x3bc8 + 8 * index) for index in range(word(GPU + 0x3e00))]
assert FALCONS == [F_FECS, F_GPCCS, F_NVDEC, F_PMU, F_SEC2], FALCONS
NAMES = {F_FECS: "FECS", F_GPCCS: "GPCCS", F_NVDEC: "NVDEC", F_PMU: "PMU", F_SEC2: "SEC2"}
BY_ID = {2: "FECS", 3: "GPCCS", 4: "NVDEC", 0: "PMU", 7: "SEC2"}
configured = {}
for falcon in FALCONS:
configured[NAMES[falcon]] = {
"+0x3a2": byte(falcon + 0x3a2), "+0x3a8": byte(falcon + 0x3a8),
"+0x548": f"{word(falcon + 0x548):#x}", "+0x560": word(falcon + 0x560),
"+0x5ec": f"{word(falcon + 0x5ec):#x}", "+0x650": word(falcon + 0x650),
"interface +0x13": byte(pointer(falcon + 0x5d8) + 0x13)}
assert {name: (state["+0x3a2"], state["+0x560"], state["+0x650"])
for name, state in configured.items()} == {
"FECS": (1, 0, 1), "GPCCS": (1, 0, 1), "NVDEC": (1, 6, 1), "PMU": (0, 0, 1),
"SEC2": (1, 6, 1)}, configured
properties = {"OBJSEC2+0x509": byte(SEC2 + 0x509), "OBJSEC2+0x50f": byte(SEC2 + 0x50f),
"OBJSEC2+0x513": byte(SEC2 + 0x513), "OBJSEC2+0x518": byte(SEC2 + 0x518),
"OBJACR+0x37b": byte(ACR + 0x37b), "OBJACR+0x37f": byte(ACR + 0x37f),
"OBJACR+0x381": byte(ACR + 0x381), "OBJACR+0x387": byte(ACR + 0x387),
"OBJACR+0x388": byte(ACR + 0x388), "OBJACR+0x392": byte(ACR + 0x392),
"OBJLSFM+0x190": byte(LSFM + 0x190), "PMU+0x56c": byte(PMU + 0x56c)}
assert properties == {"OBJSEC2+0x509": 1, "OBJSEC2+0x50f": 0, "OBJSEC2+0x513": 0,
"OBJSEC2+0x518": 0, "OBJACR+0x37b": 0, "OBJACR+0x37f": 1,
"OBJACR+0x381": 0, "OBJACR+0x387": 0, "OBJACR+0x388": 0,
"OBJACR+0x392": 0, "OBJLSFM+0x190": 0, "PMU+0x56c": 0}, properties
# The netlist the graphics engine keeps: the original descriptor, decoded by
# the original unpacker. Its code and data regions are what Graphics stores in
# the FECS and GPCCS objects (regions 1, 0, 3, 2; netlist slot 3).
q(SCRATCH, 0)
assert call("_nv017879rm", rodata(0x1148528), SCRATCH) == 0
NETLIST = pointer(SCRATCH)
netlist = bytes(cpu.mem_read(NETLIST, call("_nv017874rm", rodata(0x1148528))))
NETLIST_SHA256 = hashlib.sha256(netlist).hexdigest()
REGIONS = {struct.unpack_from("<I", netlist, 8 + 12 * index)[0]:
struct.unpack_from("<II", netlist, 12 + 12 * index)
for index in range(struct.unpack_from("<I", netlist, 4)[0])}
SETUP = sorted(executed)
def snapshot():
return (bytes(cpu.mem_read(DATA, DATA_BYTES)), heap[0],
bytes(cpu.mem_read(HEAP, heap[0] - HEAP)))
# Two starting states. RAW is the state after setup: InitLocked prepares every
# image itself. PREPARED has the NVDEC, PMU and SEC2 images already prepared
# by _nv028614rm with the traced register values (the function returns at
# once for a prepared Falcon), which saves three image decodes per case. The
# traced case, the record-selection cases and the first case of each kind
# start from RAW; a row's `pre` input says which state it used.
RAW = snapshot()
case.update(registers={0x10ac08: PHYSICAL["r10ac08"], 0x21644: PHYSICAL["r21644"]})
for falcon in (F_NVDEC, F_PMU, F_SEC2):
assert call("_nv028614rm", GPU, falcon) == 0
PREPARED = snapshot()
rows, counts, records_used = [], {}, {}
CLIENTS = ("NVDEC", "GPCCS", "FECS", "PMU", "SEC2")
DEFAULT = dict(PHYSICAL, vb=0, sli=0, pmu_child=0, a37f=1, a388=0, a387=0, s513=0, skip="",
lazy="", fc=REGIONS[1][0], fd=REGIONS[0][0], gc=REGIONS[3][0], gd=REGIONS[2][0],
patch="", pre=0)
def prepare(inputs):
state = PREPARED if inputs["pre"] else RAW
cpu.mem_write(DATA, state[0])
cpu.mem_write(HEAP, state[2])
cpu.mem_write(BLOB, bytes(BLOB_BYTES))
heap[0] = state[1]
diagnostics[0] = 0
subs.clear()
del reads[:], writes[:], services[:]
case.update(inputs=inputs, subs=[], registers={
0x10ac08: inputs["r10ac08"], 0x21644: inputs["r21644"], 0x10a108: inputs["r10a108"],
0x87108: inputs["r87108"]})
b(ACR + 0x37f, inputs["a37f"])
b(ACR + 0x388, inputs["a388"])
b(ACR + 0x387, inputs["a387"])
b(SEC2 + 0x513, inputs["s513"])
for name in filter(None, inputs["skip"].split(",")):
b(OWNERS[name][0] + 0x3a8, 1)
for name in filter(None, inputs["lazy"].split(",")):
falcon = OWNERS[name.lstrip("-")][0]
b(falcon + 0x3a2, 0 if name.startswith("-") else 1)
for target, slot, code, sizes, data, data_sizes, regions, lengths in (
(FECS, 0x1c8, 0x1d0, 0x1d8, 0x1e0, 0x1e8, (1, 0), (inputs["fc"], inputs["fd"])),
(GPCCS, 0x1f8, 0x1d8, 0x1e0, 0x1e8, 0x1f0, (3, 2), (inputs["gc"], inputs["gd"]))):
d(target + slot, 3)
for field, size_field, region, length in ((code, sizes, regions[0], lengths[0]),
(data, data_sizes, regions[1], lengths[1])):
assert 0 < length <= REGIONS[region][0]
q(target + field, NETLIST + REGIONS[region][1])
cpu.mem_write(target + size_field, struct.pack("<II", (length + 3) & ~3, length))
def apply_patches(inputs):
"""Edit prepared client state: NAME.len=N, NAME.dWORD=V, NAME.sig0/sig1."""
if not inputs["patch"]:
return
for falcon in FALCONS:
if not byte(falcon + 0x3a8):
assert call("_nv028614rm", GPU, falcon) == 0
for item in inputs["patch"].split(","):
target, value = item.split("=")
name, field = target.split(".")
falcon, value = OWNERS[name][0], int(value, 16)
if field == "len":
assert value <= word(falcon + 0x400)
d(falcon + 0x400, value)
elif field in ("sig0", "sig1"):
cpu.mem_write(pointer(falcon + 0x3f0) + 8 + 32 * int(field[3]), bytes(32))
else:
assert field[0] == "d"
record = pointer(falcon + (0x3d8 if name == "NVDEC" else 0x3e8))
assert record
d(record + int(field[1:], 16), value)
def nodes():
result, node = [], pointer(LSFM + 0x1a0)
while node:
result.append(node)
node = pointer(node)
return result
def run(kind, **changes):
inputs = dict(DEFAULT, **changes)
inputs["pre"] = int(kind not in ("V", "R") and kind in counts)
track(kind not in counts)
prepare(inputs)
apply_patches(inputs)
del reads[:]
status = [call("_nv043236rm", GPU, LSFM), 0, 0]
phases = [list(reads)]
count, total = half(LSFM + 0x192), word(LSFM + 0x194)
# OBJLSFM+1a8 points 0x18 bytes into the request the manager registered
# (id, bytes, alignment, two attribute words); +8 from there is the
# descriptor of the allocation.
record = pointer(LSFM + 0x1a8)
request = (struct.unpack("<5I", cpu.mem_read(record - 0x18, 20)) if record else ())
clients, order = [], nodes()
if status[0] == 0 and count and record:
# OBJACR InitLocked allocates the region and stores its descriptor here.
q(record + 8, REGION)
del reads[:]
status[1] = call("_nv043238rm", GPU, LSFM)
phases.append(list(reads))
if status[1] == 0:
del reads[:], writes[:]
status[2] = call("_nv043215rm", GPU, LSFM, REGION)
phases.append(list(reads))
blob = bytes(cpu.mem_read(BLOB, total)) if total and count else b""
assert not any(cpu.mem_read(BLOB + len(blob), BLOB_BYTES - len(blob)))
for node in order:
falcon = pointer(node + 0x1510)
name = NAMES[falcon]
lsb, image = word(node + 0x14), word(node + 0xf0)
descriptor = ""
if any(entry[1] == word(node + 0x104) and entry[2] == 84 for entry in writes
if entry[0] == "c"):
descriptor = blob[word(node + 0x104):word(node + 0x104) + 84].hex()
clients.append(":".join((name, blob[24 * len(clients):24 * len(clients) + 24].hex()
if status[2] == 0 and blob else "",
blob[lsb:lsb + 240].hex() if status[2] == 0 and blob else "",
descriptor, f"{image:x}", f"{word(falcon + 0x400):x}")))
used = {}
for field, label in ((0x488, "image"), (0x490, "nvdec_descriptor"),
(0x498, "descriptor"), (0x4b0, "signature")):
if pointer(falcon + field):
used[label] = f"{analysis(pointer(falcon + field)):#x}"
records_used.setdefault((name, inputs["r21644"], inputs["vb"]), used)
counts[kind] = counts.get(kind, 0) + 1
written = ",".join(f"{entry[0]}{entry[1]:x}+{entry[2]:x}" for entry in writes)
rows.append("|".join((
kind,
" ".join(f"{key}={value}" if isinstance(value, str) else f"{key}={value:x}"
for key, value in inputs.items()),
":".join(f"{value:x}" for value in status), f"{count:x}", f"{total:x}",
",".join(f"{value:x}" for value in request), written,
hashlib.sha256(blob).hexdigest() if status == [0, 0, 0] and blob else "-",
" ".join(clients), f"{diagnostics[0]:x}", ",".join(services))))
return {"inputs": inputs, "status": status, "blob": blob, "writes": [list(e) for e in writes],
"phases": phases, "nodes": order, "clients": clients, "request": request,
"subs": list(case["subs"])}
# ------------------------------------------------- the traced V100 case
physical = run("V")
assert physical["status"] == [0, 0, 0] and len(physical["blob"]) == 0xc1000, physical["status"]
blob = physical["blob"]
BLOB_SHA256 = hashlib.sha256(blob).hexdigest()
PHYSICAL_EXECUTED = sorted(executed - set(SETUP))
# Cross-check 1: every access of the image write in the BAR2 extract. The
# mapping starts at BAR2 0x2000; rep movsb runs carry no data, 32-bit stores do.
trace_writes, trace_data = [], {}
with EXTRACT.open() as stream:
lines = stream.read().split("\n")
first = next(index for index, line in enumerate(lines)
if line.startswith("U 2 2000 24 32454338 "))
last = next(index for index, line in enumerate(lines)
if line.startswith("E 32649867 W 4 2 2078 ffffffff "))
for line in lines[first:last + 1]:
part = line.split()
if part[0] == "U":
assert part[1] == "2", line
trace_writes.append(["c", int(part[2], 16) - 0x2000, int(part[3])])
else:
assert part[0] == "E" and part[2:5] == ["W", "4", "2"], line
offset = int(part[5], 16) - 0x2000
trace_data[offset] = int(part[6], 16)
if (trace_writes[-1][0] == "s"
and trace_writes[-1][1] + trace_writes[-1][2] == offset):
trace_writes[-1][2] += 4
else:
trace_writes.append(["s", offset, 4])
assert trace_writes == physical["writes"], next(
(index, a, e) for index, (a, e) in enumerate(zip(physical["writes"], trace_writes)) if a != e)
for offset, value in trace_data.items():
assert struct.unpack_from("<I", blob, offset)[0] == value, hex(offset)
stored = sum(entry[2] for entry in trace_writes if entry[0] == "s")
copied = [entry for entry in trace_writes if entry[0] == "c"]
covered = bytearray(len(blob))
for kind, offset, length in trace_writes:
covered[offset:offset + length] = b"\x01" * length
assert not any(value for value, mark in zip(blob, covered) if not mark)
# Cross-check 2: the register reads of the image write in the BAR0 transcript.
transcript = TRANSCRIPT.read_text().split("\n")
expected_reads = [(int(part[1], 16), int(part[2], 16))
for part in (line.split() for line in transcript[140596:140613])]
assert all(line.startswith("R ") for line in transcript[140596:140613])
assert physical["phases"][2] == expected_reads, (physical["phases"][2], expected_reads)
# Cross-check 3: the SEC2 boot descriptor. When SEC2 is later started in LS
# mode the driver writes the same 84-byte structure to its DMEM (transcript
# lines 165053 to 165073, after the address write of line 165052).
assert transcript[165051].split()[:3] == ["W", "0871c0", "0x1000000"]
dmem = b"".join(struct.pack("<I", int(line.split()[2], 16)) for line in transcript[165052:165073])
assert all(line.split()[:2] == ["W", "0871c4"] for line in transcript[165052:165073])
sec2_node = next(node for node in physical["nodes"] if NAMES[pointer(node + 0x1510)] == "SEC2")
assert blob[word(sec2_node + 0x104):word(sec2_node + 0x104) + 84] == dmem
# Cross-check 4: the PMU argument offset. The transcript writes the LS PMU
# arguments to DMEM 0xffd0 (line 147434 sets the port address).
pmu_node = next(node for node in physical["nodes"] if NAMES[pointer(node + 0x1510)] == "PMU")
pmu_descriptor = blob[word(pmu_node + 0x104):word(pmu_node + 0x104) + 84]
assert struct.unpack_from("<II", pmu_descriptor, 0x4c) == (1, 0xffd0)
layout = []
for index, node in enumerate(physical["nodes"]):
falcon = pointer(node + 0x1510)
header = struct.unpack_from("<6I", blob, 24 * index)
lsb = blob[header[1]:header[1] + 240]
fields = struct.unpack_from("<12I", lsb, 192)
signature = struct.unpack_from("<6I", lsb, 64)
has_descriptor = ["c", fields[5], 84] in physical["writes"]
layout.append({
"client": NAMES[falcon],
"wpr_header": {"offset": 24 * index, "falconID": header[0], "lsbOffset": header[1],
"bootstrapOwner": header[2], "bLazyBootstrap": header[3],
"binVersion": header[4], "status": header[5]},
"lsb_header": {"offset": header[1],
"signature": {"bPrdPresent": signature[0], "bDbgPresent": signature[1],
"falconId": signature[2], "bSupportsVersioning": signature[3],
"version": signature[4], "depMapCount": signature[5],
"sha256_of_192_bytes": hashlib.sha256(lsb[:192]).hexdigest()},
**{name: value for name, value in zip(
("ucodeOffset", "ucodeSize", "dataSize", "blCodeSize", "blImemOffset",
"blDataOffset", "blDataSize", "appCodeOffset", "appCodeSize",
"appDataOffset", "appDataSize", "flags"), fields)}},
"image": {"offset": fields[0], "bytes": word(falcon + 0x400),
"sha256": hashlib.sha256(
blob[fields[0]:fields[0] + word(falcon + 0x400)]).hexdigest()},
"boot_descriptor": ({"offset": fields[5], "bytes": 84,
"hex": blob[fields[5]:fields[5] + 84].hex()}
if has_descriptor else None),
"records": records_used[(NAMES[falcon], 1, 0)]})
assert [entry["client"] for entry in layout] == list(CLIENTS)
# ------------------------------------------------------------- variations
generator = random.Random(0x57505242)
# Client subsets: a Falcon whose +3a8 byte is set is not managed.
for mask in range(1, 16):
run("S", skip=",".join(name for bit, name in enumerate(("NVDEC", "GPCCS", "FECS", "SEC2"))
if mask >> bit & 1))
# Bootstrap owner, the lazy-bootstrap bytes and OBJSEC2+513.
for a388, a37f in ((0, 0), (1, 0), (1, 1)):
for s513 in (0, 1):
run("O", a388=a388, a37f=a37f, s513=s513)
run("O", s513=1)
for lazy in ("-NVDEC", "-GPCCS", "-FECS", "PMU", "-SEC2", "-NVDEC,-GPCCS,-FECS,PMU,-SEC2"):
for s513 in (0, 1):
run("O", lazy=lazy, s513=s513)
# Debug mode (bit 20 of 0x10ac08) selects which signature half must be present.
for value in (0x100000, 0xffefffff, 0xffffffff):
run("D", r10ac08=value)
for name in CLIENTS:
for field in ("sig0", "sig1"):
for value in (0, 0x100000):
run("D", r10ac08=value, patch=f"{name}.{field}=0")
run("D", patch="NVDEC.sig0=0,GPCCS.sig0=0,FECS.sig0=0")
# Region address and the Falcon configuration words that give the DMEM size.
for base in (0, 0x100, 0x20000, 0x7fde80000, 0xfffe0000, 0x123456700, 0x7ffffff00,
0xffffffffff00):
run("A", base=base)
for value in (0, 0x200, 0x400, 0x3fe00, 0x40000, 0x400e0100, 0x20420100, 0xffffffff, 0x1e00):
run("A", r10a108=value)
run("A", r87108=value)
# Sizes: netlist region lengths, image lengths and descriptor words.
for index in range(24):
lengths = {key: generator.choice((1, 3, 4, 255, 256, 257, generator.randrange(1, limit + 1),
limit - 1, limit))
for key, limit in (("fc", REGIONS[1][0]), ("fd", REGIONS[0][0]),
("gc", REGIONS[3][0]), ("gd", REGIONS[2][0]))}
run("L", **lengths)
for index in range(24):
patches = []
for name, limit in (("NVDEC", 230144), ("PMU", 288512), ("SEC2", 204544)):
if generator.random() < 0.7:
patches.append(f"{name}.len={generator.choice((4, 252, 256, 260, 4096, limit - 4, generator.randrange(1, limit // 4) * 4)):x}")
run("L", patch=",".join(patches) or "PMU.len=100")
for index in range(40):
patches = []
for name in ("PMU", "SEC2"):
for field in (0x58, 0x5c, 0x64, 0x68, 0x70, 0x78, 0x7c, 0x80, 0x84):
if generator.random() < 0.4:
# +0x64 and +0x80 feed an assertion that wants multiples of 256.
value = (generator.randrange(0, 0x400) << 8 if field in (0x64, 0x80, 0x78)
else generator.randrange(0, 0x40000))
patches.append(f"{name}.d{field:x}={value:x}")
for field in (4, 8, 0xc, 0x18, 0x1c, 0x20, 0xc0, 0xc4, 0x168):
if generator.random() < 0.4:
patches.append(f"NVDEC.d{field:x}={generator.randrange(0, 0x40000):x}")
run("P", patch=",".join(patches) or "PMU.d58=100")
# The NVDEC descriptor's segment count.
for count in (0, 1, 2, 20):
run("P", patch=f"NVDEC.d10={count:x}")
# NVDEC debug records (bit 0 of 0x21644 clear), the GPU+20c8 function.
run("R", r21644=0)
run("R", r21644=0xfffffffe)
run("R", r21644=0xffffffff)
run("R", vb=1)
# Failures: a multi-GPU group, the PMU service, no client at all.
run("F", sli=1)
run("F", pmu_child=0x55)
run("F", pmu_child=0xffff, skip="SEC2")
out = ROOT / "target/gpu-stage"
out.mkdir(parents=True, exist_ok=True)
oracle = "\n".join(rows) + "\n"
(out / "original-wpr-blob.txt").write_text(oracle)
(out / "original-wpr-blob-gv100.bin").write_bytes(blob)
report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
"function_chain": [
"OBJLSFM InitLocked _nv043236rm: clients in the order SEC2, PMU, then the other "
"registered Falcons; _nv043182rm per client (image preparation _nv028614rm, callback "
"+118 _nv043233rm, a 0x1518-byte record with the WPR and LSB headers, pushed at the list "
"head); placement; region request through _nv016949rm",
"OBJLSFM Load _nv043238rm: per managed Falcon the function at +118 (_nv028385rm), which "
"takes a sub-descriptor of the region from _nv043186rm",
"OBJACR Load _nv016956rm -> OBJACR+128 _nv016931rm -> _nv043215rm(GPU, OBJLSFM, region "
"descriptor): map, per client header, LSB header, boot descriptor (_nv043231rm -> "
"interface +70 _nv028829rm -> _nv028607rm) unless the client has its own descriptor "
"format, image (_nv028571rm); terminator; unmap"],
"setup_functions": SETUP,
"executed_in_the_physical_case": PHYSICAL_EXECUTED,
"executed": sorted(executed - set(SETUP)),
"executed_note": "Function entries are recorded for the setup, the traced case and the "
"first case of each kind.",
"fixture_supplied": list(HOOKED) + ["os_mem_copy", "_nv028792rm (setup only)"] + sorted(
name for key, (name, unused) in hooks.items() if isinstance(key, int) and key >= SERVICE),
"stored_by_harness": {
"FECS and GPCCS objects": "vtables and self pointers as the creators _nv006485rm and "
"_nv006495rm store them",
"FECS +1c8/+1d0/+1d8/+1e0/+1e8, GPCCS +1f8/+1d8/+1e0/+1e8/+1f0":
"netlist slot 3 and the code and data regions (ids 1, 0 and 3, 2) of the original "
"netlist descriptor 0x1148528; produced in the driver by the graphics engine",
"Falcon objects": "bound with _nv005876rm, attached with _nv021629rm, pointer stored at "
"interface +18 (the steps of _nv028792rm)",
"Falcon registration order": "FECS, GPCCS, NVDEC, PMU, SEC2 (from the transcript; see "
"physical_transcript.register_reads)",
"GPU children": "2080 OBJBSP, 20c8, 2120 PMU class, 2308 OBJSEC2, 2310 OBJLSFM, 2318 "
"OBJACR, 1e78, 1fb8 Graphics, 1ed0 memory manager",
"GPU+0xcac": "0x20", "PMU+0xb08": "service object",
"region record +8": "the region's memory descriptor (stored by OBJACR InitLocked)"},
"chip_identification": {key: f"{value:#x}" for key, value in identity.items()},
"properties_after_setup": properties,
"falcons_after_configuration": configured,
"netlist_sha256": NETLIST_SHA256,
"physical_case": {
"inputs": {key: (f"{value:#x}" if isinstance(value, int) else value)
for key, value in PHYSICAL.items()},
"blob_bytes": len(blob), "blob_sha256": BLOB_SHA256,
"blob_file": "target/gpu-stage/original-wpr-blob-gv100.bin",
"terminator": {"offset": 24 * len(layout), "value": "0xffffffff"},
"region_request": {"id": physical["request"][0],
"bytes": f"{physical['request'][1]:#x}",
"alignment": f"{physical['request'][2]:#x}",
"attributes": list(physical["request"][3:5])},
"sub_descriptors_of_load": [[f"{offset:#x}", f"{size:#x}"]
for offset, size in physical["subs"][:len(layout)]],
"layout": layout,
"register_reads": {
"InitLocked": [f"{offset:#x}={value:#x}" for offset, value in physical["phases"][0]],
"Load": [f"{offset:#x}={value:#x}" for offset, value in physical["phases"][1]],
"image_write": [f"{offset:#x}={value:#x}" for offset, value in physical["phases"][2]]},
"writes_in_order": [f"{'copy' if kind == 'c' else 'stores'} {offset:#x}+{length}"
for kind, offset, length in physical["writes"]]},
"physical_transcript": {
"bar2_extract": {"file": "target/trace/b3-bar12-rle.txt",
"sha256": hashlib.sha256(EXTRACT.read_bytes()).hexdigest(),
"lines": [first + 1, last + 1],
"full_trace_lines": [32454338, 32649867],
"copies_without_data": len(copied),
"stored_bytes_with_data": stored,
"order_offsets_and_lengths_equal": True,
"stored_data_equal": True,
"bytes_never_written_are_zero_in_the_blob": True},
"register_reads": {"file": "target/trace/b3-bar0.txt", "lines": [140597, 140613],
"sequence": [f"{offset:#x}={value:#x}"
for offset, value in expected_reads],
"reproduced_by_original_instructions": True},
"sec2_boot_descriptor": {"file": "target/trace/b3-bar0.txt", "lines": [165053, 165073],
"equals_blob_descriptor_at": f"{word(sec2_node + 0x104):#x}"},
"pmu_argument_offset": {"transcript": "DMEM 0xffd0 (analysis report)",
"blob_descriptor_argv": "0xffd0"}},
"records_selected": {f"{name} r21644={r21644:#x} vb={vb}": used
for (name, r21644, vb), used in sorted(records_used.items())},
"cases": len(rows), "cases_by_kind": {
"traced V100 (V)": counts["V"], "client subsets (S)": counts["S"],
"owner and lazy flags (O)": counts["O"], "debug mode and signatures (D)": counts["D"],
"addresses and DMEM sizes (A)": counts["A"], "lengths (L)": counts["L"],
"descriptor words (P)": counts["P"], "record selection (R)": counts["R"],
"failures (F)": counts["F"]},
"oracle": "target/gpu-stage/original-wpr-blob.txt",
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
"scope": "Original GV100 WPR image build with creator- and binder-selected function tables. "
"Register values, the region address and the listed services are fixture-supplied; "
"no hardware executed."}
(ROOT / "reports/gpu-wpr-blob-original.json").write_text(json.dumps(report, indent=2) + "\n")
print(f"{len(rows)} original WPR image cases " + str(counts) + f"; executed "
f"{len(executed)} functions; physical blob {len(blob):#x} bytes sha256 {BLOB_SHA256}; "
f"BAR2 extract lines {first + 1}-{last + 1} and transcript lines 140597-140613 reproduced; "
f"oracle sha256 {report['oracle_sha256']}")
if "--rows" in sys.argv:
print(oracle)