#!/usr/bin/env python3 """Run the original's channel-object paths and write an oracle for the Rust `rmapi` channel slice (userspace interface slice 6). This extends the memory fixture of tools/check_rmapi_memory_binary.py (same emulator, same GPU object built by the original's own probe and attach, same heap and allocator) and uses the UVM slice-2 fixture of tools/check_uvm_gpu_ops2_binary.py for the page directory. Both are imported and not modified. RECORD GRAMMAR (target/rmapi/original-rmapi-channel.txt). One line per item, fields separated by single spaces, all numbers hexadecimal without prefix unless stated. # ... comment case a new world (fresh emulator state); everything up to the next `case` belongs to it fixture a fixture decision of this case (free text) gpu/registers/attach-*/sweep*/initialized/stage*/regions/reserved/R ... world construction lines of the earlier harnesses (formats in tools/check_rmapi_binary.py and check_rmapi_memory_binary.py) op/call/ret/registers/asserts lines of the UVM slice-2 harness (rm_gpu_ops entry points; formats in tools/check_uvm_gpu_ops2_binary.py) note free text for the reader, not data A|F|C -> one escape through `_nv000800rm` (NV_ESC_RM_ALLOC 0x2b, NV_ESC_RM_FREE 0x29, NV_ESC_RM_CONTROL 0x2a) as in the earlier records. For `F` two lines `purged ` and `freed ` follow first (resources destroyed, in destruction order). Every line after a request line and before the next request/case/note line is an EVENT of that request, in the order the original produced it: r BAR0 register read and the value the fixture answered w BAR0 register write (recorded, not applied unless the case names a register model in a `fixture` line) os ... operating-system boundary call (formats of the memory record) bar2 map the original mapped a framebuffer descriptor through KernelBus+0x120 (`_nv039492rm`, kbusMapRmAperture): physical address of its first byte, descriptor size, caller flags bar2 unmap KernelBus+0x130 (`_nv039620rm`) bar2 remap KernelBus+0x128 (`_nv039648rm`) bar2 pte KernelBus+0x138 (`_nv039638rm`, the BAR2 page-table update): descriptor address space (1 system, 2 framebuffer), physical address of the descriptor, BAR2 virtual address, size, flags m a store instruction of the original into mapped memory: space `fb` (framebuffer physical addresses) or `sys` (system memory, fabricated page addresses); base is the physical address of the mapping the byte belongs to (the argument of the last `bar2 map` / `os kernel-map` covering it), offset is relative to base, size is 1, 2, 4 or 8, value the integer stored fill os_mem_set into mapped memory copy os_mem_copy / user copy into mapped memory E -> NV_ESC_ALLOC_OS_EVENT / NV_ESC_FREE_OS_EVENT through the original's rm_ioctl; followed by `events ` (see `event_cases`) workload-compare / workload-difference comparison of the replayed capture with the captured replies (see `workload_case`) engine-table ... the static engine table (format of the GPU record) process the calling process from here on (default 1092 = 4242) list nested user buffers of 0x80170d (hex bytes, little-endian u32 each): the handle list sent and the channel list written; in the C line the two user pointers appear as 0x2000, 0x3000 State lines the harness reads from the original's objects after a request (not events): tsg after a successful 0xa06c and wherever a case asks chan after a successful 0xc36f image final content of a mapped region after the request, in the `len:off=hex,...` form of the UVM record (zero bytes omitted) See the progress file analysis/closed-driver-580/rmapi-channel-slice-progress.md for the findings. Fixture decisions that bound every claim of the record are the `fixture` lines of each case and the list below. FIXTURE DECISIONS (beyond the two imported harnesses) 1. Stage bodies run in front of every case, each to status 0 through `GpuSequence.stage`: the seven memory bodies, then KernelFifo StateInitLocked `_nv040424rm` and OBJFIFO StateInitLocked `_nv028307rm` (channel-id manager, engine table, one scheduler owner per runlist with its two runlist buffers allocated on the original heap). 2. BAR2 is not set up (KernelBus StateInitLocked does not run). The three KernelBus functions that map a framebuffer descriptor for the CPU and the BAR2 page-table update are replaced by recorders (lines `bar2 ...`); a mapping returns a pointer into fixture memory that stands for the framebuffer, so every store of the original is seen with its physical address. Unwritten framebuffer bytes read 0. 3. System memory the original maps (nv_alloc_kernel_mapping) is fixture memory at a fixed window, so stores into notifiers and method buffers are seen (space `sys`). 4. os_flush_cpu_write_combine_buffer and os_flush_cpu_cache_all return 0. """ import hashlib import json import struct import sys from unicorn import UC_HOOK_CODE, UC_HOOK_MEM_WRITE from unicorn.x86_const import UC_X86_REG_RDI, UC_X86_REG_RSI import check_rmapi_memory_binary as M import check_uvm_gpu_ops2_binary as U R, E = M.R, M.E ROOT, OUT, DIGEST = M.ROOT, M.OUT, M.DIGEST state, gpu_state, os_state = M.state, M.gpu_state, M.os_state CLIENT, DEVICE, SUBDEVICE = M.CLIENT, M.DEVICE, M.SUBDEVICE PAGE = 0x1000 TARGET = OUT / "original-rmapi-channel.txt" R.STAGE_BODIES.update({ "kfifo-init": (0x22d0, 1, "_nv040424rm", ()), # KernelFifo StateInitLocked "ofifo-init": (0x22d8, 1, "_nv028307rm", ()), # OBJFIFO StateInitLocked }) FIFO_STAGES = ("kfifo-init", "ofifo-init") TIMER = {0x9400: 0x89abcde0, 0x9410: 0x01234567} # Fixture windows: emulator address = window + physical address. FB_WINDOW, FB_SPAN = 0x100000000000, 0x800000000 SYS_WINDOW, SYS_SPAN = 0x200000000000, 0x4000000000 windows = {"fb": dict(base=FB_WINDOW, pages=set(), maps=[]), "sys": dict(base=SYS_WINDOW, pages=set(), maps=[])} def events(): return os_state["events"] def window_map(space, physical, size): """Back [physical, physical + size) of a window with zeroed fixture memory.""" window = windows[space] first, last = physical & ~(PAGE - 1), (physical + size + PAGE - 1) & ~(PAGE - 1) for page in range(first, last, PAGE): if page not in window["pages"]: E.cpu.mem_map(window["base"] + page, PAGE) window["pages"].add(page) return window["base"] + physical def window_reset(): for window in windows.values(): for page in window["pages"]: E.cpu.mem_unmap(window["base"] + page, PAGE) window["pages"].clear() window["maps"].clear() def window_of(address): """(space, physical, base of the covering mapping) of an emulator address, or None.""" for space, window in windows.items(): physical = address - window["base"] if 0 <= physical < (FB_SPAN if space == "fb" else SYS_SPAN): for base, size in reversed(window["maps"]): if base <= physical < base + size: return space, physical, base return space, physical, physical & ~(PAGE - 1) return None def store(emu, access, address, size, value, unused): space, physical, base = window_of(address) events().append(f"m {space} {base:x} {physical - base:x} {size:x}" f" {value & ((1 << 8 * size) - 1):x}") E.cpu.hook_add(UC_HOOK_MEM_WRITE, store, begin=FB_WINDOW, end=FB_WINDOW + FB_SPAN - 1) E.cpu.hook_add(UC_HOOK_MEM_WRITE, store, begin=SYS_WINDOW, end=SYS_WINDOW + SYS_SPAN - 1) def replace(name, handler): """Replace a fixture of the imported harnesses (open-layer symbol) by another.""" if name in R.HOOKS: E.cpu.hook_del(R.HOOKS[name]) R.HOOKS[name] = E.install(name, handler) def fill(a): where = window_of(a[0]) if where: space, physical, base = where events().append(f"fill {space} {base:x} {physical - base:x} {a[2] & 0xffffffff:x}" f" {a[1] & 0xff:x}") return R.fill(a) def copy(a): where = window_of(a[0]) if where: space, physical, base = where events().append(f"copy {space} {base:x} {physical - base:x}" f" {E.read(a[1], a[2] & 0xffffffff).hex()}") return R.copy(a) def user_copy(a): copy(a) return 0 for _name, _handler in (("os_mem_set", fill), ("os_mem_copy", copy), ("os_memcpy_from_user", user_copy), ("os_memcpy_to_user", user_copy)): replace(_name, _handler) for _name in ("os_flush_cpu_write_combine_buffer", "os_flush_cpu_cache_all"): E.install(_name, lambda a: 0) class Pages(dict): """os_state["pages"] of the memory harness: an allocation of at most 1 MiB gets its kernel-mapping backing in the system-memory window at its fabricated address.""" def __setitem__(self, cookie, record): if record.get("backing") is None and record["bytes"] <= 0x100000: record["backing"] = window_map("sys", record["base"], record["bytes"]) windows["sys"]["maps"].append((record["base"], record["bytes"])) super().__setitem__(cookie, record) # Memory descriptor fields (MEMORY_DESCRIPTOR of this build): +0x8 flags (0x400 contiguous), # +0x30 size, +0x60 offset inside the parent, +0x70 address space, +0xd0 parent, +0x178 # first page address. def descriptor(memdesc): offset, root = 0, memdesc while E.q(root + 0xd0): offset += E.q(root + 0x60) root = E.q(root + 0xd0) own = E.q(memdesc + 0x178) physical = E.q(root + 0x178) + offset if root != memdesc: # A sub-descriptor carries the address of its first page; the byte offset inside # that page is the parent offset's low bits. assert own == physical & ~(PAGE - 1), (hex(own), hex(physical)) return E.d(memdesc + 0x70), physical, E.q(memdesc + 0x30) def bar2_map(a): """KernelBus+0x120 `_nv039492rm`(gpu, kbus, memdesc, flags): CPU pointer.""" space, physical, size = descriptor(a[2]) assert space == 2, space windows["fb"]["maps"].append((physical, size)) events().append(f"bar2 map {physical:x} {size:x} {a[3] & 0xffffffff:x}") return window_map("fb", physical, size) def bar2_remap(a): """KernelBus+0x128 `_nv039648rm`(gpu, kbus, memdesc, pointer): the pointer.""" space, physical, size = descriptor(a[2]) events().append(f"bar2 remap {physical:x}") return a[3] def bar2_unmap(a): """KernelBus+0x130 `_nv039620rm`(gpu, kbus, memdesc, &pointer, flags).""" space, physical, size = descriptor(a[2]) events().append(f"bar2 unmap {physical:x} {a[4] & 0xffffffff:x}") return 0 def bar2_update(a): """KernelBus+0x138 `_nv039638rm`(gpu, kbus, memdesc, va, size, flags).""" space, physical, size = descriptor(a[2]) events().append(f"bar2 pte {space:x} {physical:x} {a[3]:x} {a[4]:x} {a[5] & 0xffffffff:x}") return 0 BAR2_SLOTS = {0x120: ("_nv039492rm", bar2_map), 0x128: ("_nv039648rm", bar2_remap), 0x130: ("_nv039620rm", bar2_unmap), 0x138: ("_nv039638rm", bar2_update)} # Installed before any original instruction runs (a hook added to translated code does not # fire); the world checks that these are the functions in the KernelBus object. for _slot, (_name, _handler) in BAR2_SLOTS.items(): E.install(_name, _handler) E.handlers.pop(_name) # Object pointers of the constructors, by entry hook: `_nv039884rm` kchangrpapiConstruct, # `_nv039920rm` kchannelConstruct, `_nv040060rm` kctxshareapiConstruct. constructed = {"group": [], "channel": [], "share": []} for _kind, _name in (("group", "_nv039884rm"), ("channel", "_nv039920rm"), ("share", "_nv040060rm")): E.cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, kind: constructed[kind].append( emu.reg_read(UC_X86_REG_RDI)), _kind, begin=E.by_name[_name], end=E.by_name[_name]) graphics = {"stub": False, "case": None} def graphics_info(emu, address, size, unused): """Entry of `_nv041022rm`(gpu, KernelGraphics, index): returns KernelGraphics+0x1e0 + 0x60 * index, or NULL when that pointer is NULL. `_nv041157rm` (reached when a channel whose runlist is the graphics runlist is freed) reads byte +0x50 of the result without a NULL test. On this fixture the pointer is NULL because no KernelGraphics stage body ran. A case that says so (`fixture graphics-info-stub`) gets a zeroed block of 8 records there, so that the free path continues with "nothing to unmap".""" kgraphics = emu.reg_read(UC_X86_REG_RSI) if graphics["stub"] and E.q(kgraphics + 0x1e0) == 0: E.wq(kgraphics + 0x1e0, E.allocate(0x60 * 8)) E.cpu.hook_add(UC_HOOK_CODE, graphics_info, begin=E.by_name["_nv041022rm"], end=E.by_name["_nv041022rm"]) U.install() class Accesses(list): """gpu_state["read"] / ["written"] during a request: every access becomes an event.""" def tsg_params(error=0, ecc=0, space=0, engine=1, plugin=0): """NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS (20 bytes).""" return struct.pack(" control 0x801813).""" result, handle = self.alloc(client, device, 0, 0x90f1, params=R.vaspace_params(flags=0x48, base=0x1000)) assert result == 0 if register: assert self.run.dup_address_space(self.uvm_device, client, handle) == 0 assert self.run.set_page_directory(self.run.spaces[-1], directory, 4, video) == 0 self.flush_run() return handle class Registers(dict): """gpu_state["registers"] of a case with the channel register model (a `fixture ccsr-model` line): for channel `c` the word at 0x800000 + 8c reads back the last value written (0 before), and the word at 0x800004 + 8c reads bit 0 (ENABLE) as last set by a write with bit 10 (ENABLE_SET) or cleared by a write with bit 11 (ENABLE_CLR); every other bit reads 0 (status idle, not busy, no fault). All other registers behave as in the earlier harnesses (first read of the transcript, or a value the case names).""" def __init__(self, values): super().__init__(values) self.channels = {} @staticmethod def modelled(offset): return isinstance(offset, int) and 0x800000 <= offset < 0x808000 def __contains__(self, offset): return self.modelled(offset) or super().__contains__(offset) def __getitem__(self, offset): if self.modelled(offset): return self.channels.get(offset, 0) return super().__getitem__(offset) def written(self, offset, value): if self.modelled(offset): if offset & 4: enabled = self.channels.get(offset, 0) if value & 0x400: enabled = 1 if value & 0x800: enabled = 0 self.channels[offset] = enabled else: self.channels[offset] = value def _append(self, item): if isinstance(item, tuple): events().append(f"w {item[0]:x} {item[1]:x}") if isinstance(gpu_state["registers"], Registers): gpu_state["registers"].written(*item) else: events().append(f"r {item:x} {gpu_state['registers'][item]:x}") list.append(self, item) Accesses.append = _append process = {"pid": 4242} replace("os_get_current_process", lambda a: process["pid"]) replace("os_find_ns_pid", lambda a: (E.wd(a[1], process["pid"]), 0)[1]) def new_object(kind, before): objects = constructed[kind] return objects[before] if len(objects) > before else 0 def _channel_methods(): def ccsr_model(self): gpu_state["registers"] = Registers(gpu_state["registers"]) self.fixture("ccsr-model registers 800000..807fff: +0 reads the last value written," " +4 reads bit 0 as last set (write bit 10) or cleared (write bit 11)") def graphics_stub(self): graphics["stub"] = True self.fixture("graphics-info-stub KernelGraphics+0x1e0 (NULL on this fixture: no" " KernelGraphics stage body ran) is given a zeroed block of 8 records of" " 0x60 bytes on first use by _nv041022rm; without it the original takes a" " CPU exception in _nv041157rm when a channel on the graphics runlist is" " freed. Every graphics-side effect of such a free is therefore absent" " from this case") def context_bound(self, channel): """Stands for rm_gpu_ops_bind_channel_resources, which sets bIsContextBound (KernelChannel+0x28e) after promoting the context buffers; here only the byte.""" E.wb(self.channels[channel] + 0x28e, 1) self.fixture(f"context-bound {channel:x} KernelChannel+0x28e set to 1 by the fixture" " (no context buffer exists, nothing was promoted)") def process_id(self, pid): """The calling process (os_get_current_process, os_find_ns_pid).""" process["pid"] = pid self.lines.append(f"process {pid:x}") def group(self, engine=1, space=0, parent=DEVICE, client=CLIENT, new=0, **fields): """Class 0xa06c. State line on success: tsg """ before = len(constructed["group"]) result, handle = self.alloc(client, parent, new, 0xa06c, params=tsg_params(space=space, engine=engine, **fields)) if result == 0: self.groups[handle] = E.q(new_object("group", before) + 0x138) self.describe_group(handle) return result, handle def describe_group(self, handle): group = self.groups[handle] self.lines.append( f"tsg {handle:x} {E.d(group + 0x128):x} {E.d(group + 0x12c):x}" f" {E.d(group + 0x130):x} {E.d(group + 0x134):x} {E.q(group + 0x180):x}" f" {E.b(group + 0x191):x} {E.b(group + 0x1c0):x} {E.d(group + 0x23c):x}") def share(self, group, space, flags=1, subcontext=0, client=CLIENT, new=0): """Class 0x9067: (status, handle, subctxId of the reply).""" result, handle = self.alloc(client, group, new, 0x9067, params=share_params(space, flags, subcontext)) reply = bytes.fromhex(self.request_line().split()[-2]) return result, handle, struct.unpack_from(" image inst ; image userd """ fields.setdefault("gpfifo", 0x200400000 + 0x3000 * index) fields.setdefault("userd_offset", 0x2000 + 0x3000 * index) before = len(constructed["channel"]) result, handle = self.alloc(client, group, new, 0xc36f, params=channel_params(**fields)) if result == 0: self.channels[handle] = new_object("channel", before) reply = bytes.fromhex(self.request_line().split()[-2]) self.describe_channel(handle, struct.unpack_from(" ` (hex bytes).""" count = len(handles) if count is None else count source = E.allocate(4 * len(handles) + 16) target = E.allocate(4 * len(handles) + 16, 0xa5) E.write(source, b"".join(struct.pack(" -> the 16-byte nv_ioctl_alloc_os_event_t {hClient, hDevice, fd, Status} events records in the control state's list (+0x298) after the request and the "has events" byte of the calling file (nvfp+0x70) The reply of a class 0x79 allocation carries, at params +0x10, the address of the event record in fixture memory (the original returns a kernel pointer there): the harness replaces a non-zero value that differs from the request by 0x1000 in the record.""" case = standard("chan-events") control = case.context["nodes"]["ctl"] lock = E.allocate(16) E.wq(control + 0x2a0, lock) case.fixture("event-lock the control state's event spinlock (+0x2a0, a 16-byte wrapper" " the original's own initialization of the control node creates) is fixture" " memory; the list head +0x298 starts NULL") stack = U.runtime_stack() def os_event(escape, file, descriptor, client=CLIENT, size=16, node="dev"): request = struct.pack(" {status:x}" f" {reply.hex()} {','.join(state['diag']) or '-'}") case.finish() count, entry = 0, E.q(control + 0x298) while entry and count < 64: count, entry = count + 1, E.q(entry + 0x30) case.lines.append(f"events {count:x} {E.b(case.context['files'][file] + 0x70):x}") return status, (struct.unpack_from("= 16 else 0) def event(parent, new, index, data, file=3, node="dev", owner=CLIENT, klass=0x79, source=0, named=0x79): """Class 0x79: NV0005_ALLOC_PARAMETERS {hParentClient, hSrcResource, hClass, notifyIndex, data}.""" params = struct.pack("") + 2]) status = struct.unpack_from(" {struct.unpack_from('