#!/usr/bin/env python3 """Run the original RM side of the UVM interface (rm_gpu_ops_*) and write an oracle for the Rust `uvm::gpu_ops` module. Executed original code (580.178.04 nv-kernel.o_binary, whole object relocated; loader and fixtures of tools/check_rmapi_binary.py, which this script imports and does not modify): thunks every exported rm_gpu_ops_* symbol: the first call target of the thunk is read from the relocated instructions (73 thunks). classes _nv028356rm (findDeviceClasses) once per class id of the original's class table and of the public class predicates, to obtain the host / copy / compute / fault buffer / access counter / SEC2 classification. session rm_gpu_ops_create_session -> _nv046789rm (nvGpuOpsCreateSession) -> _nv046788rm (nvGpuOpsCreateClient), and rm_gpu_ops_destroy_session -> _nv046793rm, (a) against a recording RM API and (b) with nothing replaced below them, down to the original resource server ("deep" lines). gpu-info rm_gpu_ops_get_gpu_info's inner function _nv046818rm (nvGpuOpsGetGpuInfo) with every helper it calls (_nv028356rm, _nv017016rm, _nv029342rm, _nv029343rm, _nv018690rm, _nv021659rm, _nv017901rm, _nv054095rm, _nv041838rm, _nv041025rm). Fixture-supplied for the recording runs (everything else is original instructions): * rmapiGetInterface (_nv054239rm) returns a table whose slots record the request and answer from the case: Alloc (+0x00), Free (+0x18), Control (+0x38), DupObject (+0x50), Share (+0x60). The slot offsets are the ones the original instructions call through. * gpumgrGetGpuFromUuid (_nv031406rm) returns the case's GPU object or NULL, and nv_is_gpu_accessible answers from the case. * the GPU object is fixture memory holding only the fields _nv046818rm reads: the KernelMIGManager (+0x1fc8), KernelGraphicsManager (+0x1fd0), KernelGraphics[0] (+0x2018), KernelMemorySystem (+0x1ec8), MemoryManager (+0x1ed0), KernelNvlink (+0x2320) pointers and the property bytes +0x922 and +0x92d. MIG (IS_MIG_IN_USE) cases are not generated: the Rust module refuses that branch. """ import json import random import struct import sys def _require(condition, message=None): if not condition: raise AssertionError(message if message is not None else 'check failed') from unicorn.x86_const import UC_X86_REG_RAX, UC_X86_REG_RIP, UC_X86_REG_RSP import check_rmapi_binary as R from rmapi_binary_emulator import BASES, DIGEST, ROOT, STOP E = R.E OUT = ROOT / "target/uvm" SLOT = STOP + 0x200 SLOTS = {0: "alloc", 3: "free", 7: "control", 10: "dup", 12: "share"} INFO_SIZE = 0xf0 NVLINK_SIZE = 0x3420 def sparse(data): """`len:off=hex,off=hex` with the zero bytes left out.""" runs, start = [], None for offset, byte in enumerate(data): if byte and start is None: start = offset if not byte and start is not None: runs.append((start, offset)) start = None if start is not None: runs.append((start, len(data))) merged = [] for begin, end in runs: if merged and begin - merged[-1][1] < 4: merged[-1] = (merged[-1][0], end) else: merged.append((begin, end)) return f"{len(data):x}:" + ",".join(f"{begin:x}={data[begin:end].hex()}" for begin, end in merged) def thunk_table(): """First call target of each rm_gpu_ops_* thunk, from the relocated instructions.""" lines = [] by_address = {address: name for address, _size, name in E.functions} for address, size, name in E.functions: if not name.startswith("rm_gpu_ops_"): continue code = E.read(address, size) targets = [] position = 0 while position < len(code) - 4: if code[position] == 0xe8: target = address + position + 5 + struct.unpack_from(" {status:x} {handle_out:x}" f" {sparse(out) if out is not None else '-'}") return status def control(self, a): client, obj, command = a[1] & 0xffffffff, a[2] & 0xffffffff, a[3] & 0xffffffff size = a[5] & 0xffffffff params = E.read(a[4], size) status = self.injected() reply = self.replies.get(command) if callable(reply): reply = reply(params) if command == 0x800201: # NV0080_CTRL_CMD_GPU_GET_CLASSLIST: {numClasses, pad, classList pointer}. count_in, pointer = struct.unpack(" {status:x} {E.d(a[4]):x} {listed}") return status if status is None: status = 0 if isinstance(reply, tuple): status, reply = reply if reply is not None: _require(len(reply) == size, (hex(command), len(reply), size)) E.write(a[4], reply) self.lines.append(f"call control {client:x} {obj:x} {command:x} {sparse(params)}" f" -> {status:x} {sparse(E.read(a[4], size))}") return status def free(self, a): self.injected() self.lines.append(f"call free {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x} -> 0") return 0 def share(self, a): status = self.injected() if status is None: status = self.replies.get("share", 0) self.lines.append(f"call share {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x}" f" {E.read(a[3], 12).hex()} -> {status:x}") return status def other(self, index): def run(a): raise AssertionError(f"RM API slot {index:#x} is not part of these paths") return run API = None def install_recording(): """Replace the RM API table, the GPU lookup and the access check. The replacements are installed before any original instruction runs (hooks added to already translated code do not fire) and are switched by `world["recording"]`.""" global API API = Api.__new__(Api) API.lines, API.replies, API.next_handle, API.fail, API.count = [], {}, 0, None, 0 API.table = 0 for index in range(0x40): handler = {0: API.alloc, 3: API.free, 7: API.control, 12: API.share}.get( index, API.other(index)) E.install(SLOT + 8 * index, handler) world = {"gpu": 0, "accessible": 1, "recording": False} E.install("_nv054239rm", lambda a: API.table if world["recording"] else None) E.handlers.pop("_nv054239rm") E.install("_nv031406rm", lambda a: world["gpu"] if world["recording"] else None) E.handlers.pop("_nv031406rm") _require("nv_is_gpu_accessible" not in R.HOOKS) E.install("nv_is_gpu_accessible", lambda a: world["accessible"]) return world def quick_setup(): """What the recording cases need of the RM: the port layer (allocator, TLS). The RM API itself is replaced, so the resource server is not initialized.""" E.reset() R.state.update(admin=0, diag=[], purge=0, gpu_flags={}) _require(E.call("_nv059519rm") & 0xffffffff == 0) def fresh_table(): """E.reset() empties the fixture heap, so the API table is rebuilt per case.""" API.table = E.allocate(0x200) for index in range(0x40): E.wq(API.table + 8 * index, SLOT + 8 * index) # --------------------------------------------------------------------------------------- # Sessions. def runtime_stack(): """nvidia_stack_t as the thunks use it: the RM stack top at +8.""" stack = E.allocate(0x100) area = E.allocate(0x20000) E.wq(stack + 8, area + 0x18000) return stack def session_cases(): lines = [] # (a) recording RM API: every failure position of nvGpuOpsCreateClient. for name, fail in (("ok", None), ("alloc-fails", (0, 0x51)), ("alloc-fails-1a", (0, 0x1a)), ("share-fails", (1, 0x65)), ("share-fails-1b", (1, 0x1b))): quick_setup() fresh_table() API.begin({}, 0xc1d00041, fail) stack, out = runtime_stack(), E.allocate(16, 0xa5) status = E.call("rm_gpu_ops_create_session", stack, out) & 0xffffffff lines.append(f"case session-{name}") lines += API.lines session = E.q(out) if status == 0: blob = E.read(session, 0x28) handle, devices, lock1, p2p, lock2 = struct.unpack(" {status:x} {handle:x}") for index in (1, 0): R.state["freed"].clear() handle = E.d(sessions[index]) status = E.call("rm_gpu_ops_destroy_session", stack, sessions[index]) & 0xffffffff lines.append(f"deep destroy {handle:x} -> {status:x} freed " + ",".join(f"{freed:x}" for freed in R.state["freed"])) out = E.allocate(16) status = E.call("rm_gpu_ops_create_session", stack, out) & 0xffffffff lines.append(f"deep create -> {status:x} {E.d(E.q(out)):x}") _require(not R.state["diag"], R.state["diag"]) return lines # --------------------------------------------------------------------------------------- # Class predicates. PUBLIC_CLASSES = ( 0x506f, 0x906f, 0xa06f, 0xa16f, 0xb06f, 0xc06f, 0xc36f, 0xc46f, 0xc56f, 0xc86f, 0xc96f, 0xca6f, 0xb0b5, 0xc0b5, 0xc1b5, 0xc3b5, 0xc5b5, 0xc6b5, 0xc7b5, 0xc8b5, 0xc9b5, 0xcab5, 0xb0c0, 0xb1c0, 0xc0c0, 0xc1c0, 0xc3c0, 0xc4c0, 0xc5c0, 0xc6c0, 0xc7c0, 0xcbc0, 0xcdc0, 0xb069, 0xc369, 0xc365, 0x95a1, 0xcba2, 0xc572, 0xc361, 0xa06c, 0x9067, 0x90f1, 0x2080) def class_table(world): # The original's class table: 279 records of 56 bytes at .data+0xb620, external id first. records = E.read(BASES[".data"] + 0xb620, 279 * 56) table = [struct.unpack_from(" (connected, loop, remote type, version, line rate, caps).""" reply = bytearray(junk.randbytes(NVLINK_SIZE) if junk else NVLINK_SIZE) struct.pack_into("