Files
nvdriver/tools/generate_pf_sli_oracle.py

298 lines
9.7 KiB
Python

#!/usr/bin/env python3
"""Execute original SLI logo wrapper/read callbacks in isolated Unicorn RAM only."""
from __future__ import annotations
import argparse
import itertools
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_board_oracle_elf import (
DIGEST,
ROOT,
discover_rm_object,
parse_elf64_rm_object,
require,
require_unicorn,
write_or_check_json,
write_or_check_text,
)
TEXT = 0x10000000
DATA = 0x30000000
STACK = 0x40000000
STOP = 0x60000000
HOOK = 0x70000000
NAMES = [
"_nv030846rm",
"_nv030840rm",
"_nv030841rm",
"_nv030603rm",
"_nv031178rm",
"_nv023428rm",
"_nv023426rm",
"_nv024751rm",
]
def link_text(parsed: dict) -> bytearray:
symbols = parsed["symbols"]
syms = parsed["defined"]
text = bytearray(parsed["section_bytes"](".text"))
text_index = parsed["section_index"](".text")
ranges = [(syms[n]["st_value"], syms[n]["st_size"]) for n in NAMES]
for off, sym_idx, r_type, addend in parsed["iter_relocations"](".rela.text"):
if not any(a <= off < a + size for a, size in ranges):
continue
sym = symbols[sym_idx]
if sym["name"] == "__x86_indirect_thunk_rax":
value = HOOK + 32 + addend
else:
require(
sym["st_shndx"] == text_index,
f"unexpected section {(sym['name'], sym['st_shndx'])}",
)
value = TEXT + sym["st_value"] + addend
if r_type == 2:
value -= TEXT + off
else:
require(r_type == 11, f"unexpected relocation type {r_type}")
struct.pack_into("<i", text, off, value)
return text
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 = link_text(parsed)
addresses = {n: TEXT + syms[n]["st_value"] for n in NAMES}
helper = TEXT + syms["_nv029941rm"]["st_value"]
thunk = HOOK + 32
group_helper = TEXT + syms["_nv031434rm"]["st_value"]
gpu_helper = TEXT + syms["_nv030592rm"]["st_value"]
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(DATA, 0x40000)
uc.mem_map(STACK, 0x10000)
uc.mem_map(STOP, 4096)
uc.mem_map(HOOK, 4096)
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)
current: dict[str, int] = {}
trace: list[tuple[str, int]] = []
def hook(emu, address, _size, _user):
if address == helper:
ret(current["route"])
elif address == group_helper:
ret(current["group"])
elif address == gpu_helper:
ret(1 << current["device_view"])
elif address == thunk:
emu.reg_write(x86.UC_X86_REG_RIP, emu.reg_read(x86.UC_X86_REG_RAX))
elif address == HOOK:
reg = emu.reg_read(x86.UC_X86_REG_RSI) & 0xFFFFFFFF
trace.append(("read", reg))
ret(current["period"] if (reg & 0x7FF) == 0x80 else current["duty"])
elif address == HOOK + 16:
trace.append(("write", emu.reg_read(x86.UC_X86_REG_RCX) & 0xFFFFFFFF))
ret(current["write_status"])
uc.hook_add(unicorn.UC_HOOK_CODE, hook)
rows = []
initializers = []
for name in ("_nv030840rm", "_nv030841rm"):
for seed in (0, 0xFFFFFFFF, 0x76543210):
uc.mem_write(DATA, bytes(0x40000))
w32(DATA + 0x6B40, seed)
uc.reg_write(x86.UC_X86_REG_RDI, DATA)
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFF8)
w64(STACK + 0xFFF8, STOP)
uc.emu_start(addresses[name], STOP, count=100)
require(uc.reg_read(x86.UC_X86_REG_RIP) == STOP, f"{name} did not reach STOP")
initializers.append(
{
"function": name,
"seed": seed,
"value": struct.unpack("<I", uc.mem_read(DATA + 0x6B40, 4))[0],
}
)
for (
display,
route,
logo_brightness,
sli_brightness,
mode,
group,
device_view,
write_status,
period,
) in itertools.product(
range(4),
[0xFFFFFFFF, 0],
[0xFFFFFFFF, 101],
[0xFFFFFFFF, 55],
[0, 1, 2, 7],
[0, 1, 3, 7],
range(3),
[0, 0x35],
[0, 100],
):
current.update(
route=route,
period=period,
duty=0xC0000019,
write_status=write_status,
group=group,
device_view=device_view,
)
trace.clear()
uc.mem_write(DATA, bytes(0x40000))
w32(DATA + 0x6AAC, mode)
w32(DATA + 0x6AB0, 0x12345678)
w32(DATA + 0x6AB4, 0x11111111)
w32(DATA + 0x6AB8, logo_brightness)
w32(DATA + 0x6ABC, sli_brightness)
w64(DATA + 0x668, addresses["_nv030603rm"])
w64(DATA + 0x670, addresses["_nv031178rm"])
w64(DATA + 0x1F70, DATA + 0x10000 if display else 0)
w32(DATA + 0x10000 + 0x1AB8, 0 if display == 2 else 2)
w64(
DATA + 0x10000 + 0x11E8,
addresses["_nv023426rm"] if display == 1 else addresses["_nv023428rm"],
)
w64(
DATA + 0x10000 + 0x11E0,
addresses["_nv024751rm"] if display == 1 else HOOK + 16,
)
w64(DATA + 0x10000 + 0x3D38, DATA + 0x30000)
w64(DATA + 0x30000 + 0x50, DATA + 0x31000)
w64(DATA + 0x31000, DATA + 0x32000)
w64(DATA + 0x32000 + 0x28, HOOK)
uc.reg_write(x86.UC_X86_REG_RDI, DATA)
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFF8)
uc.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
w64(STACK + 0xFFF8, STOP)
uc.emu_start(addresses["_nv030846rm"], STOP, count=5000)
require(uc.reg_read(x86.UC_X86_REG_RIP) == STOP, "_nv030846rm did not reach STOP")
status = uc.reg_read(x86.UC_X86_REG_RAX) & 0xFFFFFFFF
rows.append(
{
"display": display,
"route": route,
"logo_brightness": logo_brightness,
"sli_brightness": sli_brightness,
"mode": mode,
"group": group,
"device_view": device_view,
"write_status": write_status,
"period": period,
"status": status,
"out_mode": struct.unpack("<I", uc.mem_read(DATA + 0x6AAC, 4))[0],
"out_sli_function": struct.unpack("<I", uc.mem_read(DATA + 0x6AB0, 4))[0],
"out_sli_brightness": struct.unpack("<I", uc.mem_read(DATA + 0x6ABC, 4))[0],
"trace": list(trace),
}
)
out = [
"// Generated by executing original ELF instructions; no hardware access.",
"const SLI_ORIGINAL_CASES: &[SliCase] = &[",
]
for c in rows:
trace_code = ", ".join(f"Trace::{op.title()}(0x{v:x})" for op, v in c["trace"])
fields = ", ".join(
f"{k}: 0x{c[k]:x}"
for k in (
"display",
"route",
"logo_brightness",
"sli_brightness",
"mode",
"group",
"device_view",
"write_status",
"period",
"status",
"out_mode",
"out_sli_function",
"out_sli_brightness",
)
)
out.append(f"SliCase {{ {fields}, trace: &[{trace_code}] }},")
out.append("];")
write_or_check_text(
ROOT / "src/nvidia/src/gpu/pf_sli_vectors.rs",
"\n".join(out) + "\n",
options.check,
"PF SLI Rust vectors",
)
report = {
"artifact_sha256": DIGEST,
"original_functions_executed": NAMES,
"preinit_initializers": initializers,
"cases": len(rows),
"source": (
"original .text instructions with original relocations; group/own-mask queries, "
"GPIO route and hardware read/write services intercepted in isolated RAM"
),
"limitations": [
"No physical GPU, native-driver execution or closed GPIO route helper execution in these wrapper vectors.",
"GPIO routing is independently source/REA recovered and tested separately.",
"Write is a required service interception, not claimed implemented hardware write.",
],
"rows": rows,
}
write_or_check_json(
ROOT / "reports/gpu-pf-sli-oracle.json",
report,
options.check,
"PF SLI JSON report",
)
print(len(rows), "original instruction oracle cases")
return 0
if __name__ == "__main__":
raise SystemExit(main())