#!/usr/bin/env python3
"""Launch build 46 and probe the live UI state during the 20 s launch-watchdog
window: what does UIApplication.delegate / the scene / the window look like,
and is Flutter ever created?"""
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 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 anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
const drv = Process.getModuleByName('Driver');

function snap(tag) {
    try {
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const dg = m0(app, sel('delegate'));
        const scenes = m0(app, sel('connectedScenes'));
        const sc = anyF(scenes, sel('anyObject'), 0);
        const sdg = sc.isNull() ? ptr(0) : m0(sc, sel('delegate'));
        let win = ptr(0), rvc = ptr(0), hidden = -1;
        if (!sdg.isNull()) {
            win = m0(sdg, sel('window'));
            if (!win.isNull()) {
                rvc = m0(win, sel('rootViewController'));
                hidden = win.add(0x20).readU8();
            }
        }
        const adWin = dg.isNull() ? ptr(0) : m0(dg, sel('window'));
        let adRvc = ptr(0);
        if (!adWin.isNull()) adRvc = m0(adWin, sel('rootViewController'));
        send({type: 'snap', tag: tag,
              appDel: dg.isNull() ? 'nil' : object_getClassName(dg).readCString(),
              sceneDel: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString(),
              win: win.isNull() ? 'nil' : object_getClassName(win).readCString(),
              hidden: hidden,
              rootVC: rvc.isNull() ? 'nil' : object_getClassName(rvc).readCString(),
              adWin: adWin.isNull() ? 'nil' : object_getClassName(adWin).readCString(),
              adRootVC: adRvc.isNull() ? 'nil' : object_getClassName(adRvc).readCString()});
    } catch (er) { send({type: 'snap_err', tag: tag, e: String(er)}); }
}

// watch the interesting lifecycle points
try { Interceptor.attach(drv.base.add(0x3271c), { onEnter() { send({type: 'REAL_SCENE_FN'}); } }); } catch (er) {}
const hooked = {};
const iv = setInterval(() => {
  for (const [cn, sn, label] of [['FlutterEngine', 'run', 'fe_run'], ['FlutterEngine', 'runWithEntrypoint:', 'fe_run1'],
      ['FlutterViewController', 'initWithEngine:nibName:bundle:', 'fvc_init'], ['FlutterViewController', 'viewDidLoad', 'fvc_vdl']]) {
    const k = cn + '|' + sn; if (hooked[k]) continue;
    const c = cls(cn); if (c.isNull()) continue;
    const m = class_getInstanceMethod(c, sel(sn)); if (m.isNull()) continue;
    hooked[k] = true;
    try { Interceptor.attach(method_getImplementation(m), { onEnter() { send({type: 'HIT', label: label}); } });
          send({type: 'hooked', label: label}); } catch (er) {}
  }
}, 400);
setTimeout(() => clearInterval(iv), 19000);

snap('t0');
setTimeout(() => snap('t3'), 3000);
setTimeout(() => snap('t7'), 7000);
setTimeout(() => snap('t12'), 12000);
setTimeout(() => snap('t18'), 18000);
"""


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()
