#!/usr/bin/env python3 """Run the original GV100 KernelMc Init and Load bodies and write an oracle. Executed original code: _nv041564rm then _nv041565rm on the same object. The registry read, the callback registration and the three GPU table calls (bus type, configuration read and write) are fixture-supplied. """ import hashlib import itertools import json from pathlib import Path import struct from elftools.elf.elffile import ELFFile from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc from unicorn.x86_const import (UC_X86_REG_RAX, 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, UC_X86_REG_R8, UC_X86_REG_R9) ROOT = Path(__file__).resolve().parents[1] ORIGINAL = Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary") DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b" TEXT, RODATA, DATA, STACK, STOP = 0x10000000, 0x20000000, 0x30000000, 0x40000000, 0x50000000 GPU, KMC, CHILD = DATA, DATA + 0x8000, DATA + 0x9000 INDIRECT, BUS, READ, WRITE = STOP + 0x100, STOP + 0x200, STOP + 0x300, STOP + 0x400 EXECUTED = ("_nv041564rm", "_nv041565rm") HOOKED = ("_nv049786rm", "_nv046906rm") 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} text = bytearray(elf.get_section_by_name(".text").data()) rodata = elf.get_section_by_name(".rodata").data() text_section, rodata_section = (elf.get_section_index(name) for name in (".text", ".rodata")) ranges = [(by_name[name]["st_value"], by_name[name]["st_size"]) for name in EXECUTED] for relocation in elf.get_section_by_name(".rela.text").iter_relocations(): offset = relocation["r_offset"] if not any(start <= offset < start + size for start, size in ranges): continue kind, target = relocation["r_info_type"], symbols[relocation["r_info_sym"]] if target.name == "__x86_indirect_thunk_rax": address = INDIRECT elif target["st_shndx"] == rodata_section: address = RODATA + target["st_value"] else: assert target["st_shndx"] == text_section, target.name address = TEXT + target["st_value"] value = address + relocation["r_addend"] if kind in (2, 4): value -= TEXT + offset else: assert kind == 11, kind struct.pack_into("