#!/usr/bin/env python3
"""Experiment 4:
  (a) shield's scene-config -> nil  (UIKit falls back to Info.plist -> Driver.SceneDelegate)
  (b) also invoke the real Driver.AppDelegate -application:didFinishLaunchingWithOptions:
      right after the shield's didFinishLaunching returns.
Watch Flutter engine/VC creation and the live UI state.
"""
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 class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const method_setImplementation = new NativeFunction(e('method_setImplementation'), 'pointer', ['pointer', 'pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
const m0 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const m1 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'pointer']);
const m2 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'pointer', 'pointer']);

// (a) scene config -> nil
const shield = cls('Function_UmcOPEDGyT');
const mCfg = class_getInstanceMethod(shield, sel('application:configurationForConnectingSceneSession:options:'));
method_setImplementation(mCfg, new NativeCallback(function () { send({type: 'cfg_nil'}); return ptr(0); },
    'pointer', ['pointer', 'pointer', 'pointer', 'pointer', 'pointer']));
send({type: 'cfg_swizzled', imp: modOf(method_getImplementation(mCfg))});

// real app delegate class + its didFinishLaunching
const realCls = cls('Driver.AppDelegate');
const mDFL = class_getInstanceMethod(realCls, sel('application:didFinishLaunchingWithOptions:'));
send({type: 'realCls', ok: !realCls.isNull(), dfl: mDFL.isNull() ? 'nil' : modOf(method_getImplementation(mDFL))});

// (b) call it once the shield's didFinishLaunching returns
const bi = Process.getModuleByName('build-info');
const shieldDFL = bi.base.add(0x28feb8);
let fired = false;
Interceptor.attach(shieldDFL, {
    onLeave(ret) {
        if (fired) return;
        fired = true;
        send({type: 'shield_dfl_returned', ret: ret.toInt32()});
        try {
            const inst = m0(m0(realCls, sel('alloc')), sel('init'));
            send({type: 'real_inst', cls: object_getClassName(inst).readCString()});
            const app = m0(cls('UIApplication'), sel('sharedApplication'));
            const r = m1(inst, sel('application:didFinishLaunchingWithOptions:'), app, ptr(0));
            send({type: 'real_dfl_called', ret: r.toString()});
        } catch (er) { send({type: 'real_dfl_err', e: String(er)}); }
    }
});
send({type: 'hooked_shield_dfl', at: modOf(shieldDFL)});

// real scene delegate
try {
    const mSD = class_getInstanceMethod(cls('Driver.SceneDelegate'), sel('scene:willConnectToSession:options:'));
    Interceptor.attach(method_getImplementation(mSD), { onEnter() { send({type: 'REAL_SD_willConnect'}); } });
    send({type: 'hooked_sd'});
} catch (er) { send({type: 'hookerr_sd', e: String(er)}); }
try {
    Interceptor.attach(Process.getModuleByName('Driver').base.add(0x3271c),
        { onEnter() { send({type: 'REAL_SCENE_FN'}); } });
    send({type: 'hooked_scene_fn'});
} catch (er) { send({type: 'hookerr_scene_fn', e: String(er)}); }

// Flutter
const hooked = {};
const tryHook = (cname, sname, label) => {
    const k = cname + '|' + sname;
    if (hooked[k]) return;
    const c = cls(cname); if (c.isNull()) return;
    const m = class_getInstanceMethod(c, sel(sname)); if (m.isNull()) return;
    hooked[k] = true;
    try {
        Interceptor.attach(method_getImplementation(m), { onEnter() { send({type: 'HIT', label: label}); } });
        send({type: 'hooked', label: label, imp: modOf(method_getImplementation(m))});
    } catch (er) { send({type: 'hookerr', label: label, e: String(er)}); }
};
const poll = () => {
    tryHook('FlutterEngine', 'run', 'fe_run');
    tryHook('FlutterEngine', 'runWithEntrypoint:', 'fe_run1');
    tryHook('FlutterViewController', 'initWithEngine:nibName:bundle:', 'fvc_initEngine');
    tryHook('FlutterViewController', 'viewDidLoad', 'fvc_viewDidLoad');
};
const iv = setInterval(poll, 300);
setTimeout(() => clearInterval(iv), 20000);
poll();

setTimeout(function () {
    try {
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const dg = m0(app, sel('delegate'));
        const scenes = m0(app, sel('connectedScenes'));
        const anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
        const sc = anyF(scenes, sel('anyObject'), 0);
        const sdg = sc.isNull() ? ptr(0) : m0(sc, sel('delegate'));
        let win = ptr(0), rvc = ptr(0);
        if (!sdg.isNull()) {
            win = m0(sdg, sel('window'));
            if (!win.isNull()) rvc = m0(win, sel('rootViewController'));
        }
        send({type: 'state',
              appDelegate: dg.isNull() ? 'nil' : object_getClassName(dg).readCString(),
              sceneDelegate: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString(),
              window: win.isNull() ? 'nil' : object_getClassName(win).readCString(),
              rootVC: rvc.isNull() ? 'nil' : object_getClassName(rvc).readCString()});
    } catch (er) { send({type: 'state_err', e: String(er)}); }
}, 9000);
"""


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)
            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)[:600], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(22)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
