#!/usr/bin/env python3 """Run chosen engine callbacks as original code inside the original stage passes over a constructed GV100, and write an oracle of what each one does. This extends tools/check_gpu_engine_dispatch_binary.py (imported unchanged; the RM API emulator behind it is imported unchanged too). The GPU object and every engine object are the ones the original's core init, probe and gpumgrAttachGpu build. The original passes _nv031220rm (PreInit), _nv031215rm (Init) and _nv031217rm (Load with PostLoad) then run from their entries. As in the dispatch oracle every non-default stage slot is a recorder that returns 0, except the callbacks listed in `LIVE`: those run as original instructions, in their place in the walk, with the lock state the original dispatcher gives them. Two things are written per case: 0. The header lines of the dispatch oracle for this GPU (`defaults`, `list`, `absent`, `missing`, `default-present`, `class`), and at the end its `observe` and `callback` lines. 1. `construct` lines: the construction-time value of every field the Rust engine states (`gpu/engine_bodies.rs::States`, `gpu/engine_bodies_more.rs`) and their arguments hold, read from the constructed objects before any pass runs. 2. Per live callback, a `live` block: live r register read at body level w register write at body level call = a callee the body reaches that is not part of the body registry = _nv049786rm; the fixture has no key out a value the callee left behind (see LEFT_BEHIND) in r/w ... register access inside that callee (not the body's) mem body|call + bytes of the GPU object and of every engine object that changed outside / inside callees, as hex strings transcript - ... comparison with the physical transcript window status The boundary between a body and its callees is `TRANSPARENT`: the functions the Rust body reproduces itself (named in the Rust module of each body). Every other function entered from the body or from a transparent function is a callee: it runs as original code (or as the fixture the emulator has for it), and is recorded with its result. Register values. A read is answered from the physical transcript of 0000:b3:00.0 (target/trace/b3-bar0.txt). When the callback has a transcript window (`WINDOWS`, from reports/original-trace-b3-segment-map.json and the lines themselves), the n-th read of a register inside the callback gets the n-th read of that register inside the window (source `t`); a register the window does not read, or a callback without a window, gets the last read before the window or the pass (source `p`), else the first read in the transcript (source `f`). A register the transcript never read stops the harness. Writes are recorded and not applied. What this proves: on the GPU the original constructs in emulation, with the earlier callbacks that have no Rust body replaced by recorders, what these original bodies read, write, call and store, and their status. What it does not prove: that a recorded callee has a Rust producer (the Rust comparison answers each callee with the recorded result); that the state these bodies see equals a physical first open's, where the earlier callbacks and the pre-stage steps of _nv000790rm ran (the `transcript` lines show where the two differ); anything about hardware. """ import difflib import hashlib import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import check_gpu_engine_dispatch_binary as D # noqa: E402 from unicorn import UC_HOOK_BLOCK, UC_HOOK_CODE, UC_HOOK_MEM_WRITE # noqa: E402 from unicorn.x86_const import UC_X86_REG_RIP, UC_X86_REG_RSI, UC_X86_REG_RSP # noqa: E402 from rmapi_binary_emulator import ARGS, BASES, CONTINUE, EXT, STACK # noqa: E402 E, R, world = D.E, D.R, D.world ROOT = D.ROOT OUT = ROOT / "target/gpu-stage" SPINE = json.loads((ROOT / "analysis/closed-driver-580/first-open-spine.json").read_text()) CHILDREN = {child["class_id"]: child for child in SPINE["children"]} LIVE_STUBS = 0x09200000 BAR0_PHYS, BAR0_SIZE = 0xa9000000, 0x1000000 BAR2_PHYS, BAR2_SIZE = 0x387400000000, 0x2000000 BAR2_VA = 0x50000000 E.cpu.mem_map(LIVE_STUBS, 0x100000) E.cpu.mem_map(R.BAR0 + 0x1000, BAR0_SIZE - 0x1000) E.cpu.mem_map(BAR2_VA, BAR2_SIZE) BAR2_VRAM = {} BAR0_WIN = [0x7fff0 << 16] def _bar2_mem_write(uc, access, addr, size, val, user): off = addr - BAR2_VA if 0xfa9000 <= off < 0xfaa000: BAR2_VRAM[0x7fff0e000 + (off - 0xfa9000)] = val & 0xffffffff elif 0 <= off < 0x1000: BAR2_VRAM[0x7fff0e000 + off] = val & 0xffffffff E.cpu.hook_add(UC_HOOK_MEM_WRITE, _bar2_mem_write, begin=BAR2_VA, end=BAR2_VA + BAR2_SIZE - 1) OBJMC, KERNEL_MC, INTR, OBJTMR, OBJBUS = 0x9aad0e, 0x3827ff, 0xc06e44, 0x9ddede, 0xcc4c31 KERNEL_FIFO, OBJDPAUX = 0xf3e155, 0xfd2ab9 HSHUB_MANAGER, VIRT_MEM_ALLOCATOR, OBJSEC2 = 0xbb32b9, 0x899e48, 0x28c408 # Functions that only carry a register access, a fill or a copy: the access macros with # their bookkeeping (_nv030477rm, _nv031156rm, _nv013539rm, _nv031155rm around a read; # _nv031157rm, _nv030927rm; _nv031395rm, _nv031426rm, _nv031390rm, _nv031478rm, _nv053913rm, # _nv031338rm, _nv031391rm, _nv031447rm, _nv013540rm around a write), the port-layer fill # and copy, the bit-vector helpers _nv017883rm.._nv017898rm, and _nv059479rm, which only # returns a global word (REA listing: `mov eax, [global]; ret`). PLUMBING = {"_nv053907rm", "_nv015884rm", "_nv053912rm", "_nv015885rm", "_nv049612rm", "_nv049615rm", "_nv030477rm", "_nv031156rm", "_nv013539rm", "_nv031155rm", "_nv031395rm", "_nv031426rm", "_nv031390rm", "_nv031478rm", "_nv053913rm", "_nv031157rm", "_nv030927rm", "_nv031338rm", "_nv031391rm", "_nv031447rm", "_nv013540rm", "_nv052705rm", "_nv052695rm", "os_mem_set", "os_mem_copy", "_nv017883rm", "_nv017885rm", "_nv017887rm", "_nv017890rm", "_nv017897rm", "_nv017898rm", "_nv059479rm"} # The access macros count in the GPU object (GPU+4120..+413f); those bytes are left out of # the `mem` lines. IO_BOOKKEEPING = ("GPU", 0x4120, 0x4140) # Per body (symbol number): the functions the Rust body reproduces itself. TRANSPARENT = { 43631: (), # _nv049734rm returns its second argument (gpu/mc_init.rs). 43629: ("_nv049734rm",), # _nv043627rm is the tail of InitLocked (gpu/mc_init.rs::init_locked). 43628: ("_nv043627rm",), # HAL body _nv043573rm and the engine-2 reset leaf (gpu/mc_load.rs). 43630: ("_nv043573rm", "_nv043634rm", "_nv043619rm", "_nv041568rm", "_nv043639rm"), 41564: (), 41565: (), # _nv037667rm with the entry count _nv037608rm and the vector length _nv060224rm # (gpu/intr_init.rs::init_interrupt_table); _nv052705rm is the table fill. 37777: ("_nv037667rm", "_nv037608rm", "_nv060224rm", "_nv052705rm"), 37773: (), # Bit-vector helpers over 0xb3 bits (gpu/intr_init.rs::init_locked). 37772: (), 37775: (), # HAL +190 _nv059661rm (gpu/timer/init.rs::program_time). 59663: ("_nv059661rm",), 59665: (), # HAL +300 _nv018541rm (gpu/bus_stage.rs::pre_init_locked). 18656: ("_nv018541rm",), 18653: (), # HAL +188 _nv018574rm, +1a8 _nv018683rm, +220 _nv018640rm with +210 _nv018450rm, # +370 _nv018468rm, +230 _nv018641rm, +228 _nv018636rm, +458 _nv018539rm # (gpu/bus_stage.rs::load). 18654: ("_nv018574rm", "_nv018683rm", "_nv018640rm", "_nv018450rm", "_nv018468rm", "_nv018641rm", "_nv018636rm", "_nv018539rm"), # _nv045390rm returns 0 and HAL +308 _nv018459rm is empty (gpu/bus_stage.rs::post_load). 18655: ("_nv045390rm", "_nv018459rm"), 40425: (), 26431: (), 59666: (), 59664: (), 35792: (), 42134: (), 26119: (), 55934: (), 41689: (), 34705: (), 26118: ("_nv026109rm", "_nv039138rm"), 43154: (), 42120: (), 42121: (), 29564: (), 17796: (), 51784: (), 44121: (), 46909: (), 47700: (), 60193: (), 41692: (), 52516: (), 43151: (), 60810: (), 27312: (), 26428: (), 39254: (), 46207: (), 39252: (), 27165: (), 39600: (), 41881: (), 41067: (), 39835: (), 19107: (), 19420: (), 35860: (), 45883: (), 27308: (), 46438: (), 55926: (), 29252: (), 35861: (), 39596: (), 46443: (), 45894: (), 44122: (), 29251: (), 34083: (), 47702: (), 27306: (), 18407: (), 19113: (), 34708: (), 43238: (), 51861: (), 39599: (), 43239: (), 16955: (), 40424: (), 29563: (), 18410: (), 36574: (), 43152: (), 33667: (), 21153: (), 21152: (), 51782: (), 59396: (), 45897: (), 45895: (), 19109: (), 34082: (), 27162: (), 37346: (), 43155: (), 50988: (), 41066: (), 46437: (), 18405: (), 41551: (), 59806: (), 39837: (), 44123: (), 45882: (), 36573: (), 21154: (), 51783: (), 47699: (), 40959: (), 37348: (), 28310: (), 16961: (), 17792: (), 41688: (), 44120: (), 29562: (), 40957: (), 43236: (), 39251: (), 41690: (), 50986: (), 28307: (), 39595: (), 51858: (), 17793: (), 59397: (), 40958: (), 27311: (), 50987: (), 17795: (), 39597: (), 40427: (), 33663: (), 33665: (), 55933: (), 28309: (), } CLOCK_MANAGER = 0xbcadd3 FAN = 0xadd018 GCX = 0x4507c4 GRAPHICS = 0xd334df GRAPHICS_MANAGER = 0x2f465a HSHUB = 0x5b3331 KERNEL_BIF = 0xdbe523 KERNEL_BUS = 0xd2ac57 KERNEL_CE = 0x242aca KERNEL_GMMU = 0x29362f KERNEL_GRAPHICS = 0xea3fa9 KERNEL_HWPM = 0xc8c00f KERNEL_MEMORY_SYSTEM = 0x7faff1 KERNEL_MIG_MANAGER = 0x1c1bf KERNEL_NVLINK = 0xce6818 KERNEL_PERF = 0xc53a57 KERNEL_PMU = 0xab9d7d LPWR = 0x112230 MEMORY_MANAGER = 0x22ad47 MEMORY_SYSTEM = 0x174e21 MIG_MANAGER = 0xfd75d0 NV_DEBUG_DUMP = 0x7e80a2 NVLINK = 0x790a3c OBJACR = 0xdb32a1 OBJBIF = 0xd1c956 OBJBSP = 0x8f99e1 OBJCE = 0x793ceb OBJCIPHER = 0x8dd911 OBJFBFLCN = 0x8a20bf OBJFIFO = 0xb02365 OBJGMMU = 0xd7a41d OBJHDACODEC = 0xa576e2 OBJHWPM = 0x97e43b OBJINFOROM = 0xe1639 OBJLSFM = 0x9a25e4 OBJMSENC = 0xe97b6c OBJUVM = 0xf9a17d OBJVBIOS = 0x5dc772 OBJVOLT = 0xa68120 PERF = 0xed0b65 PMGR = 0x894574 PMU = 0xf3d722 THERM = 0x6c1e56 # The callbacks that run as original code: (class id, slot) -> body symbol number. LIVE = { (OBJMC, "PreInitUnlocked"): 43631, (OBJMC, "InitUnlocked"): 43629, (OBJMC, "InitLocked"): 43628, (OBJMC, "Load"): 43630, (KERNEL_MC, "InitLocked"): 41564, (KERNEL_MC, "Load"): 41565, (INTR, "PreInitLocked"): 37777, (INTR, "InitUnlocked"): 37773, (INTR, "InitLocked"): 37772, (INTR, "Load"): 37775, (OBJTMR, "InitLocked"): 59663, (OBJTMR, "Load"): 59665, (OBJBUS, "PreInitLocked"): 18656, (OBJBUS, "InitLocked"): 18653, (OBJBUS, "Load"): 18654, (OBJBUS, "PostLoad"): 18655, (KERNEL_FIFO, "Load"): 40425, (KERNEL_MEMORY_SYSTEM, "Load"): 41689, (OBJDPAUX, "Load"): 26431, (OBJTMR, "PreInitLocked"): 59666, (OBJTMR, "InitUnlocked"): 59664, (LPWR, "PreInitLocked"): 43154, (OBJHDACODEC, "InitLocked"): 34705, (HSHUB_MANAGER, "InitLocked"): 35792, (KERNEL_PMU, "InitLocked"): 42134, (KERNEL_PERF, "InitLocked"): 42120, (KERNEL_PERF, "Load"): 42121, (OBJGMMU, "PostLoad"): 29564, (OBJBIF, "PreInitLocked"): 17796, (PMGR, "PreInitLocked"): 51784, (MEMORY_MANAGER, "Load"): 44121, (NV_DEBUG_DUMP, "InitLocked"): 46909, (NVLINK, "PostLoad"): 47700, (OBJVBIOS, "PreInitLocked"): 60193, (KERNEL_MEMORY_SYSTEM, "PreLoad"): 41692, (PMU, "PreInitLocked"): 52516, (LPWR, "Load"): 43151, (OBJVOLT, "Load"): 60810, (OBJFBFLCN, "PostLoad"): 27312, (OBJDPAUX, "InitLocked"): 26428, (KERNEL_BIF, "PostLoad"): 39254, (MIG_MANAGER, "InitLocked"): 46207, (KERNEL_BIF, "Load"): 39252, (FAN, "Load"): 27165, (KERNEL_BUS, "PreLoad"): 39600, (KERNEL_MIG_MANAGER, "InitLocked"): 41881, (KERNEL_GRAPHICS, "Load"): 41067, (KERNEL_CE, "InitLocked"): 39835, (OBJCE, "InitUnlocked"): 19107, (OBJCIPHER, "PreInitUnlocked"): 19420, (HSHUB, "InitLocked"): 35860, (HSHUB, "Load"): 35861, (MEMORY_SYSTEM, "InitUnlocked"): 45883, (MEMORY_SYSTEM, "PostLoad"): 45894, (OBJFBFLCN, "InitUnlocked"): 27308, (OBJMSENC, "InitUnlocked"): 46438, (OBJMSENC, "Load"): 46443, (OBJSEC2, "InitUnlocked"): 55926, (GCX, "PreLoad"): 29252, (GCX, "PostLoad"): 29251, (KERNEL_BUS, "Load"): 39596, (MEMORY_MANAGER, "PostLoad"): 44122, (GRAPHICS_MANAGER, "PostLoad"): 34083, (NVLINK, "PreInitLocked"): 47702, (OBJFBFLCN, "InitLocked"): 27306, (OBJBSP, "InitUnlocked"): 18407, (OBJCE, "PreLoad"): 19113, (OBJHDACODEC, "Load"): 34708, (OBJLSFM, "Load"): 43238, (PMU, "PostLoad"): 51861, (KERNEL_BUS, "PreInitLocked"): 39599, (OBJLSFM, "PreInitLocked"): 43239, (OBJACR, "InitLocked"): 16955, (KERNEL_FIFO, "InitLocked"): 40424, (OBJGMMU, "Load"): 29563, (OBJBSP, "Load"): 18410, (OBJHWPM, "Load"): 36574, (LPWR, "PostLoad"): 43152, (GRAPHICS, "PreInitLocked"): 33667, (CLOCK_MANAGER, "InitUnlocked"): 21153, (CLOCK_MANAGER, "InitLocked"): 21152, (PMGR, "InitLocked"): 51782, (THERM, "InitLocked"): 59396, (MEMORY_SYSTEM, "PreInitUnlocked"): 45897, (MEMORY_SYSTEM, "PreInitLocked"): 45895, (OBJCE, "PreInitLocked"): 19109, (GRAPHICS_MANAGER, "InitLocked"): 34082, (FAN, "InitLocked"): 27162, (OBJINFOROM, "Load"): 37346, (LPWR, "PreLoad"): 43155, (KERNEL_GRAPHICS, "InitLocked"): 41066, (OBJMSENC, "InitLocked"): 46437, (OBJBSP, "InitLocked"): 18405, (KERNEL_HWPM, "InitUnlocked"): 41551, (OBJUVM, "InitUnlocked"): 59806, (KERNEL_CE, "Load"): 39837, (PERF, "PostLoad"): 50988, (VIRT_MEM_ALLOCATOR, "InitLocked"): 26118, (VIRT_MEM_ALLOCATOR, "PostLoad"): 26119, (OBJSEC2, "PostLoad"): 55934, (KERNEL_MEMORY_SYSTEM, "PreInitLocked"): 41691, (MEMORY_MANAGER, "PreInitLocked"): 44123, (MEMORY_SYSTEM, "InitLocked"): 45882, (OBJHWPM, "InitUnlocked"): 36573, (CLOCK_MANAGER, "Load"): 21154, (PMGR, "Load"): 51783, (NVLINK, "Load"): 47699, (KERNEL_GMMU, "PostLoad"): 40959, (OBJINFOROM, "PostLoad"): 37348, (OBJFIFO, "PostLoad"): 28310, (OBJACR, "PreInitLocked"): 16961, (OBJBIF, "InitLocked"): 17792, (KERNEL_MEMORY_SYSTEM, "InitLocked"): 41688, (MEMORY_MANAGER, "InitLocked"): 44120, (OBJGMMU, "InitLocked"): 29562, (KERNEL_GMMU, "InitLocked"): 40957, (OBJLSFM, "InitLocked"): 43236, (KERNEL_BIF, "InitLocked"): 39251, (KERNEL_MEMORY_SYSTEM, "PostLoad"): 41690, (PERF, "InitLocked"): 50986, (OBJFIFO, "InitLocked"): 28307, (KERNEL_BUS, "InitLocked"): 39595, (PMU, "InitLocked"): 51858, (OBJBIF, "Load"): 17793, (THERM, "Load"): 59397, (KERNEL_GMMU, "Load"): 40958, (OBJFBFLCN, "Load"): 27311, (PERF, "Load"): 50987, (OBJBIF, "PostLoad"): 17795, (KERNEL_BUS, "PostLoad"): 39597, (KERNEL_FIFO, "PostLoad"): 40427, (GRAPHICS, "InitLocked"): 33663, (GRAPHICS, "Load"): 33665, (OBJSEC2, "Load"): 55933, (OBJFIFO, "Load"): 28309, } # Transcript windows (first line, last line) of the callbacks, 1-based lines of # target/trace/b3-bar0.txt. Basis: reports/original-trace-b3-segment-map.json segments # 12-13 (KernelGmmu fault-buffer registers reached from OBJBUS PreInitLocked through # KernelBus+168, then the OBJBUS reads), 22 (I2C port reset: the callee of OBJMC InitLocked # at slot 1b0 of the GPU+20e8 object; the map attributes it to Pmgr), 23, 34 (the fuse words # read by GPU+598 from OBJBUS InitLocked; the map attributes them to KernelGmmu), 48, 49, # 50 and 56. WINDOWS = { (OBJBUS, "PreInitLocked"): (37591, 37603), (OBJACR, "PreInitLocked"): (37713, 37722), (OBJMC, "InitLocked"): (48161, 48181), (OBJTMR, "InitLocked"): (48182, 48184), (OBJBUS, "InitLocked"): (107714, 107727), (OBJMC, "Load"): (139243, 139246), (KERNEL_MC, "Load"): (139247, 139248), (OBJTMR, "Load"): (139250, 139259), (OBJBUS, "Load"): (140573, 140587), } # Transcript ranges of the passes (stage_boundaries of the segment map). PASS_START = {"_nv031220rm": 37296, "_nv031215rm": 47967, "_nv031217rm": 138803} # Callees whose result is also a value they leave behind: name -> (argument index, bytes). LEFT_BEHIND = {"_nv030645rm": (1, 4), "_nv049684rm": ((0, 4), (1, 4)), "_nv031094rm": (2, 4), "_nv019282rm": (3, 1), "_nv019141rm": (3, 1)} # Construction-time fields: (object, offset, bytes). Objects are "GPU", a class name, or # "@" for a field of another engine a body reads or writes. FIELDS = ( # gpu/mc_init.rs::State ("OBJMC", 0x1b8, 1), ("OBJMC", 0x1b9, 1), ("OBJMC", 0x1bb, 1), ("OBJMC", 0x1c4, 1), ("OBJMC", 0x1c5, 1), ("OBJMC", 0x1c6, 1), ("OBJMC", 0x1c7, 1), ("GPU", 0x98d, 1), ("GPU", 0x99c, 1), ("GPU", 0x99e, 1), # gpu/kernel_mc.rs::State (InitLocked stores both) ("KernelMc", 0x108, 1), ("KernelMc", 0x10c, 4), # gpu/intr_init.rs::State and the service table ("Intr", 0x3f0, 1), ("Intr", 0x3f5, 1), ("Intr", 0x3f6, 1), ("Intr", 0x3f7, 1), ("Intr", 0x448, 4), ("Intr", 0x1518, 40), ("Intr", 0x1540, 40), ("Intr", 0x1608, 56), ("Intr", 0x1640, 1), ("Intr", 0x1668, 8), ("Intr", 0x1670, 8), ("Intr", 0x1678, 4), ("Intr", 0x1684, 4), ("Intr", 0x1688, 24), ("Intr", 0x16b8, 4), ("Intr", 0x16c8, 4), ("Intr", 0x16cc, 1), ("GPU", 0xdec, 4), ("Intr", 0x450, 0x10c8), # gpu/timer/init.rs::{InitState, Selection}; the two list heads and the callback kind # gpu/timer/load.rs reads ("OBJTMR", 0x2518, 4), ("OBJTMR", 0x24e, 1), ("OBJTMR", 0x248, 4), ("OBJTMR", 0x250, 8), ("OBJTMR", 0x258, 8), ("GPU", 0x90b, 1), ("GPU", 0x998, 1), ("GPU", 0x69e4, 4), ("GPU", 0xe01, 1), # gpu/bus_stage.rs::State ("OBJBUS", 0x460, 1), ("OBJBUS", 0x461, 1), ("OBJBUS", 0x467, 1), ("OBJBUS", 0x469, 1), ("OBJBUS", 0x5e4, 4), ("OBJBUS", 0x5e8, 1), ("OBJBUS", 0x5f0, 1), ("OBJBUS", 0x664, 4), ("OBJBUS", 0x668, 4), ("GPU", 0x4dd8, 4), # gpu/engine_bodies.rs::Arguments ("GPU", 0x90f, 1), ("GPU", 0xe00, 1), ("GPU", 0x52fc, 1), ("GPU", 0x6d29, 1), # OBJHDACODEC InitLocked (_nv034705rm) & VirtMemAllocator InitLocked (_nv026118rm) ("OBJHDACODEC", 0x218, 4), ("VirtMemAllocator", 0x120, 4), # GCX PreLoad (_nv029252rm) ("GCX", 0x1f8, 1), ("GCX", 0x1fb, 1), # OBJCE PreLoad (_nv019113rm) *[pair for i in range(9) for pair in ((f"OBJCE[{i}]", 0x485, 1), (f"OBJCE[{i}]", 0x489, 1))], # OBJBSP Load (_nv018410rm) & OBJHWPM Load (_nv036574rm) ("OBJBSP[0]", 0x448, 4), ("OBJHWPM", 0x82c, 4), # Graphics PreInitLocked (_nv033667rm) & Therm InitLocked (_nv059396rm) ("GraphicsManager", 0x650, 1), ("Therm", 0x708e, 1), # MemorySystem PreInitUnlocked (_nv045897rm) & PreInitLocked (_nv045895rm) ("MemorySystem", 0x8cb5, 1), ("MemorySystem", 0x8bfc, 4), ("MemorySystem", 0x8c11, 1), ("MemorySystem", 0x8c15, 1), ("MemorySystem", 0x13e8, 8), ("MemorySystem", 0x3f58, 8), ("MemorySystem", 0x8cf1, 1), ("MemorySystem", 0x8c48, 1), # Fan InitLocked (_nv027162rm), Lpwr PreLoad (_nv043155rm), OBJINFOROM Load (_nv037346rm) ("Fan", 0x14c, 4), ("Fan", 0x154, 4), ("Fan", 0x178, 24), ("Lpwr", 0x1208, 8), ("OBJINFOROM", 0x1f80, 1), ) # Fields of other engines' objects: (label, GPU child offset, offset in that object, bytes). FOREIGN = ( ("gpu_2068_337", 0x2068, 0x337, 1), ("gpu_1ec0_4384", 0x1ec0, 0x4384, 4), ("gpu_1f90_4a0", 0x1f90, 0x4a0, 4), ("gpu_1f70_190a", 0x1f70, 0x190a, 1), ("gpu_22c8_11d8", 0x22c8, 0x11d8, 8), ("gpu_22c8_11c0", 0x22c8, 0x11c0, 8), ("gpu_1e90_334", 0x1e90, 0x334, 1), ("gpu_1e90_344", 0x1e90, 0x344, 4), ) # Child pointers whose presence the bodies test. POINTERS = (0x1ec0, 0x20e8, 0x2120, 0x22f8, 0x1f90, 0x1f70, 0x1fb8, 0x1f80, 0x22c8, 0x2068) live = {} transcript = [] def load_transcript(): if not transcript: for number, line in enumerate(R.TRANSCRIPT.read_text().splitlines(), 1): parts = line.split() if parts[0] in ("R", "W"): transcript.append((number, parts[0], int(parts[1], 16), int(parts[2], 16))) return transcript class Registers: """Answers reads from the transcript as the module text describes.""" def __init__(self): self.lines = load_transcript() self.reads = {} for number, kind, offset, value in self.lines: if kind == "R": self.reads.setdefault(offset, []).append((number, value)) self.window = None self.floor = 0 self.used = {} def enter(self, window, floor): self.window, self.floor, self.used = window, floor, {} def read(self, offset): if 0x700000 <= offset < 0x800000: fb = BAR0_WIN[0] + (offset - 0x700000) if fb in BAR2_VRAM: return BAR2_VRAM[fb], "vram" history = self.reads.get(offset) if not history: if offset == 0x9410: return 0, "ptimer_hi" if offset == 0x9400: return 0x1000, "ptimer_lo" if offset == 0x8b980: return 0, "untraced_8b980" # V100 per-GPC TPC count/config registers (lost-event gap in b3-bar0.txt; # values forced by transcript lines 157093-157110, see gr_init.rs & # reports/gpu-graphics-load-original.json). v100_tpc = { 0x502608: 0x40007, 0x50a608: 0x40007, 0x512608: 0x40007, 0x51a608: 0x40006, 0x522608: 0x40007, 0x52a608: 0x40006, } if offset in v100_tpc: return v100_tpc[offset], f"v100_tpc_{offset:x}" # Late reads of Graphics InitLocked (_nv033662rm) in the same lost-event gap # (tools/check_gpu_graphics_init_binary.py). if offset in (0x1070, 0x40960c, 0x500920): return 0, f"gr_init_{offset:x}" assert history, f"register {offset:#x} has no transcript value" start = self.floor if self.window: first, last = self.window inside = [entry for entry in history if first <= entry[0] <= last] position = self.used.get(offset, 0) if position < len(inside): self.used[offset] = position + 1 return inside[position][1], f"t{inside[position][0]}" if inside: return inside[-1][1], f"t{inside[-1][0]}" start = first before = [entry for entry in history if entry[0] < start] if before: return before[-1][1], f"p{before[-1][0]}" return history[0][1], f"f{history[0][0]}" def objects(): """Label -> (address, size) of the GPU object and every engine object, with the size of the allocation each lies in.""" gpu = world["gpu"] found = {"GPU": gpu} for child in SPINE["children"]: for instance in range(child["slots"]): pointer = E.q(gpu + child["gpu_offset"] + 8 * instance) if pointer: name = child["name"] or f"class{child['class_id']:x}" found[name if child["slots"] == 1 else f"{name}[{instance}]"] = pointer result = {} blocks = sorted(live["allocations"]) for label, pointer in found.items(): block = max((entry for entry in blocks if entry[0] <= pointer), default=None) assert block and pointer < block[0] + block[1], f"{label} is in no allocation" result[label] = (pointer, block[0] + block[1] - pointer) return result def snapshot(): return {label: E.read(pointer, size) for label, (pointer, size) in live["objects"].items()} def difference(before, after): """Changed byte runs as (label, offset, old, new).""" runs = [] for label, old in before.items(): new = after[label] if old == new: continue offset, size = 0, len(old) while offset < size: if old[offset] == new[offset]: offset += 1 continue end = offset while end < size and old[end] != new[end]: end += 1 if not (label == IO_BOOKKEEPING[0] and IO_BOOKKEEPING[1] <= offset < IO_BOOKKEEPING[2]): runs.append((label, offset, old[offset:end], new[offset:end])) offset = end return runs def render(value): """A register argument: an object-relative name where it is a pointer the oracle knows.""" if STACK <= value < STACK + 0x100000: return "stack" for label, (pointer, size) in live["objects"].items(): if pointer <= value < pointer + size: return label if value == pointer else f"{label}+{value - pointer:x}" if BASES[".rodata"] <= value < BASES[".rodata"] + 0x8000000: return f"rodata+{value - BASES['.rodata']:x}" if BASES[".text"] <= value < BASES[".text"] + 0x8000000: return D.symbol(value) if 0x40000000 <= value < 0x4c000000: return "heap" return f"{value:x}" def emit(text): live["lines"].append(text) def body_delta(): now = snapshot() for label, offset, old, new in difference(live["snapshot"], now): emit(f"mem {live['scope']} {label}+{offset:x} {old.hex()} {new.hex()}") live["snapshot"] = now def function_entry(emu, address, size, unused): """Block hook over .text and the externals: finds the callees of a live body.""" if live.get("active") is None or live["callee"] is not None: return name = E.entry_names.get(address) or live["external_names"].get(address) if name is None or name in live["transparent"] or name.startswith("__x86_indirect_thunk"): return arguments = [emu.reg_read(register) for register in ARGS] rsp = emu.reg_read(UC_X86_REG_RSP) return_address = E.q(rsp) body_delta() live["callee"] = name live["scope"] = "call" if name == "_nv049786rm": header = f"registry {E.text(arguments[1])}" else: header = f"call {name} " + " ".join(render(value) for value in arguments) position = len(live["lines"]) emit(header) def after(value): result = value & 0xffffffff if value >> 32 in (0, 0xffffffff) else value live["lines"][position] = f"{header} = {render(result)}" spec = LEFT_BEHIND.get(name) if spec: for index, width in ((spec,) if isinstance(spec[0], int) else spec): data = E.read(arguments[index], width) emit(f"out {name} {int.from_bytes(data, 'little'):x}") body_delta() live["callee"] = None live["scope"] = "body" emu.reg_write(UC_X86_REG_RIP, return_address) return None E.wq(rsp, CONTINUE) E.continuations.append(after) def register_read(a): offset = a[2] & 0xffffffff value, source = live["registers"].read(offset) if live.get("active") is not None: live["accesses"].append(("R", offset, value)) emit(("in " if live["callee"] else "") + f"r {offset:x} {value:x} {source}") return value def register_write(a): offset, value = a[2] & 0xffffffff, a[3] & 0xffffffff if offset == 0x1700: BAR0_WIN[0] = (value & 0xffffff) << 16 elif 0x700000 <= offset < 0x800000: fb = BAR0_WIN[0] + (offset - 0x700000) BAR2_VRAM[fb] = value if 0x7fff0e000 <= fb < 0x7fff0f000: E.wd(BAR2_VA + 0xfa9000 + (fb - 0x7fff0e000), value) E.wd(BAR2_VA + (fb - 0x7fff0e000), value) if live.get("active") is not None: live["accesses"].append(("W", offset, value)) emit(("in " if live["callee"] else "") + f"w {offset:x} {value:x}") return 0 def compare_with_transcript(key): """The callback's accesses (body and callees) against its transcript window.""" window = WINDOWS.get(key) if window is None: return "transcript - " + ("none" if not live["accesses"] else f"no-window {len(live['accesses'])}") physical = [(kind, offset, value) for number, kind, offset, value in load_transcript() if window[0] <= number <= window[1]] emulated = live["accesses"] mine = [f"{kind}{offset:x}" for kind, offset, _value in emulated] theirs = [f"{kind}{offset:x}" for kind, offset, _value in physical] if mine == theirs: differing = [f"{offset:x}:{value:x}/{other:x}" for (_kind, offset, value), (_k, _o, other) in zip(emulated, physical) if value != other] verdict = ("same-accesses-other-values " + " ".join(differing) if differing else "equal") else: # "+" an access only the emulation made, "-" one only the physical run made. notes = [] for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, mine, theirs, autojunk=False).get_opcodes(): if tag in ("delete", "replace"): notes += ["+" + entry for entry in mine[i1:i2]] if tag in ("insert", "replace"): notes += ["-" + entry for entry in theirs[j1:j2]] verdict = f"differs emulated={len(mine)} physical={len(theirs)} " + " ".join(notes) return f"transcript {window[0]}-{window[1]} {verdict}" def live_hook(emu, address, size, unused): table, slot, target = live["stubs"][(address - LIVE_STUBS) // 16] engstate = emu.reg_read(UC_X86_REG_RSI) descriptor = world["engstates"][engstate] body = D.class_body(engstate, target)[0] number = D.number(D.symbol(body)) key = (descriptor >> 8, slot) expected = live["selected"][key] assert expected in (None, number), f"{descriptor:x} {slot} dispatches to {number}" emit(f"live {descriptor:x} {slot} {D.number(D.symbol(target))} {number} " f"{int(world['locked'])}") live["registers"].enter(WINDOWS.get(key), PASS_START[live["pass"]]) live["transparent"] = PLUMBING | set(TRANSPARENT.get(number, ())) | {D.symbol(body), D.symbol(target)} live.update(active=key, callee=None, scope="body", accesses=[], snapshot=snapshot()) world["events"].append(["callback", descriptor, slot, D.symbol(target), D.symbol(body), int(world["locked"]), None]) event = world["events"][-1] def after(value): assert live["callee"] is None, f"{live['callee']} did not return" body_delta() emit(compare_with_transcript(key)) emit(f"status {value & 0xffffffff:x}") event[6] = value & 0xffffffff live["active"] = None return value E.nested(target, [emu.reg_read(register) for register in ARGS], after) E.cpu.hook_add(UC_HOOK_CODE, live_hook, begin=LIVE_STUBS, end=LIVE_STUBS + 0xfffff) E.cpu.hook_add(UC_HOOK_BLOCK, function_entry, begin=BASES[".text"], end=BASES[".text"] + 0x8000000) E.cpu.hook_add(UC_HOOK_BLOCK, function_entry, begin=EXT, end=EXT + 0x10000) def replace(name, handler): if name in R.HOOKS: E.cpu.hook_del(R.HOOKS.pop(name)) E.handlers.pop(name, None) R.HOOKS[name] = E.install(name, handler) def construct(selected): """A constructed GPU with recorders, and original code in the `selected` slots. Returns the `construct` lines.""" allocations = [] def allocate(a): size = a[1] & 0xffffffff status = R.allocate(a) allocations.append((E.q(a[0]), size)) return status replace("os_alloc_mem", allocate) live.clear() live.update(allocations=allocations, stubs=[], lines=[], active=None, callee=None, selected=selected, external_names={address: name for name, address in E.externals.items()}) lines = D.construct() replace("_nv049612rm", register_read) replace("_nv049615rm", register_write) for name, handler in R.STAGE_FIXTURES.items(): replace(name, handler) E.wq(E.externals["os_page_size"], 0x1000) E.wq(E.externals["os_page_mask"], 0xfffffffffffff000) E.wq(E.externals["os_page_shift"], 12) pages_state = {"next": 1, "pages": {}} def alloc_pages(a): count, size, contiguous = a[1] & 0xffffffff, a[2], a[3] & 0xff table, private = E.stack_argument(2), E.stack_argument(3) index = pages_state["next"] pages_state["next"] += 1 base = 0x100000000 + 0x10000000 * index for entry in range(1 if contiguous else count): E.wq(table + 8 * entry, base + entry * size) cookie = E.allocate(16) E.wq(cookie, index) E.wq(private, cookie) pages_state["pages"][cookie] = {"base": base, "bytes": count * size, "backing": None} return 0 def free_pages(a): pages_state["pages"].pop(a[4], None) return 0 def alloc_kernel_mapping(a): record = pages_state["pages"][a[1]] if record["backing"] is None: record["backing"] = E.allocate(record["bytes"]) return record["backing"] + a[2] * 0x1000 + (a[3] & 0xffffffff) replace("nv_alloc_pages", alloc_pages) replace("nv_free_pages", free_pages) replace("nv_alloc_kernel_mapping", alloc_kernel_mapping) replace("nv_free_kernel_mapping", lambda a: 0) replace("nv_get_device_memory_config", lambda a: 0x56) replace("os_pat_supported", lambda a: 1) replace("os_flush_cpu_write_combine_buffer", lambda a: 0) BAR2_VRAM.clear() BAR0_WIN[0] = 0x7fff0 << 16 mapped_other = {} def map_kernel_space(a): phys, size = a[0], a[1] if BAR0_PHYS <= phys < BAR0_PHYS + BAR0_SIZE: return R.BAR0 + (phys - BAR0_PHYS) if BAR2_PHYS <= phys < BAR2_PHYS + BAR2_SIZE: return BAR2_VA + (phys - BAR2_PHYS) if phys not in mapped_other: mapped_other[phys] = E.allocate(max(size, 0x1000)) return mapped_other[phys] replace("os_map_kernel_space", map_kernel_space) mono_ns = [0] def monotonic_time_ns(a): mono_ns[0] += 1_000_000_000 return mono_ns[0] replace("os_get_monotonic_time_ns", monotonic_time_ns) replace("os_get_monotonic_time_ns_hr", monotonic_time_ns) live["registers"] = Registers() live["registers"].enter(None, 0) live["objects"] = objects() gpu = world["gpu"] for table, slot, target in world["stubs"]: users = [descriptor for engstate, descriptor in world["engstates"].items() if E.q(engstate) == table] if (users[0] >> 8, slot) in selected: E.wq(table + D.SLOT_OFFSET[slot], LIVE_STUBS + 16 * len(live["stubs"])) live["stubs"].append((table, slot, target)) assert len(live["stubs"]) == len(selected), "a selected slot is not a non-default slot" for label, offset, width in FIELDS: pointer = live["objects"][label][0] lines.append(f"construct {label}+{offset:x} {E.read(pointer + offset, width).hex()}") for label, child, offset, width in FOREIGN: pointer = E.q(gpu + child) lines.append(f"construct {label} " + (E.read(pointer + offset, width).hex() if pointer else "absent")) lines.append("construct pointers " + " ".join( f"{offset:x}={int(E.q(gpu + offset) != 0)}" for offset in POINTERS)) return lines def case(name, selected): lines = [f"case {name}"] + construct(selected) R.state["diag"].clear() for entry, arguments in (("_nv031220rm", ()), ("_nv031215rm", ()), ("_nv031217rm", (0,))): live["pass"] = entry emit(f"pass {D.number(entry)}") status = D.run_pass(entry, *arguments) emit(f"pass-status {D.number(entry)} {status:x}") if status != 0: break lines += live["lines"] # The whole walk, as in the dispatch oracle: a live callback has its own status. for event in world["events"]: if event[0] == "observe": lines.append(f"observe {event[1]:x} {event[2]} {D.number(event[3])} {event[4]:x}") elif event[0] == "callback": _, descriptor, slot, wrapper, body, locked, status = event lines.append(f"callback {descriptor:x} {slot} {D.number(wrapper)} " f"{D.number(body)} {locked} {status:x}") lines.append("diagnostics " + (" ".join(str(entry) for entry in R.state["diag"]) or "-")) lines.append("end") return lines def survey_one(class_id, slot): """One callback (every instance of the class) as original code with nothing declared transparent: its direct callees, every register access under it, its status. Prints one JSON object. Planning evidence: the other callbacks are recorders, so the state it runs on is the constructed one, not that of a first open.""" result = {"class_id": f"{class_id:x}", "slot": slot, "completed": False} try: construct({(class_id, slot): None}) R.state["diag"].clear() for entry, arguments in (("_nv031220rm", ()), ("_nv031215rm", ()), ("_nv031217rm", (0,))): live["pass"] = entry if D.run_pass(entry, *arguments) != 0: break result["completed"] = True except Exception as error: # the reason is the result result["stopped"] = str(error).split(" after [")[0][:300] lines = live.get("lines", []) reads, writes, callees = [], [], [] for line in lines: fields = line.split(" ") if fields[0] == "in": fields = fields[1:] if fields[0] == "r": reads.append(int(fields[1], 16)) elif fields[0] == "w": writes.append(int(fields[1], 16)) elif fields[0] in ("call", "registry"): callees.append(fields[1] if fields[0] == "call" else "registry:" + fields[1]) result.update( instances=sum(line.startswith("live ") for line in lines), statuses=sorted({line.split(" ")[1] for line in lines if line.startswith("status ")}), body=next((int(line.split(" ")[4]) for line in lines if line.startswith("live ")), None), reads=len(reads), writes=len(writes), registers_read=[f"{offset:x}" for offset in sorted(set(reads))][:400], registers_written=[f"{offset:x}" for offset in sorted(set(writes))][:400], callee_calls=len(callees), callees=sorted(set(callees))[:60], body_state_changes=sum(line.startswith("mem body ") for line in lines), objects_changed=sorted({line.split(" ")[2].split("+")[0] for line in lines if line.startswith("mem ")}), diagnostics=list(R.state["diag"])[:20]) print("SURVEY " + json.dumps(result)) def survey(): """Every non-default stage callback of the constructed GV100, each alone, each in its own process (a stopped emulation does not leak into the next). Writes reports/gv100-engine-callback-survey.json.""" import concurrent.futures import subprocess D.construct() wanted = [] for table, slot, _target in world["stubs"]: if slot in D.RECORDED: descriptor = next(value for engstate, value in world["engstates"].items() if E.q(engstate) == table) wanted.append((descriptor >> 8, slot)) def run(item): class_id, slot = item try: done = subprocess.run([sys.executable, __file__, "SURVEY-ONE", f"{class_id:x}", slot], capture_output=True, text=True, timeout=240) except subprocess.TimeoutExpired: return {"class_id": f"{class_id:x}", "slot": slot, "completed": False, "stopped": "no end within 240 s (a wait the fixtures never satisfy)"} for line in done.stdout.splitlines(): if line.startswith("SURVEY "): return json.loads(line[7:]) return {"class_id": f"{class_id:x}", "slot": slot, "completed": False, "stopped": "harness: " + done.stderr.strip().splitlines()[-1][:300]} with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: results = list(pool.map(run, wanted)) names = {child["class_id"]: child["name"] for child in SPINE["children"]} for entry in results: entry["class"] = names.get(int(entry["class_id"], 16)) report = { "evidence_category": "instruction emulation of the original object; planning evidence", "tool": "tools/check_gpu_engine_live_binary.py SURVEY", "method": "per (class, slot): the original passes _nv031220rm, _nv031215rm, " "_nv031217rm over the GPU the original constructs, with that one callback " "(every instance) executed as original code and every other non-default " "callback a recorder returning 0. Register reads: last read before the " "pass in the physical transcript, else the first read; writes not applied.", "limits": "the state each callback sees is the constructed one, not a first open's; " "a completed callback with no register access is not thereby a constant; " "`stopped` names what ended the emulation (a register the transcript never " "read, an open-layer symbol without a fixture, an unmapped access, a wait).", "callbacks": results, } (ROOT / "reports/gv100-engine-callback-survey.json").write_text( json.dumps(report, indent=1) + "\n") print(json.dumps({"report": "reports/gv100-engine-callback-survey.json", "callbacks": len(results), "completed": sum(entry["completed"] for entry in results)})) def main(): if "SURVEY-ONE" in sys.argv: position = sys.argv.index("SURVEY-ONE") return survey_one(int(sys.argv[position + 1], 16), sys.argv[position + 2]) if "SURVEY" in sys.argv: return survey() lines = case("first-open-live", dict(LIVE)) if "PRINT" in sys.argv: print("\n".join(lines)) OUT.mkdir(parents=True, exist_ok=True) text = "\n".join(lines) + "\n" (OUT / "original-engine-live.txt").write_text(text) print(json.dumps({"oracle": "target/gpu-stage/original-engine-live.txt", "sha256": hashlib.sha256(text.encode()).hexdigest(), "live_callbacks": sum(line.startswith("live ") for line in lines), "lines": len(lines)})) if __name__ == "__main__": main()