#!/usr/bin/env python3
"""Resolve the stubs and GOT/data loads around the build-55 abort path."""
import sys
import struct
import capstone
import lief

sys.stdout.reconfigure(encoding='utf-8')

DRV = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
d = open(DRV, 'rb').read()
b = lief.parse(DRV)

# map binding address -> (symbol, library)
binds = {}
for e in b.bindings:
    try:
        a = e.address
        sym = e.symbol.name if e.symbol else ''
        lib = ''
        try:
            lib = e.library.name if e.library else ''
        except Exception:
            pass
        binds[a] = (sym, lib)
    except Exception:
        pass
print('bindings parsed: %d' % len(binds))

md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_LITTLE_ENDIAN)

STUBS = [0x190bbc4, 0x190bd14, 0x190bd20, 0x190bd2c, 0x190bd50, 0x190c6b0,
         0x19379c0, 0x193cbc0, 0x1938240, 0x192a620]

print('\n== stub resolution ==')
for s in STUBS:
    # stub: adrp x16, page ; ldr x16, [x16, #off] ; br x16  (or ldr x16, [x16, off]; ...)
    page = None
    off = None
    for insn in md.disasm(d[s:s + 16], s):
        if insn.mnemonic == 'adrp' and insn.op_str.startswith('x16'):
            # imm in op_str like "x16, #0x1d9c000"
            try:
                page = int(insn.op_str.split(',')[1].strip().lstrip('#'), 0)
            except Exception:
                page = (s & ~0xFFF) + int(insn.op_str.split(',')[1].strip().lstrip('#'), 0)
        elif insn.mnemonic == 'ldr' and insn.op_str.startswith('x16'):
            m = insn.op_str.split('#')
            if len(m) > 1:
                off = int(m[1].rstrip(']').strip(), 0)
            break
    if page is None or off is None:
        print('  0x%08x  UNRESOLVED (page=%s off=%s)' % (s, page, off))
        continue
    got = page + off
    sym, lib = binds.get(got, ('?', '?'))
    print('  0x%08x -> GOT 0x%09x  %s  (%s)' % (s, got, sym, lib))

print('\n== data loads (x8 = adrp 0x1f84000 / 0x1d9b000) ==')
DATA_LOADS = [0x1f84330, 0x1f84338, 0x1f84340, 0x1f84348, 0x1d9bd20, 0x1d9bd28]
for a in DATA_LOADS:
    fo = a - 0x100000000
    if 0 <= fo < len(d) - 8:
        raw = struct.unpack_from('<Q', d, fo)[0]
    else:
        raw = None
    sym, lib = binds.get(a, ('?', '?'))
    print('  0x%09x  bind=%-42s lib=%-28s raw=0x%x' % (a, sym, lib, raw if raw is not None else 0))

# what section are these in?
print('\n== sections containing the data loads ==')
for e in b.sections:
    if e.virtual_address <= 0x1f84348 < e.virtual_address + e.size:
        print('  0x1f84330-348 in section %s (seg %s)' % (e.name, e.segment.name))
    if e.virtual_address <= 0x1d9bd28 < e.virtual_address + e.size:
        print('  0x1d9bd20-d28 in section %s (seg %s)' % (e.name, e.segment.name))

# also: which function contains 0x328e0? dump export trie name lookup via lief symbols near it
print('\n== any exported/static symbol near 0x328e0 / 0x31f8c ==')
cands = []
for s in b.symbols:
    try:
        v = s.value
    except Exception:
        continue
    if v and (abs(v - 0x10328e0) < 0x4000 or abs(v - 0x1031f8c) < 0x4000):
        cands.append((v, s.name))
for v, n in sorted(cands)[-30:]:
    print('  0x%09x  %s' % (v, n))
