"""Rank candidate hash-lookup functions in a PE image (docs/modding.md, "Day one: finding the hook"). python -I tools/find_hash_lookup.py game_scarlett_master.exe [--hash player_story000_00 ...] [--window 48] [--top 15] [--json out.json] Reads the file only; nothing runs. For each --hash (a model name, hashed with joaat as the game does, or 0x...; default: Lucia's player model and cs_mandy), it finds every place the executable sections hold that 32-bit value (an immediate such as `mov ecx, 0xE472B687`) and the direct calls (E8 rel32) in the next --window bytes. Each call target is a candidate; candidates are ranked by how many of the hashes lead to them, then by how many direct calls the whole image makes to them. RAGE's archetype lookup by hash takes the hash and is called from hundreds of places, so it should rank first; pass its RVA to `gta6rt --archetype-lookup`. Standard library only. No game data is written: the report holds RVAs and counts. The report destination must not name the scanned executable, which it would truncate. """ import argparse import json import os import struct import sys from collections import Counter, defaultdict # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from report_paths import same_report_path # noqa: E402 IMAGE_SCN_MEM_EXECUTE = 0x20000000 def joaat(name): """RAGE's joaat: Jenkins one-at-a-time over the lower-cased name (joaat('cs_mandy') == 0xD7C0CDFF). Over the Latin-1 bytes, as hashdict.joaat (the pinned dictionary) does; tests/test_joaat_agreement.py checks it.""" h = 0 for c in name.lower().encode("latin-1", "replace"): h = (h + c) & 0xFFFFFFFF h = (h + (h << 10)) & 0xFFFFFFFF h ^= h >> 6 h = (h + (h << 3)) & 0xFFFFFFFF h ^= h >> 11 return (h + (h << 15)) & 0xFFFFFFFF def parse_hash(text): if text.lower().startswith("0x"): value = int(text, 16) if value > 0xFFFFFFFF: raise ValueError(f"{text} is wider than 32 bits") return value return joaat(text) def sections(data): """[(name, rva, raw offset, size, executable)] of a PE file (32- or 64-bit).""" if data[:2] != b"MZ": raise ValueError("not a PE file (no MZ header): an encrypted or packed executable can't be scanned") pe = struct.unpack_from("= 0, got {window}") if top <= 0: raise ValueError(f"top must be >= 1, got {top}") code_sections = [s for s in sections(data) if s[4]] if not code_sections: raise ValueError("no executable section") lo = min(s[1] for s in code_sections) hi = max(s[1] + s[3] for s in code_sections) all_calls = defaultdict(list) for _, rva, raw, size, _ in code_sections: for target, sites in direct_calls(data[raw:raw + size], rva).items(): if lo <= target < hi: all_calls[target].extend(sites) leads = defaultdict(set) # candidate rva -> hashes that lead to it hits = Counter() # hash -> occurrences found for name, value in hashes: needle = struct.pack("= 0: hits[name] += 1 tail = code[at + 4:at + 4 + window] j = tail.find(b"\xE8") while 0 <= j <= len(tail) - 5: rel = struct.unpack_from("12} callers {c['direct_callers']:>6} led by {', '.join(c['led_by'])}") if a.json: try: with open(a.json, "w", encoding="utf-8", newline="\n") as f: json.dump(report, f, indent=1) f.write("\n") except OSError as e: print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) return 2 return 0 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())