# -*- coding: utf-8 -*-
"""
scan_xrefs.py - tim moi tham chieu (ADRP + ADD/LDR/STR) toi cac dia chi global
trong mot Mach-O, khong can analysis.

Dung: python scan_xrefs.py <binary> <hexaddr> [hexaddr...]

Voi moi xref, in:
  - dia chi instruction
  - loai (add/ldr/str)
  - function start uoc luong (call-target gan nhat phia truoc)
  - vai instruction lan can (de doc ngu canh)
"""
import struct, sys
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM

def parse(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    segs, sections = [], []
    off = 32
    for _ in range(ncmds):
        cmd, size = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            name = d[off+8:off+24].rstrip(b'\x00').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off+24)
            segs.append((name, vmaddr, vmsize, fileoff, filesize))
            nsects, = struct.unpack_from('<I', d, off + 64)
            so = off + 72
            for _i in range(nsects):
                sname = d[so:so+16].rstrip(b'\x00').decode()
                segname = d[so+16:so+32].rstrip(b'\x00').decode()
                addr, sz = struct.unpack_from('<QQ', d, so+32)
                foff, = struct.unpack_from('<I', d, so+48)
                sections.append((segname, sname, addr, sz, foff))
                so += 80
        off += size
    return d, segs, sections

def text_span(segs, d):
    for name, vm, vs, fo, fs in segs:
        if name == '__TEXT':
            return vm, d[fo:fo+fs]
    raise SystemExit('no __TEXT')

def main():
    if len(sys.argv) < 3:
        raise SystemExit(__doc__)
    path = sys.argv[1]
    targets = [int(x, 16) for x in sys.argv[2:]]
    d, segs, sections = parse(path)
    base, text = text_span(segs, d)

    md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
    md.detail = False
    md.skipdata = True          # khong dung o byte khong decode duoc (Mach-O header...)

    # pass 1: decode tat ca instruction, thu thap call target (BL) lam moc function start
    insns = []
    for ins in md.disasm(text, base):
        insns.append((ins.address, ins.mnemonic, ins.op_str))
    call_targets = set()
    for a, mn, ops in insns:
        if mn == 'bl' and ops.startswith('#0x'):
            try:
                call_targets.add(int(ops[1:], 16))
            except ValueError:
                pass

    # pass 2: tim ADRP roi ghep voi instruction ke tiep
    hits = []
    pages = {}
    for i, (a, mn, ops) in enumerate(insns):
        if mn != 'adrp':
            continue
        # adrp xN, #0xpage
        try:
            reg, page = ops.split(',')
            reg = reg.strip()
            page = int(page.strip().lstrip('#'), 16)
        except ValueError:
            continue
        pages[(i, reg)] = page
        for t in targets:
            if page != (t & ~0xfff):
                continue
            # nhin 1 instruction ke tiep
            if i + 1 >= len(insns):
                continue
            a2, mn2, ops2 = insns[i+1]
            if mn2 in ('add', 'ldr', 'ldrsw', 'str', 'strb', 'ldrb', 'ldrh', 'strh', 'ldur', 'stur'):
                parts = [x.strip() for x in ops2.split(',')]
                # xac dinh thanh ghi base: add dung operand 2, load/store dung reg trong [...]
                if mn2 == 'add':
                    if len(parts) < 3 or parts[1] != reg:
                        continue
                    tail = parts[2]
                else:
                    import re as _re
                    mm = _re.search(r'\[(\w+)', ops2)
                    if not mm or mm.group(1) != reg:
                        continue
                    tail = ops2[ops2.rfind('#'):]
                import re
                m = re.search(r'#(0x[0-9a-f]+|-?\d+)', tail)
                if not m:
                    continue
                offv = int(m.group(1), 0)
                if (page + offv) == t:
                    hits.append((a, a2, mn2, ops2, t))

    def fstart(addr):
        best = None
        for c in call_targets:
            if c <= addr and (best is None or c > best):
                best = c
        return best

    byaddr = {a: (mn, ops) for a, mn, ops in insns}
    addrs = [a for a, _, _ in insns]
    idx = {a: i for i, a in enumerate(addrs)}

    for a, a2, mn2, ops2, t in hits:
        fs = fstart(a)
        print('target=0x%x  insn=0x%x  %s %s   func~0x%x' % (t, a2, mn2, ops2, fs if fs else 0))
        i = idx.get(a2)
        if i is not None:
            for j in range(max(0, i-3), min(len(insns), i+4)):
                aa, mm, oo = insns[j]
                mark = '>>' if aa == a2 else '  '
                print('   %s 0x%x  %-8s %s' % (mark, aa, mm, oo))
        print()

if __name__ == '__main__':
    main()
