#!/usr/bin/env python3
"""Properly walk __objc_methlist in the Driver: resolve every method's selref and
find whether setIdleTimerDisabled: is DEFINED (category) rather than just called."""
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 = ['Driver',
           'Frameworks/build-info.framework/build-info',
           'Frameworks/bshield.framework/bshield',
           'Frameworks/flutter_bshield_callback.framework/flutter_bshield_callback']

SEL_VMS = {
    'Driver': [0x101f7c5e0],  # setIdleTimerDisabled: selref (known)
}
INTERESTING = ('setIdleTimerDisabled', 'sharedApplication', 'appearance', 'setExclusiveTouch')


def sections(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    out = []
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            nsects, = struct.unpack_from('<I', d, off + 64)
            so = off + 72
            for i in range(nsects):
                sn = d[so:so + 16].rstrip(b'\0').decode(errors='replace')
                sg = d[so + 16:so + 32].rstrip(b'\0').decode(errors='replace')
                addr, asz, foff = struct.unpack_from('<QQI', d, so + 32)
                out.append((sg, sn, addr, asz, foff))
                so += 80
        off += sz
    return out


def main():
    for t in TARGETS:
        d = zp.read('Payload/Driver.app/' + t)
        BASE = 0x100000000
        secs = sections(d)

        # selref slots: map slot_vm -> selector string (read pointer, read string)
        selref = {}
        for sg, sn, addr, asz, foff in secs:
            if sn == '__objc_selrefs':
                for i in range(0, asz, 8):
                    raw, = struct.unpack_from('<Q', d, foff + i)
                    if 0x100000000 <= raw < 0x102000000:
                        fo = raw - BASE
                        if 0 <= fo < len(d):
                            e = d.find(b'\0', fo)
                            if e > fo and e - fo < 200:
                                selref[addr + i] = d[fo:e].decode('latin1', 'replace')

        # methlist slots: map slot_vm -> selector string
        methref = {}
        for sg, sn, addr, asz, foff in secs:
            if sn == '__objc_methname':
                pass  # strings live here; already covered via pointers

        # pointers from __objc_methlist entries: relative method lists point at SELREF slots
        # find selref slots for our interesting selectors
        interesting_slots = {}
        for slot, s in selref.items():
            if any(k in s for k in INTERESTING):
                interesting_slots[slot] = s
        print('== %s ==  (%d selrefs, %d interesting)' % (t, len(selref), len(interesting_slots)))

        # brute-force: scan __objc_methlist sections for (entry + int32) == interesting slot
        for sg, sn, addr, asz, foff in secs:
            if sn != '__objc_methlist':
                continue
            found = []
            for p in range(8, asz - 4, 4):
                v, = struct.unpack_from('<i', d, foff + p)
                if v == 0 or abs(v) > 0x800000:
                    continue
                slot = addr + p + v
                if slot in interesting_slots:
                    found.append((addr + p, slot, interesting_slots[slot]))
            for entry, slot, s in found:
                print('  %s,%s: method entry 0x%09x -> selref 0x%09x  sel=%r' % (sg, sn, entry, slot, s))
        print()


if __name__ == '__main__':
    main()
