Files
nvdriver/tools/gpu_hal_stub_bodies.py

253 lines
9.5 KiB
Python

#!/usr/bin/env python3
"""Classify the trivial functions bound in the GV100 HAL tables.
Many HAL slots are bound to a few bytes that only return a constant. This tool
runs every bound function of at most 40 bytes that has no relocation, with
distinct readable and writable scratch objects as arguments, and records the
returned value and whether it read or wrote memory. A function that touches no
memory returns the same value for any arguments.
Static original-instruction evidence for these leaf functions only.
"""
import argparse
import bisect
import hashlib
import json
import os
from pathlib import Path
import struct
ROOT = Path(__file__).resolve().parents[1]
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
TEXT, SCRATCH, STACK, STOP = 0x10000000, 0x30000000, 0x40000000, 0x50000000
LIMIT = 40
def _discover_rm_object(explicit=None) -> Path:
if explicit is not None:
return Path(explicit).expanduser().resolve()
candidates = []
for var in ("NV_RS_RM_OBJECT", "NV_KERNEL_O_BINARY"):
val = os.environ.get(var)
if val:
candidates.append(Path(val).expanduser())
env_kernel = os.environ.get("NV_RS_KERNEL_SRC")
if env_kernel:
candidates.append(Path(env_kernel).expanduser() / "nvidia/nv-kernel.o_binary")
env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT")
if env_analysis:
candidates.append(
Path(env_analysis).expanduser() / "extracted/kernel/nvidia/nv-kernel.o_binary"
)
candidates.extend(
[
Path.home()
/ "nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary",
Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary"),
Path("/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary"),
]
)
for cand in candidates:
if cand.is_file():
return cand.resolve()
return candidates[0].resolve()
def load_text_and_relocations(rm_object: Path):
"""Parse `.text`, `.symtab`, and `.rela.text` offsets using stdlib ELF64."""
if not rm_object.is_file():
raise SystemExit(
f"Missing 580.178.04 nv-kernel.o_binary: {rm_object} "
"(set NV_RS_RM_OBJECT, NV_RS_KERNEL_SRC, NV_RS_ANALYSIS_ROOT, or --rm-object)"
)
raw = rm_object.read_bytes()
got = hashlib.sha256(raw).hexdigest()
if got != DIGEST:
raise SystemExit(f"SHA-256 mismatch for {rm_object}: expected {DIGEST}, got {got}")
if len(raw) < 64 or raw[:4] != b"\x7fELF" or raw[4] != 2 or raw[5] != 1:
raise SystemExit("RM object is not a little-endian ELF64 file")
e_shoff = struct.unpack_from("<Q", raw, 40)[0]
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", raw, 58)
sh0 = struct.unpack_from("<IIQQQQIIQQ", raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5]
if e_shstrndx == 0xFFFF:
e_shstrndx = sh0[6]
headers = [
struct.unpack_from("<IIQQQQIIQQ", raw, e_shoff + i * e_shentsize)
for i in range(e_shnum)
]
_, _, _, _, shstr_off, shstr_size, _, _, _, _ = headers[e_shstrndx]
shstr = raw[shstr_off : shstr_off + shstr_size]
sec_data = {}
for hdr in headers:
sh_name, sh_type, _flags, _addr, sh_offset, sh_size, *_rest = hdr
end = shstr.find(b"\0", sh_name)
name = shstr[sh_name : end if end != -1 else len(shstr)].decode("utf-8", errors="replace")
sec_data[name] = b"" if sh_type == 8 else raw[sh_offset : sh_offset + sh_size]
strtab = sec_data[".strtab"]
symbols = {}
for name_off, _info, _other, _shndx, value, size in struct.iter_unpack(
"<IBBHQQ", sec_data[".symtab"]
):
end = strtab.find(b"\0", name_off)
name = strtab[name_off : end if end != -1 else len(strtab)].decode("utf-8", errors="replace")
if name:
symbols[name] = (value, size)
relocated = sorted(off for off, _info, _addend in struct.iter_unpack("<QQq", sec_data[".rela.text"]))
return symbols, sec_data[".text"], relocated
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description="Classify or verify trivial GV100 HAL stub functions."
)
parser.add_argument("--rm-object", type=Path, default=None)
parser.add_argument("--check", action="store_true")
args = parser.parse_args(argv)
rm_object = _discover_rm_object(args.rm_object)
symbols, text, relocated = load_text_and_relocations(rm_object)
try:
from unicorn import (
UC_ARCH_X86,
UC_HOOK_MEM_READ,
UC_HOOK_MEM_WRITE,
UC_MODE_64,
Uc,
UcError,
)
from unicorn.x86_const import (
UC_X86_REG_R8,
UC_X86_REG_R9,
UC_X86_REG_RAX,
UC_X86_REG_RCX,
UC_X86_REG_RDI,
UC_X86_REG_RDX,
UC_X86_REG_RIP,
UC_X86_REG_RSI,
UC_X86_REG_RSP,
)
except ImportError as exc:
raise SystemExit("Unicorn (`unicorn`) is required to run gpu_hal_stub_bodies") from exc
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for address, size in (
(TEXT, (len(text) + 4095) & ~4095),
(SCRATCH, 0x600000),
(STACK, 0x10000),
(STOP, 0x1000),
):
cpu.mem_map(address, size)
cpu.mem_write(TEXT, text)
touched = {"read": 0, "write": 0}
cpu.hook_add(
UC_HOOK_MEM_READ,
lambda *a: touched.__setitem__("read", touched["read"] + 1),
begin=SCRATCH,
end=SCRATCH + 0x600000 - 1,
)
cpu.hook_add(
UC_HOOK_MEM_WRITE,
lambda *a: touched.__setitem__("write", touched["write"] + 1),
begin=SCRATCH,
end=SCRATCH + 0x600000 - 1,
)
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,
)
def classify(name):
entry = symbols.get(name)
if entry is None or entry[1] > LIMIT:
return None
start, size = entry
if bisect.bisect_left(relocated, start) != bisect.bisect_left(relocated, start + size):
return None
results = []
for fill in (0x00, 0xFF):
cpu.mem_write(SCRATCH, bytes([fill]) * 0x600000)
touched.update(read=0, write=0)
for index, register in enumerate(arguments):
cpu.reg_write(register, SCRATCH + 0x100000 * index + 0x8000)
cpu.reg_write(UC_X86_REG_RAX, 0x5A5A5A5A5A5A5A5A)
cpu.reg_write(UC_X86_REG_RSP, STACK + 0xFF00)
cpu.mem_write(STACK + 0xFF00, struct.pack("<Q", STOP))
try:
cpu.emu_start(TEXT + start, STOP, count=200)
except UcError:
return None
if cpu.reg_read(UC_X86_REG_RIP) != STOP:
return None
results.append((cpu.reg_read(UC_X86_REG_RAX), touched["read"], touched["write"]))
(first, reads, writes), (second, _, _) = results
if reads or writes or first != second:
return {"bytes": size, "kind": "touches-memory", "reads": reads, "writes": writes}
if first == 0x5A5A5A5A5A5A5A5A:
return {"bytes": size, "kind": "returns-nothing"}
return {"bytes": size, "kind": "constant", "eax": f"{first & 0xffffffff:#x}"}
bindings = json.loads((ROOT / "reports/gv100-engine-hal-bindings.json").read_text())
tables = {"OBJGPU": bindings["gpu_object"]["hal_slots"]}
tables.update(
{
entry["class_label"] or f"ordinal{entry['engine_ordinals0'][0]}": entry["hal_slots"]
for entry in bindings["classes"]
}
)
tables.update(
{entry["class_label"]: entry["hal_slots"] for entry in bindings.get("other_objects", ())}
)
functions, per_class = {}, {}
for label, slots in tables.items():
trivial = 0
for slot in slots.values():
name = slot["function"]
if name not in functions:
functions[name] = classify(name)
trivial += functions[name] is not None and functions[name]["kind"] != "touches-memory"
per_class[label] = {"slots": len(slots), "constant_or_empty_slots": trivial}
classified = {name: result for name, result in sorted(functions.items()) if result}
report = {
"original_sha256": DIGEST,
"size_limit_bytes": LIMIT,
"scope": "Leaf functions bound in the GV100 HAL tables that are at most the size limit "
"and contain no relocation, executed with scratch arguments. `constant` and "
"`returns-nothing` functions touched no memory in either run.",
"functions": classified,
"classes": per_class,
"totals": {
"bound_functions": len(functions),
"classified": len(classified),
"constant_or_empty": sum(
1 for r in classified.values() if r["kind"] != "touches-memory"
),
},
}
report_path = ROOT / "reports/gv100-hal-stub-bodies.json"
if args.check:
if not report_path.is_file() or json.loads(report_path.read_text()) != report:
raise SystemExit(f"HAL stub bodies report differs: {report_path}")
else:
report_path.write_text(json.dumps(report, indent=1) + "\n")
print(report["totals"])
total_slots = sum(entry["slots"] for entry in per_class.values())
print(
"slots",
total_slots,
"bound to constant or empty bodies",
sum(entry["constant_or_empty_slots"] for entry in per_class.values()),
)
return 0
if __name__ == "__main__":
raise SystemExit(main())