#!/usr/bin/env python3
"""Full lifecycle trace: discover app delegate via UIApplication.setDelegate:, hook
didFinishLaunching/configScene, discover scene delegate from the returned session, hook
willConnect, and hook FlutterEngine/FlutterViewController start points."""
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 object_getClassName = new NativeFunction(e('object_getClassName'), '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'}); return false; }
    const m = class_getInstanceMethod(c, sel(selName));
    if (m.isNull()) { send({type: 'miss', label: label, why: 'no sel on ' + clsName}); return false; }
    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});
            if (label === 'configScene') this.sess = args[3];
        },
        onLeave(v) {
            const info = {type: 'leave', label: label, ret: modOf(v)};
            if (label === 'configScene' && this.sess) {
                try {
                    const g = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
                    const sc = g(this.sess, sel('scene'));
                    const dg = g(sc, sel('delegate'));
                    info.sceneDelegate = cname(dg);
                    if (!dg.isNull()) {
                        // hook the scene delegate lifecycle right now, before willConnect runs
                        for (const [s2, l2] of [['scene:willConnectToSession:options:', 'willConnect'],
                                                ['sceneWillEnterForeground:', 'willEnter'],
                                                ['sceneDidBecomeActive:', 'didActive']]) {
                            const mm = class_getInstanceMethod(object_getClassName(dg) === '' ? ptr(0) : cls(cname(dg)), sel(s2));
                            if (!mm.isNull()) {
                                const i2 = method_getImplementation(mm);
                                send({type: 'imp', label: l2, cls: cname(dg), sel: s2, imp: modOf(i2)});
                                Interceptor.attach(i2, {
                                    onEnter(a2) { send({type: 'enter', label: l2, winArg: cname(a2[2])}); },
                                    onLeave(v2) { send({type: 'leave', label: l2, ret: modOf(v2)}); }
                                });
                            } else {
                                send({type: 'miss', label: l2, why: 'no sel on ' + cname(dg)});
                            }
                        }
                    }
                } catch (er) { info.sdErr = String(er); }
            }
            send(info);
        }
    });
    return true;
}

// 1) discover app delegate when UIApplication installs it
{
    const m = class_getInstanceMethod(cls('UIApplication'), sel('setDelegate:'));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        send({type: 'imp', label: 'setDelegate', cls: 'UIApplication', imp: modOf(imp)});
        Interceptor.attach(imp, {
            onEnter(args) {
                const dn = cname(args[2]);
                send({type: 'delegateSet', cls: dn});
                if (dn !== '(nil)') {
                    hookClsMethod(dn, 'application:didFinishLaunchingWithOptions:', 'didFinish');
                    hookClsMethod(dn, 'application:configurationForConnectingSceneSession:options:', 'configScene');
                    hookClsMethod(dn, 'application:performFetchWithCompletionHandler:', 'performFetch');
                }
            }
        });
    } else { send({type: 'miss', label: 'setDelegate', why: 'no sel'}); }
}

// 2) window wiring evidence
for (const [s2, l2] of [['setRootViewController:', 'setRootVC'], ['makeKeyAndVisible', 'makeKey'],
                        ['setHidden:', 'setHidden']]) {
    const m = class_getInstanceMethod(cls('UIWindow'), sel(s2));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        send({type: 'imp', label: l2, cls: 'UIWindow', sel: s2, imp: modOf(imp)});
        Interceptor.attach(imp, {
            onEnter(args) {
                send({type: 'enter', label: l2, arg: cname(args[2])});
            }
        });
    }
}

// 3) Flutter start points (Flutter framework may load lazily -> retry)
let flutterHooked = false;
const tryFlutter = () => {
    if (flutterHooked) return;
    const fe = cls('FlutterEngine');
    if (fe.isNull()) return;
    flutterHooked = true;
    for (const [s2, l2] of [['runWithEntrypoint:', 'fe_run'], ['runWithEntrypoint:initialRoute:', 'fe_run2'],
                            ['run', 'fe_run0']]) {
        const m = class_getInstanceMethod(fe, sel(s2));
        if (!m.isNull()) {
            const imp = method_getImplementation(m);
            send({type: 'imp', label: l2, cls: 'FlutterEngine', sel: s2, imp: modOf(imp)});
            Interceptor.attach(imp, { onEnter() { send({type: 'enter', label: l2}); } });
        }
    }
    const fvc = cls('FlutterViewController');
    if (!fvc.isNull()) {
        for (const [s2, l2] of [['initWithEngine:nibName:bundle:', 'fvc_init'],
                                ['initWithProject:', 'fvc_init2']]) {
            const m = class_getInstanceMethod(fvc, sel(s2));
            if (!m.isNull()) {
                const imp = method_getImplementation(m);
                send({type: 'imp', label: l2, cls: 'FlutterViewController', sel: s2, imp: modOf(imp)});
                Interceptor.attach(imp, { onEnter() { send({type: 'enter', label: l2}); } });
            }
        }
    }
    send({type: 'flutter', hooked: true});
};
const t = setInterval(tryFlutter, 500);
setTimeout(() => clearInterval(t), 20000);
"""


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(22)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
