#!/usr/bin/env python3
"""Spawn-time UIKit lifecycle hooks (native objc runtime, no bridge):
AppDelegate.didFinishLaunching, configurationForConnectingSceneSession, scene delegate
willConnect, UIWindow.setRootViewController:, UIWindow.makeKeyAndVisible.
"""
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 objc_getClass = new NativeFunction(e('objc_getClass'), 'pointer', ['pointer']);
const sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const objc_msgSend = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const class_getName = new NativeFunction(e('class_getName'), 'pointer', ['pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const cname = o => o.isNull() ? '(nil)' : object_getClassName(o).readCString();
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

function hookClsMethod(clsName, selName, label) {
    const c = cls(clsName);
    if (c.isNull()) { send({type: 'miss', label: label, why: 'no class ' + clsName}); return null; }
    const m = class_getInstanceMethod(c, sel(selName));
    if (m.isNull()) { send({type: 'miss', label: label, why: 'no sel ' + selName}); return null; }
    const imp = method_getImplementation(m);
    send({type: 'imp', label: label, cls: clsName, sel: selName, imp: modOf(imp)});
    Interceptor.attach(imp, {
        onEnter(args) {
            send({type: 'enter', label: label, self: cname(args[0])});
            if (label === 'configScene') this.isSession = args[3];
        },
        onLeave(v) {
            const info = {type: 'leave', label: label, ret: modOf(v)};
            if (label === 'configScene' && this.isSession) {
                try {
                    const getScene = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
                    const sc = getScene(this.isSession, sel('scene'));
                    const dg = getScene(sc, sel('delegate'));
                    info.sceneDelegate = cname(dg);
                } catch (er) { info.sdErr = String(er); }
            }
            send(info);
        }
    });
    return imp;
}

const dl = cname(new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer'])(
    new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer'])(
        cls('UIApplication'), sel('sharedApplication')), sel('delegate')));
send({type: 'delegateClass', name: dl});

hookClsMethod(dl, 'application:didFinishLaunchingWithOptions:', 'didFinish');
hookClsMethod(dl, 'application:configurationForConnectingSceneSession:options:', 'configScene');
hookClsMethod(dl, 'application:didFinishLaunchingWithOptions:', 'didFinish2');

hookClsMethod('UIWindow', 'setRootViewController:', 'setRootVC');
hookClsMethod('UIWindow', 'makeKeyAndVisible', 'makeKey');
hookClsMethod('UIWindow', 'setHidden:', 'setHidden');

setInterval(function () { send({type: 'tick'}); }, 5000);
"""


class Watchdog:
    def __init__(self, secs=150):
        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(150)
    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)
            dev.kill(p.pid)
    time.sleep(2)
    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)[:500], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(20)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
