#!/usr/bin/env python3
"""Dump exported symbol names of the 3.19.0 shield binaries from LC_DYLD_INFO export trie."""
import sys, struct, zipfile

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

zp = zipfile.ZipFile(r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa')
TARGETS = ['Frameworks/build-info.framework/build-info',
           'Frameworks/bshield.framework/bshield',
           'Driver']

KEYWORDS = ['verdict', 'check', 'detect', 'shield', 'repac', 'sign', 'integ', 'tamper',
            'jail', 'hook', 'debug', 'violat', 'report', 'noti', 'engine', 'crypt', 'rezip']


def uleb(d, q):
    v = 0; shift = 0
    while True:
        b = d[q]; q += 1
        v |= (b & 0x7f) << shift
        if not (b & 0x80):
            return v, q
        shift += 7


def walk(d, q, end, prefix, out, depth=0):
    while q < end:
        ssize, q = uleb(d, q)
        if ssize == 0:
            q += 1
            continue
        nterm, q = uleb(d, q)
        name = d[q:q + ssize - nterm].decode('latin1', 'replace')
        q += ssize - nterm
        full = prefix + name
        if nterm > 0:
            # node has data: [ordinal uleb][leaf ops...]
            _, q2 = uleb(d, q)
            out.append((full, d[q:q + nterm].hex()))
            q += nterm
        else:
            walk(d, q, end, full + '/', out, depth + 1)
            return  # children consumed to end


def exports(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd in (0x26,) or cmd == 0x80000022:  # LC_FUNCTION_STARTS? no - LC_DYLD_INFO
            pass
        if cmd == 0x80000022:  # LC_DYLD_INFO
            eoff, esz = struct.unpack_from('<II', d, off + 24)  # rebase(+8+4), binds(+8+8)...
            # layout: rebase_off, rebase_size, bind_off, bind_size, weak_off, weak_size, lazy_off, lazy_size, export_off, export_size
            eoff, esz = struct.unpack_from('<II', d, off + 8 + 32)
            return d[eoff:eoff + esz]
        off += sz
    return None


def main():
    for t in TARGETS:
        d = zp.read('Payload/Driver.app/' + t)
        trie = exports(d)
        if not trie:
            print('%s: no LC_DYLD_INFO export trie' % t)
            continue
        out = []
        try:
            walk(trie, 0, len(trie), '', out)
        except Exception as e:
            print('trie walk err %s: %s' % (t, e))
        print('%s: %d exported symbols' % (t, len(out)))
        hits = [(n, h) for n, h in out if any(k in n.lower() for k in KEYWORDS)]
        print('  keyword hits: %d' % len(hits))
        for n, h in hits[:80]:
            print('    %s' % n)
        # save full list
        fn = r'E:\ios\work319\exports_' + t.split('/')[-1] + '.txt'
        with open(fn, 'w', encoding='utf-8') as f:
            for n, h in out:
                f.write('%s  %s\n' % (n, h))
        print('  full list -> %s' % fn)


if __name__ == '__main__':
    main()
