Files
nvdriver/tools/generate_pf_rom_validation_oracle.py

337 lines
12 KiB
Python

#!/usr/bin/env python3
"""Original ROM image validator + NPDE helper + CPU image reader in isolated RAM."""
from __future__ import annotations
import argparse
import json
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_xform_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
NAMES = ["_nv059839rm", "_nv000307rm", "_nv054392rm"]
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, 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)
def address(n: str) -> int:
return TEXT + syms[n]["st_value"]
def w32(a: int, v: int) -> None:
uc.mem_write(a, struct.pack("<I", v))
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)
addr_memset = address("_nv052705rm")
addr_logs = (address("_nv047869rm"), address("_nv047868rm"), address("_nv046745rm"))
def hook(emu, pc, _size, _user):
if 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 in addr_logs:
ret(0)
uc.hook_add(unicorn.UC_HOOK_CODE, hook)
base = [0x21, 512, 0xAA55, 0x52494350, 0x10DE, 0, 3, 1, 1, 1, 0, 12, 1, 1, 0, 1, 0, 0]
specs = []
for flags in range(64):
for good in (0, 1):
c = base.copy()
c[0] = flags
c[9] = good
specs.append(c)
for index, values in (
(1, [0, 64, 511, 512, 1024]),
(2, [0xAA55, 0x4E56, 0xBB77, 0x1234]),
(3, [0x52494350, 0x5344504E, 0x53494752, 0x12345678]),
(4, [0x10DE, 0x1234]),
(5, [0, 1, 2, 3, 0x70, 0x71]),
(6, [0, 3, 0x203, 0x10003]),
(7, [0, 1, 2]),
(17, [0, 7, 8, 255]),
):
for value in values:
c = base.copy()
c[index] = value
specs.append(c)
for flags in (0, 1, 4, 8, 0x10, 0x21, 0x2B, 0x2F):
for ver, length, blocks, last, nflags in (
(0x100, 10, 1, 1, 0),
(0x101, 11, 1, 1, 0),
(0x100, 12, 1, 1, 4),
(0x102, 12, 1, 1, 0),
(0x100, 12, 2, 1, 0),
):
c = base.copy()
c[0] = flags
c[1] = 1024
c[9] = 0
c[10:15] = [ver, length, blocks, last, nflags]
specs.append(c)
for platform in (0, 1):
for flags in (1, 4, 5, 0x10, 0x21, 0x25):
c = base.copy()
c[0] = flags
c[9] = 0
c[16] = platform
specs.append(c)
for flags in (0, 1, 4, 5, 8, 0x21, 0x25):
c = base.copy()
c[0] = flags
c[1] = 1024
c[15] = 2
specs.append(c)
rows = []
for spec in specs:
(
flags,
declared,
romsig,
pcirsig,
vendor,
code,
cls,
blocks,
last,
good,
version,
extlen,
extblocks,
extlast,
extflags,
images,
platform,
count,
) = spec
if blocks == 0 and (flags & 4) == 0:
continue
data = bytearray(2048)
for n in range(images):
off = n * 512
struct.pack_into("<H", data, off, romsig)
struct.pack_into("<H", data, off + 0x18, 0x40)
struct.pack_into("<I", data, off + 0x40, pcirsig)
struct.pack_into("<I", data, off + 0x44, 0x1DB50000 | vendor)
data[off + 0x4D : off + 0x50] = bytes([(cls >> 16) & 255, (cls >> 8) & 255, cls & 255])
struct.pack_into("<H", data, off + 0x50, blocks)
data[off + 0x54] = code
data[off + 0x55] = (last if n == images - 1 else 0) << 7
if version:
struct.pack_into("<H", data, off + 0x4A, 0x20)
struct.pack_into(
"<IHHHBB",
data,
off + 0x60,
0x4544504E,
version,
extlen,
extblocks,
extlast << 7,
extflags,
)
data[off + 511] = (-sum(data[off : off + 511]) + (0 if good else 1)) & 255
uc.mem_write(DATA, bytes(0x40000))
uc.mem_write(DATA + 0x100000, bytes(data))
uc.mem_write(DATA + 0x92B, bytes([platform]))
w32(DATA + 0xCEC, 0x1DB510DE)
diag = bytearray(88)
diag[0] = 0x34
diag[1] = count
struct.pack_into("<II", diag, 0x50, 0xAABBCCDD, 0x11223344)
uc.mem_write(DATA + 0x20000, bytes(diag))
uc.reg_write(x86.UC_X86_REG_RDI, DATA)
uc.reg_write(x86.UC_X86_REG_RSI, DATA + 0x100000)
uc.reg_write(x86.UC_X86_REG_RDX, declared)
uc.reg_write(x86.UC_X86_REG_RCX, DATA + 0x21000)
uc.reg_write(x86.UC_X86_REG_R8, flags)
uc.reg_write(x86.UC_X86_REG_R9, DATA + 0x21004)
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFE8)
uc.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
w64(STACK + 0xFFE8, STOP)
w64(STACK + 0xFFF0, DATA + 0x20000)
uc.emu_start(address("_nv059839rm"), STOP, count=50000)
require(uc.reg_read(x86.UC_X86_REG_RIP) == STOP, f"_nv059839rm did not reach STOP for {spec}")
status = uc.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF
consumed, types = struct.unpack("<II", uc.mem_read(DATA + 0x21000, 8))
out = list(uc.mem_read(DATA + 0x20000, 88))
rows.append(
{
"spec": spec,
"status": status,
"consumed": consumed,
"types": types,
"diagnostics": out,
}
)
physical = []
capture = ROOT / "target/physical/prom-b3.bin"
if capture.exists():
image = capture.read_bytes()
for flags in (0, 1, 4, 5, 0x21):
for platform in (0, 1):
uc.mem_write(DATA, bytes(0x40000))
uc.mem_write(DATA + 0x100000, image)
uc.mem_write(DATA + 0x92B, bytes([platform]))
w32(DATA + 0xCEC, 0x1DB510DE)
diag = bytearray(88)
diag[0] = 0x34
struct.pack_into("<II", diag, 0x50, 0xAABBCCDD, 0x11223344)
uc.mem_write(DATA + 0x20000, bytes(diag))
uc.reg_write(x86.UC_X86_REG_RDI, DATA)
uc.reg_write(x86.UC_X86_REG_RSI, DATA + 0x100000)
uc.reg_write(x86.UC_X86_REG_RDX, len(image))
uc.reg_write(x86.UC_X86_REG_RCX, DATA + 0x21000)
uc.reg_write(x86.UC_X86_REG_R8, flags)
uc.reg_write(x86.UC_X86_REG_R9, DATA + 0x21004)
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFE8)
uc.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
w64(STACK + 0xFFE8, STOP)
w64(STACK + 0xFFF0, DATA + 0x20000)
uc.emu_start(address("_nv059839rm"), STOP, count=40000000)
require(uc.reg_read(x86.UC_X86_REG_RIP) == STOP, "physical validation did not reach STOP")
status = uc.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF
consumed, types = struct.unpack("<II", uc.mem_read(DATA + 0x21000, 8))
out = list(uc.mem_read(DATA + 0x20000, 88))
physical.append(
{
"flags": flags,
"platform": platform,
"status": status,
"consumed": consumed,
"types": types,
"diagnostics": out,
}
)
print(
"physical image",
[(c["flags"], c["platform"], c["status"], hex(c["consumed"]), c["types"]) for c in physical],
flush=True,
)
else:
previous = ROOT / "reports/gpu-pf-rom-validation-oracle.json"
if previous.exists():
physical = json.loads(previous.read_text()).get("physical_image", [])
lines = [
"// Actual original validator + NPDE helper + CPU image reader.",
"const CASES: &[Case] = &[",
]
for c in rows:
lines.append(
f"Case {{ spec: {c['spec']}, status: {c['status']}, consumed: {c['consumed']}, "
f"types: {c['types']}, diagnostics: {c['diagnostics']} }},"
)
lines.append("];")
lines += [
"// Original validator on the physical GV100 PROM capture: flags, platform, status, consumed, types, diagnostics.",
"#[allow(dead_code)]",
"type PhysicalCase = (u32, bool, u32, u32, u32, [u8; 88]);",
"#[allow(dead_code)]",
"const PHYSICAL_CASES: &[PhysicalCase] = &[",
]
for c in physical:
lines.append(
f"({c['flags']}, {'true' if c['platform'] else 'false'}, {c['status']}, "
f"{c['consumed']}, {c['types']}, {c['diagnostics']}),"
)
lines.append("];")
write_or_check_text(
ROOT / "src/nvidia/src/gpu/rom_validate_vectors.rs",
"\n".join(lines) + "\n",
options.check,
"PF ROM validation Rust vectors",
)
report = {
"artifact_sha256": DIGEST,
"functions": NAMES,
"cases": len(rows),
"physical_image": physical,
"interceptions": ["pure memset", "log/assert diagnostics"],
"rows": rows,
"limits": [
"No hardware/native calls",
"Padded RAM prevents original unchecked-read faults; Rust bounds checks are tested separately",
"Original nonprogressing zero-length chain excluded",
],
}
write_or_check_json(
ROOT / "reports/gpu-pf-rom-validation-oracle.json",
report,
options.check,
"PF ROM validation JSON report",
)
print(len(rows), "original image validation cases")
return 0
if __name__ == "__main__":
raise SystemExit(main())