#!/usr/bin/env python3 """Run the original producers of the OBJLSFM Falcon mask and write an oracle. The dword at OBJLSFM+198 has one bit per light-secure Falcon id. A set bit means the manager does not handle that Falcon: _nv043190rm(gpu, lsfm, id) returns it, the NVDEC HS run (core gpu::nvdec_hs_run) asks it for the NVDEC Falcon, and a Falcon whose bit is clear after InitLocked is a client of the WPR image. This harness executes the original code that produces the dword on a GV100 (chip HAL 0x23, RM HAL 2) with the object's real relocations for .text, .rodata and .data, function tables filled by the original binders and creators, and writes the cases core gpu::lsfm_mask is compared with. Executed original code: OBJLSFM ConstructEngine _nv043185rm with the table entries +108, +128, +130, +138; PreInitLocked _nv043239rm; InitLocked _nv043236rm with _nv043182rm, _nv043197rm, the entries +100, +118, +188; the query _nv043190rm. OBJACR ConstructEngine _nv016731rm (the stores to +37b, +37c, +381 and +391 are compared); PreInitLocked _nv016961rm with the entries +100 _nv016960rm, +108, +118; _nv016949rm, +148, +1a8, +1b0. OBJFUSE binder _nv005974rm; _nv030951rm, +118 _nv029006rm, +100 _nv029045rm, +168 _nv029047rm, _nv028943rm. Jtag object creation _nv006537rm (function +100 and byte +108 for the chip), +100 _nv039060rm. OBJVBIOS binder _nv006018rm and property initializer _nv005846rm; the function they store at +270. PMU class creator _nv005744rm, property initializer _nv005852rm, the start of the class constructor body _nv051986rm up to the function at +330 (_nv052503rm), +308 _nv052063rm, _nv052305rm, _nv052182rm, +3d8 _nv052308rm. Falcons as tools/check_gpu_wpr_blob_binary.py builds them: NVDEC, SEC2, PMU, FECS and GPCCS by their creators, binders and configuration functions, attached with _nv021629rm, configured with _nv028412rm (with _nv043743rm executed), images prepared by _nv028614rm from the packed records in .rodata. GPU chip identification _nv030179rm and _nv030823rm from the traced BOOT0 and BOOT42 words; the chip predicates _nv030932rm and _nv030933rm with the table _nv031281rm. Fixture-supplied: register reads (_nv053907rm), diagnostics, the allocator, memory fill and copy performed as such, the registry lookup _nv049786rm, the class cast of the Jtag creation, the base constructor _nv003389rm, the ancestor lookup of the PMU constructor, _nv015308rm (where the PMU constructor is stopped), the OBJACR function at +130 (the HS ACR preparation, recorded), the HS ACR image preparation _nv016905rm of the OBJACR constructor (recorded), the 32-bit read of the OBJFUSE register aperture (the register at its base plus the offset), the object _nv006784rm creates at OBJFUSE+2f8, the device aperture at GPU+1d30, the memory-descriptor and multi-GPU services, the netlist views of the FECS and GPCCS objects, and the order in which the Falcons were registered. No hardware is involved. """ import bisect from _binary_path import resolve_580_binary import hashlib import itertools import json from pathlib import Path import struct import warnings warnings.simplefilter("ignore") from elftools.elf.elffile import ELFFile # noqa: E402 from unicorn import (UC_ARCH_X86, UC_HOOK_BLOCK, UC_HOOK_CODE, UC_HOOK_MEM_WRITE, # noqa: E402 UC_MODE_64, Uc, UcError) from unicorn.x86_const import (UC_X86_REG_R8, UC_X86_REG_R9, UC_X86_REG_RAX, # noqa: E402 UC_X86_REG_RBP, UC_X86_REG_RCX, UC_X86_REG_RDI, UC_X86_REG_RDX, UC_X86_REG_RIP, UC_X86_REG_RSI, UC_X86_REG_RSP) ROOT = Path(__file__).resolve().parents[1] ORIGINAL = resolve_580_binary() DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b" TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt" RODATA_ADDRESS = 0x111d660 # address of .rodata in the analysis database TEXT, RODATA, DATAS, BSS, DATA, STACK, STOP, HEAP = ( 0x10000000, 0x20000000, 0x28000000, 0x2c000000, 0x30000000, 0x40000000, 0x50000000, 0x60000000) INDIRECT, EXTERNAL, SERVICE = STOP + 0x100, STOP + 0x200, STOP + 0xc000 DATA_BYTES, HEAP_BYTES = 0x400000, 0x1000000 (GPU, CHIP, RM, NVDEC, PMUX, SEC2, GRAPHICS, FECS, GPCCS, ACR, LSFM, F_NVDEC, F_PMU, F_SEC2, F_FECS, F_GPCCS, VBIOS, FUSE, SCRATCH, MEMORY, JTAG) = ( DATA + 0x20000 * index for index in range(21)) PMU = PMUX + 8 (KERNEL_GRAPHICS, SYSTEM, MANAGER, FACTORY, MEMMGR, REGION, PMU_CHILD, TABLES, PARENT, MAPPING) = (MEMORY + 0x1000 * index for index in range(10)) 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) # Class vtables and self pointers the creators _nv006485rm and _nv006495rm store. GRAPHICS_FALCONS = (("FECS", FECS, (0x4db66c0, 0x4db66d8, 0x4db6838), "_nv005875rm", "_nv005777rm"), ("GPCCS", GPCCS, (0x4db69e0, 0x4db69f8, 0x4db6b58), "_nv005879rm", "_nv005781rm")) DIAGNOSTICS = ("_nv047869rm", "_nv047868rm", "_nv046745rm", "_nv046747rm", "_nv046751rm") # Register values of the traced V100 (target/trace/b3-bar0.txt). BOOT0, BOOT42 = 0x140000a1, 0x140a1000 PHYSICAL = {0x10ac08: 0, 0x21644: 1, 0x10a108: 0x400e0100, 0x87108: 0x20420100, 0x1373a0: 0xa, 0x21434: 1} JTAG_REGISTER, FUSE_REGISTER, DEBUG_REGISTER = 0x1373a0, 0x21434, 0x10ac08 LSFM_KEYS = ("RMLSFMDisableMask", "RmLSFMFeature") ACR_KEYS = ("RmAcrSigningAlgo", "RmUseAutoAcr", "RMDisableAcr", "RMEnableAcr", "RmSec2EnableApm", "RMAcrExecuteOnSec2", "RmEnableRiscvLs", "RMAcrUseCeForShadowCopy", "RmAllowPrivSecDisabled", "RmBootFromHs", "RmPmuBootstrapMode", "RMEnableAcrRiscv", "RmSwapAcrRegions") FEATURES = (0x2b, 0x3c, 0x3f, 0x4a, 0x4b) assert hashlib.sha256(ORIGINAL.read_bytes()).hexdigest() == DIGEST with ORIGINAL.open("rb") as stream: elf = ELFFile(stream) symbols = list(elf.get_section_by_name(".symtab").iter_symbols()) by_name = {symbol.name: symbol for symbol in symbols} sections = {} for name, base in ((".text", TEXT), (".rodata", RODATA), (".data", DATAS)): sections[elf.get_section_index(name)] = (base, bytearray( elf.get_section_by_name(name).data()), name) bss_index, bss_size = elf.get_section_index(".bss"), elf.get_section_by_name(".bss")["sh_size"] text_index = elf.get_section_index(".text") starts = sorted((symbol["st_value"], symbol["st_size"], symbol.name) for symbol in symbols if symbol["st_shndx"] == text_index and symbol["st_size"]) relocations = {name: [(entry["r_offset"], entry["r_info_type"], entry["r_info_sym"], entry["r_addend"]) for entry in elf.get_section_by_name(".rela" + name).iter_relocations()] for name in (".text", ".rodata", ".data")} entries = {start: name for start, size, name in starts} start_offsets = [start for start, size, name in starts] external = {} def address_of(symbol): index = symbol["st_shndx"] if index in sections: return sections[index][0] + symbol["st_value"] if index == bss_index: return BSS + symbol["st_value"] if symbol.name == "__x86_indirect_thunk_rax": return INDIRECT return external.setdefault(symbol.name, EXTERNAL + 8 * len(external)) for base, data, name in sections.values(): for offset, kind, index, addend in relocations[name]: value = address_of(symbols[index]) + addend assert len(external) < (SERVICE - EXTERNAL) // 8 if kind in (2, 4): struct.pack_into("= 0 else hex(address) def rodata(address): """Emulator address of an object at an analysis-database address.""" return RODATA + address - RODATA_ADDRESS def analysis(address): return address - RODATA + RODATA_ADDRESS def string(address): data = bytes(cpu.mem_read(address, 64)) return data[:data.index(0)].decode() def leave(emu, value): rsp = emu.reg_read(UC_X86_REG_RSP) emu.reg_write(UC_X86_REG_RSP, rsp + 8) emu.reg_write(UC_X86_REG_RAX, value & 0xffffffffffffffff) emu.reg_write(UC_X86_REG_RIP, pointer(rsp)) def hook(*names): def register(function): for name in names: hooks[text(name) if name.startswith("_nv") else name] = (name, function) return function return register def service(name): def register(function): address = SERVICE + 16 * sum(1 for key in hooks if isinstance(key, int) and key >= SERVICE) hooks[address] = (name, function) return address return register @hook("_nv053907rm") def register_read(a, low): assert (a[0], low[1], low[2]) == (GPU + 0x4120, 0, 0), a value = case["registers"][low[3]] reads.append(low[3]) return value @hook("_nv053912rm") def register_write(a, low): raise AssertionError(("no register is written", hex(low[3]), hex(low[4]))) @hook(*DIAGNOSTICS) def diagnostic(a, low): diagnostics[0] += 1 return 0 @hook("_nv049765rm") def state_assertion(a, low): return 0 @hook("_nv052687rm") def allocate(a, low): address = heap[0] heap[0] += (low[0] + 0x3f) & ~0x1f assert heap[0] < HEAP + HEAP_BYTES # Allocations are not zeroed by the service; a pattern exposes a missing fill. cpu.mem_write(address, b"\xa5" * low[0]) return address @hook("_nv052701rm", "_nv059714rm") def release(a, low): return 0 @hook("_nv052705rm") def fill(a, low): cpu.mem_write(a[0], bytes([low[1] & 0xff]) * low[2]) return a[0] @hook("_nv049786rm") def registry(a, low): """(gpu, key, &value): the status; the value only on success.""" assert a[0] == GPU key = string(a[1]) calls.append("k:" + key) if key in case["registry"]: d(a[2], case["registry"][key]) return 0 return 0x56 @hook("_nv043717rm") def descriptor_for_gpu(a, low): assert a[1] == GPU return a[0] @hook("_nv031390rm") def multi_gpu(a, low): assert a[0] == GPU return 0 @hook("_nv031478rm") def gpu_section(a, low): assert (a[0], low[1], low[2]) == (GPU, 0, 0), a return 0 @hook("_nv000333rm") def kernel_graphics(a, low): assert a[0] == GPU return KERNEL_GRAPHICS @hook("_nv017883rm", "_nv017897rm", "_nv030258rm") def bookkeeping(a, low): return 0 @hook("_nv031521rm") def sec2_construct_service(a, low): return 0 @hook("_nv003389rm") def base_constructor(a, low): return 0 @hook("_nv006784rm") def fuse_second_object(a, low): """The object _nv028936rm creates at OBJFUSE+2f8 over the aperture.""" assert (a[0], a[1], low[2], low[4]) == (FUSE + 0x2f8, FUSE, 0, 1), a return 0 @hook("_nv015308rm") def pmu_constructor_stop(a, low): """The PMU constructor body is stopped here, after its function at +330.""" calls.append("stop") return 0x40 @hook("_nv016905rm") def hs_image_preparation(a, low): assert (a[0], a[1]) == (GPU, ACR), a calls.append(f"hs:{low[2]:x}") return 0 def copy(a, low): cpu.mem_write(a[0], bytes(cpu.mem_read(a[1], low[2]))) return a[0] hooks[address_of(by_name["os_mem_copy"])] = ("os_mem_copy", copy) @service("PMU+b08 object, vtable +40") def pmu_child(a, low): assert a[0] == PMU_CHILD return 0 @service("OBJACR+130") def acr_130(a, low): assert (a[0], a[1], low[2]) == (GPU, ACR, 0), a calls.append("acr130") return case.get("acr130", 0) def hooked(emu, address, size, unused): a = [emu.reg_read(register) for register in ARGUMENTS] leave(emu, hooks[address][1](a, [value & 0xffffffff for value in a])) def unresolved(emu, address, size, unused): assert address in hooks, [name for name, value in external.items() if value == address] def block(emu, address, size, unused): if address - TEXT in entries: executed.add(entries[address - TEXT]) def install_hooks(): """One code hook per fixture address; imports without a fixture trap.""" for address in hooks: if address not in installed: installed[address] = cpu.hook_add(UC_HOOK_CODE, hooked, begin=address, end=address) def track(enabled): """Function-entry tracking costs a callback per block; it is switched on for the setup, the GV100 chain and the first case of each kind.""" if enabled and not tracking: tracking.append(cpu.hook_add(UC_HOOK_BLOCK, block)) elif not enabled and tracking: cpu.hook_del(tracking.pop()) installed, tracking = {}, [] cpu.hook_add(UC_HOOK_CODE, unresolved, begin=EXTERNAL, end=SERVICE - 1) cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, unused: emu.reg_write( UC_X86_REG_RIP, emu.reg_read(UC_X86_REG_RAX)), begin=INDIRECT, end=INDIRECT) def call(name, *arguments): for register, argument in zip(ARGUMENTS, arguments): cpu.reg_write(register, argument) rsp = STACK + 0xfff00 cpu.reg_write(UC_X86_REG_RSP, rsp) cpu.reg_write(UC_X86_REG_RBP, STACK + 0x80000) q(rsp, STOP) executed.add(name) install_hooks() cpu.emu_start(text(name), STOP, count=400000000) assert cpu.reg_read(UC_X86_REG_RIP) == STOP, name return cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff # A fixture that answers only some calls of a function and lets the others run. conditional = {} def conditional_hook(name, function): def run(emu, address, size, unused): a = [emu.reg_read(register) for register in ARGUMENTS] result = function(a, [value & 0xffffffff for value in a]) if result is not None: leave(emu, result) conditional[name] = cpu.hook_add(UC_HOOK_CODE, run, begin=text(name), end=text(name)) def conditional_remove(name): cpu.hook_del(conditional.pop(name)) # ---------------------------------------------------------------- setup case.update(registers=dict(PHYSICAL), registry={}) track(True) cpu.mem_write(CHIP + 0x10, struct.pack(" 1 else (subset,)): for mask in (0, 0x10): initialize("I", order=order, mask=mask) for order in itertools.permutations(ORDER): initialize("I", order=order) initialize("I", order=order, changes={"PMU": dict(state="zero")}) initialize("I", order=order, changes={"NVDEC": dict(state="zero")}) # ------------------------------------------------- V: the GV100 chain # ConstructEngine of OBJLSFM and OBJACR, PreInitLocked of OBJLSFM and OBJACR, # InitLocked of OBJLSFM and the query per Falcon, with no registry value and # the register words of the traced V100. begin("V", CONSTRUCTED) track(True) before = {name: falcon_state(OWNERS[name][0]) for name in ORDER} chain = [call("_nv043185rm", GPU, LSFM)] masks = [word(LSFM + 0x198)] chain.append(call("_nv016731rm", GPU, ACR)) flags_constructed = acr_flags() construct_reads = list(reads) assert construct_reads == [JTAG_REGISTER, FUSE_REGISTER] * 2, construct_reads chain.append(call("_nv043239rm", GPU, LSFM)) masks.append(word(LSFM + 0x198)) pre_init_reads = reads[len(construct_reads):] chain.append(call("_nv016961rm", GPU, ACR)) flags_pre_init = acr_flags() # OBJACR PreInitLocked reads no register before its function at +130. assert reads == construct_reads + pre_init_reads and calls[-1] == "acr130", (reads, calls) chain.append(call("_nv043236rm", GPU, LSFM)) masks.append(word(LSFM + 0x198)) registered = nodes() queries = {name: call("_nv043190rm", GPU, LSFM, word(OWNERS[name][0] + 0x608)) & 0xff for name in ORDER} identifiers = {name: word(OWNERS[name][0] + 0x608) for name in ORDER} signatures = {name: f"{analysis(pointer(OWNERS[name][0] + 0x4b0)):#x}" for name in ORDER} assert (signatures["NVDEC"], signatures["PMU"], signatures["SEC2"]) == ( "0x1147610", "0x114b138", "0x1153b68"), signatures # The signature record: 192 stored bytes, copied behind an 8-byte header at # Falcon+3f0. Falcon+608 is its dword at +72 (instance 0). records = {} for name in ORDER: falcon = OWNERS[name][0] assert call("_nv017874rm", pointer(falcon + 0x4b0)) == 192 records[name] = bytes(cpu.mem_read(pointer(falcon + 0x3f0) + 8, 192)) assert struct.unpack_from(" +200 -> +18); if that left the PMU " "Falcon unmanaged (+3a7 clear) and SEC2 exists with +513 clear and OBJACR+392 clear, " "0xffffffff is stored; otherwise _nv043182rm for every other listed Falcon.", "_nv043182rm per Falcon with +3a8 clear: the image preparation _nv028614rm; with a " "signature record (+3f0 or +3f8) and the Falcon's bit clear: Falcon+650 of 2 or 3 " "sets the bit (OBJACR+381 and OBJLSFM+190 are clear on GV100); otherwise OBJACR+392 " "set or a first instance-location entry of 2 makes it a client (a record on the list " "at +1a0, +192 incremented, Falcon+3a7 = 1); otherwise the bit is set.", "_nv043190rm(gpu, lsfm, id): bit (id & 0x1f) of OBJLSFM+198."], "setup_functions": SETUP, "executed": {kind: sorted(names) for kind, names in sorted(kinds_executed.items())}, "fixture_supplied": sorted(str(name) for name, function in hooks.values()), "chip_identification": {key: f"{value:#x}" for key, value in identity.items()}, "feature_table": {f"{feature:#x}": [f"{value:#x}" for value in pair] for feature, pair in feature_table.items()}, "vbios": {"binder": "_nv006018rm", "property_initializer": "_nv005846rm", "object_creation": "_nv006698rm", "OBJVBIOS+0x270": VBIOS_270, "executed_result": vbios_270}, "fuse": {"binder": "_nv005974rm", "slots": {f"{offset:#x}": name for offset, name in sorted(FUSE_SLOTS.items())}, "OBJFUSE+0x2f0 after the binder": 0, "jtag": JTAG_STATE, "jtag_object_creation": "_nv006537rm"}, "fuse_aperture": FUSE_APERTURE, "pmu": PMU_STATE, "pmu_owner_cast_to_class__nv003202rm": PMU_OWNER_CAST, "prepare_functions": PREPARE, "falcon_engines": {name: f"{value:#x}" for name, value in ENGINES.items()}, "instance_location_default": [2, 1, 0], "gv100_chain": { "registry": "no value for any key", "registers": {f"{offset:#x}": f"{value:#x}" for offset, value in PHYSICAL.items()}, "statuses": dict(zip(("OBJLSFM ConstructEngine", "OBJACR ConstructEngine", "OBJLSFM PreInitLocked", "OBJACR PreInitLocked", "OBJLSFM InitLocked"), chain)), "OBJLSFM+0x198": dict(zip(("after ConstructEngine", "after PreInitLocked", "after InitLocked"), (f"{mask:#x}" for mask in masks))), "OBJACR +37b +37c +381 +391": {"after ConstructEngine": flags_constructed, "after PreInitLocked": flags_pre_init}, "OBJACR ConstructEngine reads": [f"{offset:#x}" for offset in construct_reads], "OBJLSFM PreInitLocked reads": [f"{offset:#x}" for offset in pre_init_reads], "OBJACR PreInitLocked reads before +130": [], "falcons_before": before, "falcons_after": {name: falcon_state(OWNERS[name][0]) for name in ORDER}, "falcon_state_format": "+3a5 +3a7 +3a8 +3aa . +608", "falcon_ids": identifiers, "signature_records": signatures, "signature_record_sha256": {name: hashlib.sha256(record).hexdigest() for name, record in records.items()}, "clients_in_list_order": registered, "query_per_falcon": queries}, "physical_transcript": { "file": "target/trace/b3-bar0.txt", "lines_37713_37715": transcript[37712:37715], "reading": "The Jtag check and fuse word 0x21434 = 1 directly after the Graphics " "PreInitLocked tables and directly before the WPR bounds OBJACR " "PreInitLocked reads through OBJACR+130: the read of OBJLSFM PreInitLocked, " "which it makes only with OBJACR present, OBJACR+37b clear and GPU+4de4 " "clear."}, "cases": counts, "total_cases": sum(counts.values()), "oracle": "target/gpu-stage/original-lsfm-mask.txt", "oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(), "scope": "Original producers of OBJLSFM+198 on a GV100 and of the OBJACR bytes they read. " "Registry answers and register words are fixture-supplied; the Falcons are the " "five of tools/check_gpu_wpr_blob_binary.py, not the device's full list. No " "hardware executed."} (ROOT / "reports/gpu-lsfm-mask-original.json").write_text(json.dumps(report, indent=2) + "\n") print(f"{sum(counts.values())} original cases {counts}; GV100 chain masks " f"{[hex(mask) for mask in masks]}, clients {registered}, OBJVBIOS+270 {VBIOS_270} " f"-> {vbios_270}")