import lief, re
import capstone as C

DYLIB = r"E:\ios\zeplao_unpack\data\Library\MobileSubstrate\DynamicLibraries\ZaloXposediOS.dylib"
b = lief.MachO.parse(DYLIB).at(0)

# 1. Map stub (start addr) -> import symbol name via chained fixups on got entries
stub_info = {}
try:
    cf = b.dyld_chained_fixups
    print("chained fixups:", cf)
except Exception as e:
    print("cf err", e)

# Instead: disassemble each 12-byte stub in __stubs to find its GOT address
sec_stubs = b.get_section("__TEXT__", "__stubs") if False else None
for sec in b.sections:
    if sec.name.strip() == "__stubs":
        sec_stubs = sec
print("stubs sec:", sec_stubs.name if sec_stubs else None)

md = C.Cs(C.CS_ARCH_ARM64, C.CS_MODE_LITTLE_ENDIAN)

stub_got = {}  # stub start -> got VA
if sec_stubs:
    sd = bytes(sec_stubs.content)
    sva = sec_stubs.virtual_address
    for i in range(0, len(sd), 12):
        ins = list(md.disasm(sd[i:i+12], sva+i))
        page = None
        off = 0
        got = None
        for ins2 in ins:
            if ins2.mnemonic == "adrp" and "x17" in ins2.op_str:
                m = re.findall(r"0x[0-9a-f]+", ins2.op_str)
                if m: page = int(m[0], 16)
            elif ins2.mnemonic == "ldr" and page is not None and ins2.op_str.startswith("x17"):
                m = re.findall(r"-?0x[0-9a-f]+", ins2.op_str)
                if m:
                    off = int(m[0], 16)
                got = page + off
        stub_got[sva+i] = got

print("stub count", len(stub_got))

# Map got addr -> symbol via chained fixups
got2sym = {}
# lief relocation list (it may decode chained fixups into relocations)
for rel in b.relocations:
    try:
        s = rel.symbol.name
        got2sym[rel.address] = s
    except Exception:
        pass
print("relocs:", len(got2sym))

stub_sym = {}
for addr, got in stub_got.items():
    if got and got in got2sym:
        stub_sym[addr] = got2sym[got]
print("resolved stubs:", len(stub_sym))
print("target stubs:", [(hex(a), s) for a, s in stub_sym.items() if "NSSearch" in s or "NSHome" in s])
