#!/usr/bin/env python3
"""Resolve plugin stubs via LC_DYLD_CHAINED_FIXUPS (plugin uses chained fixups)."""
import struct, sys
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
P = r'patch_src\Payload\Driver.app\Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback'
d = open(P, 'rb').read()
base = 0x100000000

ncmds = struct.unpack_from('<I', d, 16)[0]
off = 32
fix = None
segs = []
for _ in range(ncmds):
    cmd, size = struct.unpack_from('<II', d, off)
    if cmd == 0x80000034:
        fix = struct.unpack_from('<II', d, off + 8)
    if cmd == 0x19:
        n = struct.unpack_from('<I', d, off + 64)[0]
        so = off + 72
        for _s in range(n):
            sn = d[so:so + 16].split(b'\0')[0].decode()
            addr = struct.unpack_from('<Q', d, so + 32)[0]
            fsz = struct.unpack_from('<Q', d, so + 40)[0]
            foff = struct.unpack_from('<I', d, so + 48)[0]
            segs.append((sn, addr, fsz, foff))
            so += 80
    off += size
print('chained fixups:', fix)
fo, fs = fix
imgoff, starts, imports_off, symbols_off, imports_count, imports_format, symbols_format = struct.unpack_from('<7I', d, fo)
names = []
for i in range(imports_count):
    v = struct.unpack_from('<I', d, fo + imports_off + i * 4)[0]
    noff = (v >> 9) & 0xFFFF
    names.append(d[fo + symbols_off + noff:].split(b'\0')[0].decode('latin1'))
print('imports:', imports_count)

# build bind map: walk fixup chains per segment
binds = {}
for si, (sn, va, fsz, foff) in enumerate(segs):
    if fsz == 0:
        continue
print('segments:', [(s[0], hex(s[1]), hex(s[3])) for s in segs])
# pointer format from starts header
img = fo + starts
seg_count = struct.unpack_from('<I', d, img)[0]
for si in range(seg_count):
    seg_off = struct.unpack_from('<I', d, img + 4 + si * 4)[0]
    if seg_off == 0 or seg_off >= len(d):
        print('  seg %d empty' % si)
        continue
    ssize, page_size, ptr_fmt, sego, max_valid = struct.unpack_from('<IHHQI', d, img + seg_off)
    page_count = d[img + seg_off + 20]
    print('  seg %d fmt %d pages %d' % (si, ptr_fmt, page_count))
    p = img + seg_off
    page_starts = [struct.unpack_from('<H', d, p + 21 + i * 2)[0] for i in range(page_count)]
    foff = sego
    for pi, ps in enumerate(page_starts):
        if ps == 0xFFFF:
            continue
        cur = foff + pi * page_size + ps
        while cur + 8 <= len(d) and cur < foff + fsz:
            raw = struct.unpack_from('<Q', d, cur)[0]
            nxt = (raw >> 51) & 0x7FF
            is_bind = (raw >> 62) & 1
            if is_bind:
                ordi = raw & 0xFFFFF
                if ordi < len(names):
                    binds[base + cur] = names[ordi]
            else:
                tgt = raw & 0xFFFFFFFFF
                binds[base + cur] = 'rebase:%#x' % tgt
            if nxt == 0:
                break
            cur += nxt * 4
print('resolved slots:', len(binds))

# resolve stubs of interest
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
for stub in (0x8cac, 0x8dc0, 0x8b08, 0x8d30, 0x8e00, 0x8f00, 0x8f20, 0x8f40):
    ins = list(md.disasm(d[stub:stub + 12], base + stub))
    lp = None
    if len(ins) >= 2 and ins[0].mnemonic == 'adrp' and ins[1].mnemonic == 'ldr':
        lp = ins[0].operands[1].imm + ins[1].operands[1].mem.disp
    nm = binds.get(lp, '?')
    # for rebase slots pointing into __objc_methname? decode classref target
    extra = ''
    if nm.startswith('rebase:'):
        tv = int(nm.split(':')[1], 16)
        o = tv - base
        if 0 <= o < len(d):
            s = d[o:o + 40].split(b'\0')[0]
            extra = ' -> ' + s[:30].decode('latin1')
    print('stub %#x -> %#x %s%s' % (stub, lp or 0, nm, extra))
