#!/usr/bin/env python3
"""Attach to the stuck app: does Driver.SceneDelegate exist? its methods/IMPs? any live instance?"""
import os, sys, time, json, threading

sys.stdout.reconfigure(encoding='utf-8')
import frida


class Watchdog:
    def __init__(self, secs=60):
        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)


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 class_getName = new NativeFunction(e('class_getName'), 'pointer', ['pointer']);
const class_copyMethodList = new NativeFunction(e('class_copyMethodList'), 'pointer', ['pointer', 'pointer']);
const sel_getName = new NativeFunction(e('sel_getName'), 'pointer', ['pointer']);
const method_getName = new NativeFunction(e('method_getName'), 'pointer', ['pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

function methodList(c) {
    const cntP = Memory.alloc(Process.pointerSize);
    const list = class_copyMethodList(c, cntP);
    const n = cntP.readUInt();
    const out = [];
    for (let i = 0; i < n; i++) {
        const meth = list.add(i * Process.pointerSize).readPointer();
        out.push({sel: sel_getName(method_getName(meth)).readCString(),
                  imp: modOf(method_getImplementation(meth))});
    }
    return out;
}

for (const nm of ['Driver.SceneDelegate', 'Driver.AppDelegate', 'SceneDelegate', 'AppDelegate']) {
    const c = objc_getClass(S(nm));
    if (c.isNull()) { send({type: 'class', name: nm, exists: false}); continue; }
    send({type: 'class', name: nm, exists: true, realName: class_getName(c).readCString(),
          methods: methodList(c)});
}
"""


def main():
    Watchdog(60)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    procs = {p.name: p.pid for p in dev.enumerate_processes()}
    pid = procs.get('Driver')
    if not pid:
        print('Driver not running')
        return
    print('attach', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:1200], flush=True))
    s.load()
    time.sleep(6)
    sess.detach()


if __name__ == '__main__':
    main()
