#!/usr/bin/env python3
"""Watch UIApplicationMain (via its import stub) and the class lookups that pick the delegate."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const libobjc = Process.getModuleByName('libobjc.A.dylib');
const e = n => libobjc.getExportByName(n);
const drv = Process.getModuleByName('Driver');
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

// resolve the UIApplicationMain import stub GOT slot
const stub = drv.base.add(0x190a9d0);
const ins = [];
for (let i = 0; i < 3; i++) ins.push(stub.add(i * 4).readU32());
send({type: 'stub_words', w: ins.map(x => '0x' + x.toString(16))});
let slot = null;
try {
    const w0 = ins[0], w1 = ins[1];
    const immlo = (w0 >> 29) & 3, immhi = (w0 >> 5) & 0x7ffff;
    let imm = (immhi << 2) | immlo;
    if (imm & (1 << 20)) imm -= (1 << 21);
    const page = (0x190a9d0 & ~0xfff) + (imm << 12);
    const imm12 = ((w1 >> 10) & 0xfff) * 8;
    slot = page + imm12;
    send({type: 'slot', slot: '0x' + slot.toString(16)});
    const p = drv.base.add(slot).readPointer();
    const ds = DebugSymbol.fromAddress(p);
    send({type: 'uamain_target', ptr: p.toString(), sym: ds.name});
    Interceptor.attach(p, { onEnter(a) {
        let s3 = '(null)', s4 = '(null)';
        try { if (!a[2].isNull()) s3 = a[2].readCString(); } catch (er) {}
        try { if (!a[3].isNull()) s4 = a[3].readCString(); } catch (er) {}
        send({type: 'UIApplicationMain', principal: s3, delegate: s4});
    }});
    send({type: 'hooked_uamain'});
} catch (er) { send({type: 'uamain_err', e: String(er)}); }

// class lookups
const lookups = {};
for (const n of ['objc_getClass', 'objc_lookUpClass', 'objc_getRequiredClass']) {
    try {
        const p = e(n);
        Interceptor.attach(p, { onEnter(a) { this.nm = a[0].isNull() ? '(null)' : a[0].readCString(); },
                                onLeave(v) {
                                    if (this.nm && (this.nm.indexOf('AppDelegate') >= 0 || this.nm.indexOf('Driver') >= 0))
                                        send({type: 'getClass', fn: n, name: this.nm, ret: modOf(v)});
                                } });
        lookups[n] = true;
    } catch (er) { send({type: 'hookerr_lookup', fn: n, e: String(er)}); }
}
send({type: 'hooked_lookups', ok: Object.keys(lookups)});

// NSClassFromString
try {
    const p = Module.getExportByName('Foundation', 'NSClassFromString');
    Interceptor.attach(p, { onEnter(a) { this.s = a[0].isNull() ? '(null)' : ObjC === undefined ? a[0].readCString() : a[0].readCString(); },
                            onLeave(v) {
                                if (this.s && this.s.indexOf('ppDelegate') >= 0) send({type: 'NSClassFromString', s: this.s, ret: modOf(v)});
                            } });
    send({type: 'hooked_nscfs'});
} catch (er) { send({type: 'hookerr_nscfs', e: String(er)}); }
"""


class Watchdog:
    def __init__(self, secs=90):
        self.deadline = time.time() + secs
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while True:
            time.sleep(0.25)
            if time.time() > self.deadline:
                print('HARD TIMEOUT', flush=True)
                os._exit(3)


def main():
    Watchdog(90)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            print('kill stale', p.pid, flush=True)
            try:
                dev.kill(p.pid)
            except Exception:
                pass
    time.sleep(1.5)
    pid = dev.spawn([BID])
    print('spawned', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:900], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(14)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
