#!/usr/bin/env python3
# methlist.py - resolve ObjC relative method lists that reference selref slots
import struct, json, sys
sys.path.insert(0, "analysis")
from xref_macho import Bin, decode_ptr

def main(scan_path, bin_path, targets_file):
    scan = json.load(open(scan_path, encoding="utf-8"))
    b = Bin(bin_path, scan)
    ns = {}
    exec(open(targets_file, encoding="utf-8").read(), ns)
    targets = ns["TARGETS"]
    tset = set(targets)
    # find selref slots pointing at target strings
    slots = {}
    for s in b.segs:
        for c in s["sects"]:
            if "selref" not in c["name"]:
                continue
            for o in range(0, c["size"] - 7, 8):
                v = struct.unpack_from("<Q", b.data, c["offset"] + o)[0]
                if v in tset:
                    slots[c["addr"] + o] = targets[v]
    print(f"selref slots: { {hex(k): v for k, v in slots.items()} }")
    if not slots:
        return
    # relative method lists: entries of 3x int32 (name, types, imp) relative to field address
    for s in b.segs:
        for c in s["sects"]:
            if "methlist" not in c["name"] and c["name"] != "__objc_methlist":
                continue
            base_off, size, addr = c["offset"], c["size"], c["addr"]
            n_fields = size // 4
            for fi in range(n_fields):
                fo = base_off + fi * 4
                val = struct.unpack_from("<i", b.data, fo)[0]
                fva = addr + fi * 4
                tgt = fva + val
                if tgt in slots:
                    print(f"  methlist ref: field @{fva:#x} -> slot {tgt:#x} ('{slots[tgt]}') "
                          f"in methlist section range {addr:#x}-{addr+size:#x} (entry ~{fva - (fva % 12):#x})")

if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2], sys.argv[3])
