# -*- coding: utf-8 -*-
"""Verify user's offset table against build-info / flutter_bshield_callback binaries.
Parses Mach-O symtab + objc metadata, maps given offsets -> nearest symbol/method."""
import struct, sys, os

PAY = r'E:\ios\dump_tool\out\Payload\Driver.app\Frameworks'

def parse(path):
    d = open(path, 'rb').read()
    magic = struct.unpack_from('<I', d, 0)[0]
    if magic == 0xBEBAFECA:  # fat
        n = struct.unpack_from('>I', d, 4)[0]
        for i in range(n):
            cpu, sub, off, size, align = struct.unpack_from('>IIIII', d, 8 + i*20)
            if cpu == 0x0100000C:  # arm64
                d = d[off:off+size]
                break
    magic = struct.unpack_from('<I', d, 0)[0]
    swap = magic in (0xFEEDFACF, )  # little
    ncmds = struct.unpack_from('<I', d, 16)[0]
    pos = 32
    symtab = None; segs = []
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, pos)
        if cmd == 2:
            symtab = struct.unpack_from('<IIII', d, pos+8)
        elif cmd == 0x19:  # LC_SEGMENT_64
            segname = d[pos+8:pos+24].rstrip(b'\0').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, pos+24)
            segs.append((segname, vmaddr, fileoff))
        pos += sz
    return d, symtab, segs

def symbols(d, symtab):
    symoff, nsyms, stroff, strsize = symtab
    out = []
    for i in range(nsyms):
        n_strx, n_type, n_sect, n_desc, n_value = struct.unpack_from('<IBBHQ', d, symoff + i*16)
        end = d.find(b'\0', stroff + n_strx)
        name = d[stroff + n_strx:end].decode('ascii', 'ignore')
        out.append((n_value, name))
    return out

def nearest(syms, off, maxn=3):
    cands = [(abs(v - off), v, n) for v, n in syms if v and 0 <= off - v < 0x10000]
    cands.sort()
    return [(hex(v), n) for _, v, n in cands[:maxn]]

bi_d, bi_st, bi_segs = parse(os.path.join(PAY, 'build-info.framework', 'build-info'))
bi_syms = symbols(bi_d, bi_st) if bi_st else []
print('build-info: %d symbols, segments: %s' % (len(bi_syms), [(s, hex(v)) for s, v, o in bi_segs]))

checks_bi = {
    'ShieldData +getDetectFlags 0x6364': 0x6364,
    'ShieldData +initialize 0x4680': 0x4680,
    'singleton accessor 0x297ec': 0x297ec,
    'table lookup 0x18d70': 0x18d70,
    'ShieldData +get 0x4174': 0x4174,
    'ShieldAPI +getShieldCode 0x7970': 0x7970,
    'ShieldAPI +generateSignature 0xaab0': 0xaab0,
    'ShieldAPI +encryptRequest 0x5abc': 0x5abc,
}
for label, off in checks_bi.items():
    n = nearest(bi_syms, off)
    print('%-40s -> %s' % (label, n if n else 'NO symbol nearby'))

fc_d, fc_st, fc_segs = parse(os.path.join(PAY, 'flutter_bshield_callback.framework', 'flutter_bshield_callback'))
fc_syms = symbols(fc_d, fc_st) if fc_st else []
print('\nflutter_bshield_callback: %d symbols' % len(fc_syms))
for label, off in (('onBShieldOSProtectionStatusChanged 0x4598', 0x4598), ('dispatcher 0x661c', 0x661c)):
    n = nearest(fc_syms, off)
    print('%-44s -> %s' % (label, n if n else 'NO symbol nearby'))
