#!/usr/bin/env python3
"""Spawn-time hooks on the REAL Driver.SceneDelegate / Driver.AppDelegate methods (by class+selector
IMP lookup) to see which of them UIKit ever calls."""
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 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 hook(clsName, selName, label) {
    const c = cls(clsName);
    if (c.isNull()) { send({type: 'miss', label: label, why: 'class'}); return; }
    const m = class_getInstanceMethod(c, sel(selName));
    if (m.isNull()) { send({type: 'miss', label: label, why: 'sel'}); return; }
    const imp = method_getImplementation(m);
    send({type: 'imp', label: label, imp: modOf(imp)});
    Interceptor.attach(imp, {
        onEnter(args) {
            send({type: 'enter', label: label,
                  arg2: args[2].isNull() ? 'nil' : cname(args[2]),
                  arg3: args[3].isNull() ? 'nil' : cname(args[3])});
        },
        onLeave(v) { send({type: 'leave', label: label, ret: modOf(v)}); }
    });
}

hook('Driver.SceneDelegate', 'scene:willConnectToSession:options:', 'willConnect');
hook('Driver.SceneDelegate', 'sceneWillEnterForeground:', 'fg');
hook('Driver.SceneDelegate', 'sceneDidEnterBackground:', 'bg');
hook('Driver.SceneDelegate', 'init', 'sd_init');
hook('Driver.AppDelegate', 'application:didFinishLaunchingWithOptions:', 'ad_didFinish');
hook('Driver.AppDelegate', 'application:configurationForConnectingSceneSession:options:', 'ad_config');
hook('Driver.AppDelegate', 'window', 'ad_window');
hook('Driver.AppDelegate', 'setWindow:', 'ad_setWindow');
"""


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