mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
390 lines
14 KiB
Python
Executable File
390 lines
14 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Emulate original exact 580 channel predicates with register/lookup/log calls intercepted.
|
|
No GPU or native target execution. Relocations are linked into an isolated Unicorn memory image.
|
|
"""
|
|
|
|
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_hal_channel_elf import (
|
|
ROOT,
|
|
SHN_UNDEF,
|
|
STT_FUNC,
|
|
discover_rm_object,
|
|
parse_elf64_rm_object,
|
|
require,
|
|
require_unicorn,
|
|
write_or_check_json,
|
|
write_or_check_text,
|
|
)
|
|
|
|
TEXT = 0x10000000
|
|
DATA = 0x30000000
|
|
STACK = 0x40000000
|
|
STUB = 0x50000000
|
|
STOP = 0x60000000
|
|
NAMES = [
|
|
"_nv027717rm",
|
|
"_nv028059rm",
|
|
"_nv028037rm",
|
|
"_nv018613rm",
|
|
"_nv040880rm",
|
|
"_nv040884rm",
|
|
]
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
p = argparse.ArgumentParser(
|
|
description="Emulate 580.178.04 channel predicates and check/regenerate channel vectors."
|
|
)
|
|
p.add_argument(
|
|
"--check",
|
|
action="store_true",
|
|
help="Verify generated Rust vectors and JSON report without writing.",
|
|
)
|
|
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:
|
|
opt = build_parser().parse_args(argv)
|
|
unicorn, x86 = require_unicorn()
|
|
|
|
rm_object = discover_rm_object(opt.rm_object)
|
|
parsed = parse_elf64_rm_object(rm_object)
|
|
symbols = parsed["symbols"]
|
|
defined = parsed["defined"]
|
|
text = bytearray(parsed["section_bytes"](".text"))
|
|
section_index = parsed["section_index"](".text")
|
|
|
|
at = {
|
|
TEXT + s["st_value"]: s["name"]
|
|
for s in symbols
|
|
if s["st_type"] == STT_FUNC and s["st_shndx"] == section_index and s["name"]
|
|
}
|
|
functions: dict[str, tuple[int, int]] = {}
|
|
for name in NAMES:
|
|
sym = defined[name]
|
|
functions[name] = (sym["st_value"], sym["st_size"])
|
|
|
|
def selected(off: int) -> bool:
|
|
return any(start <= off < start + size for start, size in functions.values())
|
|
|
|
hooks: dict[int, str] = {}
|
|
undef: dict[str, int] = {}
|
|
for off, sym_idx, kind, addend in parsed["iter_relocations"](".rela.text"):
|
|
if not selected(off):
|
|
continue
|
|
sym = symbols[sym_idx]
|
|
if sym["st_shndx"] == section_index:
|
|
target = TEXT + sym["st_value"]
|
|
elif sym["st_shndx"] == SHN_UNDEF:
|
|
target = undef.setdefault(sym["name"], STUB + 0x100 + len(undef) * 16)
|
|
hooks[target] = sym["name"]
|
|
else:
|
|
target = STUB + 0x8000 # Non-dereferenced diagnostic data relocation.
|
|
require(kind in (2, 4, 11), f"unexpected relocation {(off, kind, sym['name'])}")
|
|
displacement = target + addend - (TEXT + off) if kind in (2, 4) else target + addend
|
|
struct.pack_into("<i", text, off, displacement)
|
|
|
|
for address, name in at.items():
|
|
if name in (
|
|
"_nv053907rm",
|
|
"_nv053912rm",
|
|
"_nv030608rm",
|
|
"_nv047869rm",
|
|
"_nv046745rm",
|
|
"_nv046764rm",
|
|
"_nv059492rm",
|
|
"_nv059509rm",
|
|
"_nv059505rm",
|
|
):
|
|
hooks[address] = name
|
|
|
|
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, 0x60000)
|
|
uc.mem_map(STACK, 0x10000)
|
|
uc.mem_map(STUB, 0x10000)
|
|
uc.mem_map(STOP, 4096)
|
|
|
|
virtual = STUB + 0x10
|
|
hooks[virtual] = "resolve_engine"
|
|
hooks[STUB + 0x20] = "recover_gpu"
|
|
|
|
state = {
|
|
"input_raw": 0,
|
|
"reads": [],
|
|
"read_values": None,
|
|
"timeout_status": 0,
|
|
"remove_on_timeout": False,
|
|
"helper_calls": [],
|
|
"writes": [],
|
|
}
|
|
|
|
def ret(value: int) -> None:
|
|
sp = uc.reg_read(x86.UC_X86_REG_RSP)
|
|
target = struct.unpack("<Q", uc.mem_read(sp, 8))[0]
|
|
uc.reg_write(x86.UC_X86_REG_RAX, value)
|
|
uc.reg_write(x86.UC_X86_REG_RSP, sp + 8)
|
|
uc.reg_write(x86.UC_X86_REG_RIP, target)
|
|
|
|
def on_code(emu, address, _size, _user):
|
|
if address == STOP:
|
|
emu.emu_stop()
|
|
return
|
|
name = hooks.get(address)
|
|
if not name:
|
|
return
|
|
if name.startswith("__x86_indirect_thunk_"):
|
|
require(name == "__x86_indirect_thunk_rax", f"unexpected thunk {name}")
|
|
emu.reg_write(x86.UC_X86_REG_RIP, emu.reg_read(x86.UC_X86_REG_RAX))
|
|
return
|
|
if name == "_nv053907rm":
|
|
state["reads"].append(emu.reg_read(x86.UC_X86_REG_RCX))
|
|
rv = state["read_values"]
|
|
ret(state["input_raw"] if rv is None else rv[min(len(state["reads"]) - 1, len(rv) - 1)])
|
|
elif name == "_nv053912rm":
|
|
state["writes"].append((emu.reg_read(x86.UC_X86_REG_RCX), emu.reg_read(x86.UC_X86_REG_R8)))
|
|
ret(0)
|
|
elif name in ("_nv059492rm", "_nv059509rm", "_nv059505rm", "recover_gpu"):
|
|
state["helper_calls"].append(name)
|
|
if name == "_nv059505rm" and state["remove_on_timeout"]:
|
|
emu.mem_write(DATA + 0x915, b"\x00")
|
|
ret(state["timeout_status"] if name == "_nv059505rm" else 0)
|
|
elif name == "_nv030608rm":
|
|
ret(DATA + 0x10000)
|
|
elif name == "resolve_engine":
|
|
emu.mem_write(emu.reg_read(x86.UC_X86_REG_R9), struct.pack("<I", 0))
|
|
ret(0)
|
|
elif name in ("_nv047869rm", "_nv046745rm", "_nv046764rm"):
|
|
ret(0)
|
|
else:
|
|
raise RuntimeError("Unexpected original call " + name)
|
|
|
|
uc.hook_add(unicorn.UC_HOOK_CODE, on_code)
|
|
|
|
def put(offset: int, value: int) -> None:
|
|
uc.mem_write(DATA + offset, struct.pack("<Q", value))
|
|
|
|
put(0x20000 + 0x470, DATA + 0x30000)
|
|
put(0x30000 + 0x274, 7)
|
|
put(0x20000 + 0x398, DATA + 0x40000)
|
|
put(0x40000 + 0x128, 42)
|
|
put(0x20000 + 0x128, 42)
|
|
put(0x10000 + 0x1B8, virtual)
|
|
|
|
all_regs = [
|
|
x86.UC_X86_REG_RAX,
|
|
x86.UC_X86_REG_RBX,
|
|
x86.UC_X86_REG_RCX,
|
|
x86.UC_X86_REG_RDX,
|
|
x86.UC_X86_REG_RSI,
|
|
x86.UC_X86_REG_RDI,
|
|
x86.UC_X86_REG_R8,
|
|
x86.UC_X86_REG_R9,
|
|
x86.UC_X86_REG_R10,
|
|
x86.UC_X86_REG_R11,
|
|
x86.UC_X86_REG_R12,
|
|
x86.UC_X86_REG_R13,
|
|
x86.UC_X86_REG_R14,
|
|
x86.UC_X86_REG_R15,
|
|
]
|
|
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,
|
|
]
|
|
expected_read = {
|
|
"_nv027717rm": 0x800004 + 7 * 8,
|
|
"_nv028059rm": 0x3080 + 3 * 4,
|
|
"_nv028037rm": 0x2640,
|
|
}
|
|
|
|
def run(name: str, raw_val: int, args: list[int]) -> int:
|
|
state["input_raw"] = raw_val
|
|
state["reads"] = []
|
|
for reg in all_regs:
|
|
uc.reg_write(reg, 0)
|
|
uc.reg_write(x86.UC_X86_REG_RSP, STACK + 0xFFF8)
|
|
uc.mem_write(STACK + 0xFFF8, struct.pack("<Q", STOP))
|
|
uc.reg_write(x86.UC_X86_REG_RBP, STACK + 0x8000)
|
|
for reg, value in zip(arg_regs, args):
|
|
uc.reg_write(reg, value)
|
|
try:
|
|
uc.emu_start(TEXT + functions[name][0], STOP, count=1000)
|
|
except Exception as error:
|
|
raise RuntimeError(
|
|
(
|
|
name,
|
|
hex(uc.reg_read(x86.UC_X86_REG_RIP)),
|
|
hex(uc.reg_read(x86.UC_X86_REG_RSP)),
|
|
state["reads"],
|
|
state["writes"],
|
|
state["helper_calls"],
|
|
)
|
|
) from error
|
|
require(uc.reg_read(x86.UC_X86_REG_RIP) == STOP, f"{name} did not reach STOP")
|
|
if name in expected_read:
|
|
require(
|
|
state["reads"] == [expected_read[name]],
|
|
f"{name} reads mismatch: {state['reads']}",
|
|
)
|
|
return uc.reg_read(x86.UC_X86_REG_RAX) & 255
|
|
|
|
rows = []
|
|
for st in range(16):
|
|
for bits in range(8):
|
|
raw_val = (st << 24) | (bits & 1) | (((bits >> 1) & 1) << 1) | (((bits >> 2) & 1) << 28)
|
|
for mask in (0, 1, 2, 4, 8, 16, 32, 64, 127):
|
|
for all_bits in (0, 1):
|
|
rows.append((0, raw_val, mask, all_bits, run(NAMES[0], raw_val, [DATA, 0, DATA + 0x20000, mask, all_bits])))
|
|
|
|
for st in range(8):
|
|
for is_tsg in range(2):
|
|
for next_valid in range(2):
|
|
for current_match in range(2):
|
|
for next_match in range(2):
|
|
raw_val = (
|
|
(st << 13)
|
|
| (is_tsg << 12)
|
|
| (next_valid << 28)
|
|
| (42 if current_match else 43)
|
|
| ((42 if next_match else 43) << 16)
|
|
)
|
|
rows.append((1, raw_val, 0, 0, run(NAMES[1], raw_val, [DATA, 0, 3, DATA + 0x20000])))
|
|
|
|
for st in range(8):
|
|
for is_tsg in range(2):
|
|
for current_match in range(2):
|
|
for next_match in range(2):
|
|
wanted = 42 if is_tsg else 7
|
|
raw_val = (
|
|
(st << 13)
|
|
| (is_tsg << 12)
|
|
| (wanted if current_match else wanted + 1)
|
|
| ((wanted if next_match else wanted + 1) << 16)
|
|
)
|
|
rows.append((2, raw_val, 0, 0, run(NAMES[2], raw_val, [DATA, 0, 0x123400, DATA + 0x20000])))
|
|
|
|
fault_pointer_vectors = []
|
|
put(0x1F88, DATA + 0x49000)
|
|
put(0x49000 + 0x8E0, 0x200)
|
|
for method, offset in (("_nv040880rm", 0x100E2C), ("_nv040884rm", 0x100E30)):
|
|
for queue in range(2):
|
|
for raw_val in (0, 1, 0xFFFFF, 0xC0000005, 0xFFFFFFFF):
|
|
status = run(method, raw_val, [DATA, 0, queue, DATA + 0x48000])
|
|
pointer = struct.unpack("<I", uc.mem_read(DATA + 0x48000, 4))[0]
|
|
require(
|
|
status == 0
|
|
and pointer == (raw_val & 0xFFFFF)
|
|
and state["reads"] == [offset + 0x200 + queue * 20],
|
|
f"fault pointer mismatch for {method} q={queue} raw={raw_val:#x}",
|
|
)
|
|
fault_pointer_vectors.append(
|
|
{
|
|
"method": method,
|
|
"queue": queue,
|
|
"raw": raw_val,
|
|
"pointer": pointer,
|
|
"register_offset": state["reads"][0],
|
|
}
|
|
)
|
|
|
|
fb_cases = []
|
|
for label, values, expired, attached, remove in (
|
|
("clear", [0], 0, True, False),
|
|
("pending_then_clear", [1, 2, 0], 0, True, False),
|
|
("expiry_then_clear", [1, 0], 0x65, True, False),
|
|
("expiry_still_busy", [1], 0x65, True, False),
|
|
("initial_detached", [1], 0, False, False),
|
|
("detached_during_wait", [1], 0, True, True),
|
|
):
|
|
uc.mem_write(DATA + 0x915, bytes([int(attached)]))
|
|
put(0x1A0, STUB + 0x20)
|
|
state["read_values"] = values
|
|
state["timeout_status"] = expired
|
|
state["remove_on_timeout"] = remove
|
|
state["helper_calls"] = []
|
|
state["writes"] = []
|
|
result = run("_nv018613rm", 0, [DATA])
|
|
require(state["writes"] == [(0x70000, 1)], f"unexpected FB flush writes: {state['writes']}")
|
|
require(
|
|
state["helper_calls"][:2] == ["_nv059492rm", "_nv059509rm"],
|
|
f"unexpected FB flush helpers: {state['helper_calls']}",
|
|
)
|
|
fb_cases.append(
|
|
{
|
|
"case": label,
|
|
"status": result,
|
|
"register_reads": list(state["reads"]),
|
|
"register_writes": [list(w) for w in state["writes"]],
|
|
"helper_calls": list(state["helper_calls"]),
|
|
}
|
|
)
|
|
require([c["status"] for c in fb_cases] == [0, 0, 0, 0x65, 0, 0], "unexpected FB flush statuses")
|
|
require(
|
|
[len(c["register_reads"]) for c in fb_cases] == [1, 3, 2, 4, 0, 2],
|
|
"unexpected FB flush read counts",
|
|
)
|
|
state["read_values"] = None
|
|
|
|
lines = [
|
|
"// Original machine instructions executed only in isolated Unicorn emulator.",
|
|
"pub type Vector = (u8, u32, u32, u8, bool);",
|
|
"#[rustfmt::skip]",
|
|
"pub const VECTORS:&[Vector]=&[",
|
|
*[
|
|
f"({k},{raw_val},{mask},{all_bits},{str(bool(out)).lower()}),"
|
|
for k, raw_val, mask, all_bits, out in rows
|
|
],
|
|
"];",
|
|
]
|
|
write_or_check_text(
|
|
ROOT / "src/nvidia/src/mmu/channel_oracle_vectors.rs",
|
|
"\n".join(lines) + "\n",
|
|
opt.check,
|
|
"channel oracle Rust vectors",
|
|
)
|
|
report = {
|
|
"passed": True,
|
|
"vectors": len(rows),
|
|
"artifact_sha256": parsed["digest"],
|
|
"functions": {
|
|
n: {"text_offset": hex(a), "bytes": size} for n, (a, size) in functions.items()
|
|
},
|
|
"FB_flush_cases": fb_cases,
|
|
"fault_pointer_vectors": fault_pointer_vectors,
|
|
"execution": (
|
|
"Isolated Unicorn x86_64 instruction emulation only; original register read, "
|
|
"KernelFifo lookup, engine resolution, and diagnostics intercepted with mocks; "
|
|
"no native target code or GPU executed"
|
|
),
|
|
}
|
|
write_or_check_json(
|
|
ROOT / "reports/channel-binary-oracle.json",
|
|
report,
|
|
opt.check,
|
|
"channel binary oracle report",
|
|
)
|
|
print(len(rows), "original instruction-emulated channel vectors")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|