#!/usr/bin/env python3
"""Experiment: force the scene configuration's delegateClass to Driver.SceneDelegate at runtime.
If the real scene delegate runs, 0x3271c should fire and Flutter should start."""
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 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']);
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

const nsstr = s => m1(cls('NSString'), sel('stringWithUTF8String:'), S(s));

const role = nsstr('UIWindowSceneSessionRoleApplication');
const name = nsstr('Default Configuration');
const allocCfg = m0(cls('UISceneConfiguration'), sel('alloc'));
const cfg = m2(allocCfg, sel('initWithName:sessionRole:'), name, role);
send({type: 'cfg', ptr: cfg.toString(), cls: object_getClassName(cfg).readCString()});

const realCls = cls('Driver.SceneDelegate');
send({type: 'realCls', ptr: realCls.toString(), name: realCls.isNull() ? 'nil' : 'Driver.SceneDelegate'});
m1(cfg, sel('setDelegateClass:'), realCls);
const got = m0(cfg, sel('delegateClass'));
send({type: 'delegateClass', ptr: got.toString(),
      name: got.isNull() ? 'nil' : object_getClassName(got).readCString()});

const m = class_getInstanceMethod(cls('Function_UmcOPEDGyT'),
                                  sel('application:configurationForConnectingSceneSession:options:'));
if (m.isNull()) { send({type: 'no_method'}); } else {
    const oldImp = method_getImplementation(m);
    const cb = new NativeCallback(function (self, cmd, session, options) {
        send({type: 'swizzled_call'});
        return cfg;
    }, 'pointer', ['pointer', 'pointer', 'pointer', 'pointer']);
    method_setImplementation(m, cb);
    send({type: 'swizzled', old: modOf(oldImp)});
}

// watch the real scene delegate + Flutter
const sdImp = method_getImplementation(class_getInstanceMethod(cls('Driver.SceneDelegate'),
    sel('scene:willConnectToSession:options:')));
try {
    Interceptor.attach(sdImp, {
        onEnter(a) { send({type: 'REAL_SD_willConnect', scene: a[2].toString(), session: a[3].toString()}); }
    });
    send({type: 'hooked_sd', imp: modOf(sdImp)});
} catch (er) { send({type: 'hookerr_sd', e: String(er)}); }

const sceneFn = Process.getModuleByName('Driver').base.add(0x3271c);
try {
    Interceptor.attach(sceneFn, { onEnter(a) { send({type: 'REAL_SCENE_FN', x0: a[0].toString(), x1: a[1].toString()}); } });
    send({type: 'hooked_scene_fn'});
} catch (er) { send({type: 'hookerr_scene_fn', e: String(er)}); }

let flutterDone = false;
const hookFlutter = () => {
    if (flutterDone) return;
    const fe = cls('FlutterEngine');
    if (fe.isNull()) return;
    flutterDone = true;
    for (const [s2, l2] of [['run', 'fe_run'], ['runWithEntrypoint:', 'fe_run1']]) {
        const mm = class_getInstanceMethod(fe, sel(s2));
        if (!mm.isNull()) {
            try {
                Interceptor.attach(method_getImplementation(mm), { onEnter() { send({type: 'FLUTTER', label: l2}); } });
                send({type: 'hooked', label: l2});
            } catch (er) { send({type: 'hookerr', label: l2, e: String(er)}); }
        }
    }
};
setInterval(hookFlutter, 400);
setTimeout(() => clearInterval(hookFlutter), 16000);
"""


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


if __name__ == '__main__':
    main()
