import lief, struct, re

DYLIB = r"E:\ios\zeplao_unpack\data\Library\MobileSubstrate\DynamicLibraries\ZaloXposediOS.dylib"
binary = lief.MachO.parse(DYLIB).at(0)
ctx = binary
segs = {}
text = None
for seg in ctx.segments:
    if seg.name == "__TEXT":
        text = seg

# collect sections
sections = {}
for seg in ctx.segments:
    for sec in seg.sections:
        name = sec.segment_name.rstrip('\0') + "/" + sec.name.rstrip('\0')
        sections[name] = (sec.virtual_address, bytes(sec.content))

data = sections.get("__TEXT/__text", (None, None))
va_text, code = data
print("text VA", hex(va_text), "size", len(code))

# Build symbol map
symtab = {}
for sym in ctx.symbols:
    if sym.value:
        symtab[sym.value] = sym.name

# imports: find NSSearchPathForDirectoriesInDomains
targets = []
for sym in ctx.symbols:
    n = sym.name
    if any(k in n for k in ("NSSearchPath", "NSHomeDirectory")):
        targets.append((n, sym.value))
print("symbols:")
for n, v in targets:
    print(" ", n, hex(v))

# disassemble and resolve calls via symbol stubs
capstone = __import__("capstone")
import capstone.arm64 as arm64
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_LITTLE_ENDIAN)
md.detail = True

# Find stub helpers that jump to the import, by scanning __TEXT/__stubs
stub_section = None
for name, (va, d) in sections.items():
    if "__stubs" in name:
        stub_section = (name, va, d)
if stub_section:
    name, sva, sd = stub_section
    for i in range(0, len(sd), 12):
        instr_off = sva + i
        # each stub: adrp x16, ADD x16, br x16 or 12-byte pattern
        stub_bytes = sd[i:i+12]
        ins = list(md.disasm(stub_bytes, instr_off))
        if len(ins) >= 3:
            # try resolve: for ARM64 stubs, ldr x17 from __got
            pass

# Simpler: disassemble all text, track 'b' to stubs is hard; instead search for
# reference to the GOT entry of NSSearchPathForDirectoriesInDomains.
got_map = {}
for seg in ctx.segments:
    if seg.name == "__DATA_CONST":
        for sec in seg.sections:
            if "__got" in sec.name or "__auth_got" in sec.name:
                base = sec.virtual_address
                d = bytes(sec.content)
                for i in range(0, len(d), 8):
                    for sym in ctx.symbols:
                        pass

# lief: get got entries via relocations
got_target = None
for rel in ctx.relocations:
    s = rel.symbol.name if rel.has_symbol else ""
    if "NSSearchPath" in s:
        got_target = rel.address
        print("GOT relocation for", s, "at", hex(rel.address))
print("got_target", got_target)

# Now disassemble text and find adrp/add pairs computing got_target, then the
# bl to that stub, and print surrounding instructions.
md.detail
insns = list(md.disasm(code, va_text))
print("insn count", len(insns))

# map stub address that loads got_target: scan __stubs for pattern 'nop; adrp x17..; ldr x17..'
stub_hits = {}
if stub_section:
    name, sva, sd = stub_section
    ins_list = list(md.disasm(sd, sva))
    for idx, ins in enumerate(ins_list):
        if ins.id == arm64.ARM64_LDR and ins.op_str.startswith("x17, [x"):
            # previous adrp
            for j in range(max(0, idx-3), idx):
                prev = ins_list[j]
                if prev.id == arm64.ARM64_ADRP and "x17" in prev.op_str:
                    # compute target of ldr: adrp page + imm
                    page = (prev.address & ~0xFFF)
                    import re
                    m = re.findall(r"-?0x[0-9a-f]+", ins.op_str)
                    if m:
                        off = int(m[0], 16)
                        addr = page + off
                        if addr == got_target:
                            stub_hits[prev.address] = None
    # stubs typically 3 insns each from stub start
    for i in range(0, len(sd), 12):
        bl = list(md.disasm(sd[i:i+12], sva+i))
        stub_addr = None
        for ins in bl:
            m = re.findall(r"-?0x[0-9a-f]+", ins.op_str)
            if ins.id == arm64.ARM64_LDR and m:
                # ldr x17, [x17, #imm]
                pass
    # simpler brute-force: page-align scan for hits above then map to stub start (address & ~3)
    for a in list(stub_hits):
        sa = a & ~0xF
        stub_hits[sa] = True
    print("stub starts loading NSSearchPath GOT:", [hex(k) for k in stub_hits])

# Now find bl to those stubs in text and print context
stub_starts = set(stub_hits.keys())
def compute_adrp(ins, idx, insns_list, reg):
    # returns computed target if possible using next added add/ldr imm
    return None

for idx, ins in enumerate(insns):
    if ins.id == arm64.ARM64_BL:
        tgt = int(ins.op_str.replace('#', '0x'), 16) if 'x' in ins.op_str else None
        if tgt in stub_starts:
            print("\n=== BL to NSSearchPath stub at", hex(ins.address), "===")
            for k in range(max(0, idx-25), min(len(insns), idx+25)):
                i2 = insns[k]
                mark = ">>" if k == idx else "  "
                print(mark, hex(i2.address), i2.mnemonic, i2.op_str)
