#!/usr/bin/env python3
"""Hook UIApplicationMain: who calls it, with which delegate class name."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
let addr = null;
try { addr = Module.getExportByName('UIKitCore', 'UIApplicationMain'); } catch (e) {}
if (!addr) { try { addr = Module.getExportByName(null, 'UIApplicationMain'); } catch (e) {} }
send({type: 'sym', addr: addr ? modOf(addr) : 'not found'});
if (addr) {
    Interceptor.attach(addr, {
        onEnter(a) {
            let s3 = '(null)';
            try { if (!a[3].isNull()) s3 = a[3].readCString(); } catch (e) { s3 = 'ERR'; }
            let s2 = '(null)';
            try { if (!a[2].isNull()) s2 = a[2].readCString(); } catch (e) { s2 = 'ERR'; }
            const bt = Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 10).map(modOf);
            send({type: 'UIApplicationMain', argc: a[0].toInt32(), principal: s2, delegate: s3, bt: bt});
        }
    });
}
"""


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(12)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
