Files
nvdriver/tools/generate_pf_rom_cache_oracle.py

292 lines
10 KiB
Python

#!/usr/bin/env python3
"""Original ROM cache .text/.bss mutations in isolated RAM."""
from __future__ import annotations
import argparse
from pathlib import Path
import struct
import sys
if str(Path(__file__).resolve().parent) not in sys.path:
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _pf_rom_source_acpi_elf import (
DIGEST,
ROOT,
discover_rm_object,
link_rom_functions,
parse_elf64_rm_object,
require,
require_unicorn,
write_or_check_json,
write_or_check_text,
)
TEXT = 0x10000000
DATA = 0x30000000
STACK = 0x40000000
RODATA = 0x50000000
STOP = 0x60000000
BSS = 0x70000000
NAMES = ["_nv059881rm", "_nv059882rm", "_nv059883rm", "_nv059884rm"]
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument(
"--check",
action="store_true",
help="Verify Rust vectors and JSON report without modifying files.",
)
p.add_argument(
"--rm-object",
default=None,
help="Path to 580.178.04 nv-kernel.o_binary (overrides auto-discovery).",
)
return p
def main(argv: list[str] | None = None) -> int:
options = build_parser().parse_args(argv)
unicorn, x86 = require_unicorn()
rm_object = discover_rm_object(options.rm_object)
parsed = parse_elf64_rm_object(rm_object)
syms = parsed["defined"]
text, rodata = link_rom_functions(
parsed,
NAMES,
text_base=TEXT,
rodata_base=RODATA,
bss_base=BSS,
thunk_rax_addr=STOP + 0x100,
)
uc = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_64)
uc.mem_map(TEXT, (len(text) + 4095) & ~4095)
uc.mem_write(TEXT, bytes(text))
uc.mem_map(RODATA, (len(rodata) + 4095) & ~4095)
uc.mem_write(RODATA, rodata)
uc.mem_map(DATA, 0x400000)
uc.mem_map(STACK, 0x10000)
uc.mem_map(STOP, 4096)
uc.mem_map(BSS, 0x10000)
def address(n: str) -> int:
return TEXT + syms[n]["st_value"]
def w64(a: int, v: int) -> None:
uc.mem_write(a, struct.pack("<Q", v))
def ret(value: int) -> None:
rsp = uc.reg_read(x86.UC_X86_REG_RSP)
rip = struct.unpack("<Q", uc.mem_read(rsp, 8))[0]
uc.reg_write(x86.UC_X86_REG_RAX, value)
uc.reg_write(x86.UC_X86_REG_RSP, rsp + 8)
uc.reg_write(x86.UC_X86_REG_RIP, rip)
st = {"allocated": [], "freed": [], "fail_allocate": False, "locked": False}
addr_alloc = address("_nv052687rm")
addr_free = address("_nv052701rm")
addr_memcpy = address("_nv052695rm")
addr_memset = address("_nv052705rm")
addr_lock = address("_nv052743rm")
addr_unlock = address("_nv052747rm")
addr_destroy = address("_nv052745rm")
addr_log = address("_nv047869rm")
def hook(emu, pc, _size, _user):
if pc == addr_alloc:
if st["fail_allocate"]:
st["fail_allocate"] = False
ret(0)
return
size = emu.reg_read(x86.UC_X86_REG_RDI)
require(0 < size <= 32, f"unexpected cache alloc size {size}")
value = DATA + 0x100000 + len(st["allocated"]) * 64
st["allocated"].append(value)
emu.mem_write(value, bytes(64))
ret(value)
elif pc == addr_free:
value = emu.reg_read(x86.UC_X86_REG_RDI)
if value:
st["freed"].append(value)
ret(0)
elif pc == addr_memcpy:
dst = emu.reg_read(x86.UC_X86_REG_RDI)
src = emu.reg_read(x86.UC_X86_REG_RDX)
size = emu.reg_read(x86.UC_X86_REG_RCX)
emu.mem_write(dst, bytes(emu.mem_read(src, size)))
ret(dst)
elif pc == addr_memset:
dst = emu.reg_read(x86.UC_X86_REG_RDI)
value = emu.reg_read(x86.UC_X86_REG_RSI) & 255
count = emu.reg_read(x86.UC_X86_REG_RDX)
emu.mem_write(dst, bytes([value]) * count)
ret(dst)
elif pc == addr_lock:
require(not st["locked"], "recursive lock acquire")
st["locked"] = True
ret(0)
elif pc == addr_unlock:
require(st["locked"], "unlock without lock")
st["locked"] = False
ret(0)
elif pc == addr_destroy:
require(not st["locked"], "destroy mutex while locked")
ret(0)
elif pc == addr_log:
ret(0)
uc.hook_add(unicorn.UC_HOOK_CODE, hook)
arg_regs = [
x86.UC_X86_REG_RDI,
x86.UC_X86_REG_RSI,
x86.UC_X86_REG_RDX,
x86.UC_X86_REG_RCX,
x86.UC_X86_REG_R8,
]
def call(name: str, args: list[int]) -> int:
for reg, value in zip(arg_regs, args):
uc.reg_write(reg, value)
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFE8)
uc.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
w64(STACK + 0xFFE8, STOP)
uc.emu_start(address(name), STOP, count=20000)
require(uc.reg_read(x86.UC_X86_REG_RIP) == STOP, f"{name} did not reach STOP")
return uc.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF
scenarios = [
[
[0, 8, 10, 1, 1, 0],
[0, 8, 10, 2, 2, 0],
[1, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 8, 11, 3, 1, 0],
[0, 8, 10, 4, 0, 0],
[0, 8, 10, 5, 0, 1],
[1, 99, 0, 0, 0, 0],
[2, 0, 0, 0, 1, 0],
[2, 0, 0, 0, 2, 0],
[0, 0, 0, 0, 0, 0],
],
[[0, 8, i, i + 1, 0, 0] for i in range(32)]
+ [[0, 8, 999, 9, 0, 0], [0, 8, 0, 99, 0, 0]],
[[0, 8, 10, i, i, 0] for i in range(1, 33)]
+ [
[0, 8, 10, 33, 33, 0],
[2, 0, 0, 0, 33, 0],
[0, 8, 10, 34, 1, 0],
[0, 8, 11, 35, 34, 0],
[2, 0, 0, 0, 34, 0],
],
]
rows = []
for scenario, ops in enumerate(scenarios):
uc.mem_write(BSS, bytes(0x10000))
st["allocated"].clear()
st["freed"].clear()
w64(BSS + 0x8898, 1)
for operation in ops:
kind, size, checksum, payload, owner, fail = operation
st["fail_allocate"] = bool(fail)
w64(DATA + 0x100, 0xDEADBEEF)
if kind == 0:
image = struct.pack("<II", payload, (checksum - payload) & 0xFFFFFFFF)
uc.mem_write(DATA + 0x20000, image)
status = call("_nv059881rm", [DATA + 0x100, DATA + 0x20000, size, checksum, owner])
published = struct.unpack("<Q", uc.mem_read(DATA + 0x100, 8))[0]
elif kind == 1:
ptr = (
struct.unpack("<Q", uc.mem_read(BSS + 0x88A0 + size * 24, 8))[0]
if size < 32
else 0xDEADBEEF
)
status = call("_nv059882rm", [ptr])
published = 0xDEADBEEF
else:
status = call("_nv059884rm", [DATA + 0x100, DATA + 0x108, DATA + 0x10C, owner])
published = struct.unpack("<Q", uc.mem_read(DATA + 0x100, 8))[0]
count = struct.unpack("<I", uc.mem_read(BSS + 0x8BA0, 4))[0]
owners = struct.unpack("<I", uc.mem_read(BSS + 0x8DA8, 4))[0]
entries = []
pointers = []
for i in range(count):
ptr, length, total, refs = struct.unpack("<QIII", uc.mem_read(BSS + 0x88A0 + i * 24, 20))
pointers.append(ptr)
first, second = struct.unpack("<II", uc.mem_read(ptr, 8))
entries.append([length, total, refs, first, second])
owner_rows = []
for i in range(owners):
key, target = struct.unpack("<QQ", uc.mem_read(BSS + 0x8BA8 + i * 16, 16))
owner_rows.append([key, (target - (BSS + 0x88A0)) // 24])
index = pointers.index(published) if published in pointers else -1
rows.append(
{
"scenario": scenario,
"op": operation,
"status": status,
"published": index,
"count": count,
"owners": owners,
"entries": entries,
"owner_rows": owner_rows,
}
)
call("_nv059883rm", [])
require(
len(st["freed"]) == len(st["allocated"]) and set(st["freed"]) == set(st["allocated"]),
"ROM cache shutdown leaked allocations",
)
require(struct.unpack("<I", uc.mem_read(BSS + 0x8BA0, 4))[0] == 0, "entry count not zeroed")
require(struct.unpack("<I", uc.mem_read(BSS + 0x8DA8, 4))[0] == 0, "owner count not zeroed")
require(struct.unpack("<Q", uc.mem_read(BSS + 0x8898, 8))[0] == 0, "mutex handle not cleared")
lines = [
"// Original cache .text/.bss mutations and every image byte (8byte inputs).",
"const CACHE_CASES: &[Case] = &[",
]
for row in rows:
ent = row["entries"] + [[0] * 5] * (32 - row["count"])
own = row["owner_rows"] + [[0] * 2] * (32 - row["owners"])
lines.append(
f"Case {{ scenario: {row['scenario']}, op: {row['op']}, status: {row['status']}, "
f"published: {row['published']}, count: {row['count']}, owners: {row['owners']}, "
f"entries: {ent}, owner_rows: {own} }},"
)
lines.append("];")
write_or_check_text(
ROOT / "src/nvidia/src/gpu/rom_cache_vectors.rs",
"\n".join(lines) + "\n",
options.check,
"PF ROM cache Rust vectors",
)
report = {
"artifact_sha256": DIGEST,
"functions": NAMES,
"operations": len(rows),
"shutdown_cases": len(scenarios),
"interceptions": ["CPU allocation/free/copy/zero", "mutex serialized contract", "logs"],
"rows": rows,
"limits": [
"Isolated original text+globalbss; no native/hardware calls",
"Imagebytes cover8byte fixtures; checksum argument passed directly as helper API requires",
],
}
write_or_check_json(
ROOT / "reports/gpu-pf-rom-cache-oracle.json",
report,
options.check,
"PF ROM cache JSON report",
)
print(len(rows), "original cache mutation operations")
return 0
if __name__ == "__main__":
raise SystemExit(main())