#!/usr/bin/env python3
"""Native ObjC introspection (Frida 17 has no ObjC bridge): app delegate, key window,
scenes, root VCs, and interesting classes with their selectors."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=90):
        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 sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const msg0 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const msg1 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), '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 objc_getClassList = new NativeFunction(e('objc_getClassList'), 'int', ['pointer', 'int']);

function S(s) { return Memory.allocUtf8String(s); }
function cls(n) { return objc_getClass(S(n)); }
function sel(s) { return sel_registerName(S(s)); }
function m0(o, s) { return o.isNull() ? ptr(0) : msg0(o, sel(s)); }
function m1(o, s, a) { return o.isNull() ? ptr(0) : msg1(o, sel(s), a); }
function cname(o) { return o.isNull() ? '(nil)' : object_getClassName(o).readCString(); }
function num(o) { return o.isNull() ? -1 : Number(m0(o, 'unsignedLongValue') !== ptr(0) && false ? 0 : 0); }
function cnt(o) {
    if (o.isNull()) return -1;
    const v = m1(o, 'count', ptr(0));
    try { return Number(m0(o, 'count')); } catch (e2) {}
    try {
        const NSUInteger = new NativeFunction(m0(m0(cls('NSNumber'), 'numberWithLong:'), 'longValue'), 'long', ['pointer']);
        return -2;
    } catch (e) { return -3; }
}
function n_of(o) {
    // count of NSArray-like: call -count via objc_msgSend returning NSUInteger
    try {
        const f = new NativeFunction(e('objc_msgSend'), 'ulong', ['pointer', 'pointer']);
        return Number(f(o, sel('count')));
    } catch (er) { return -1; }
}
function desc(o) {
    if (o.isNull()) return '(nil)';
    try { return msg0(o, sel('description')).readUtf8String(); }
    catch (e) { return cname(o); }
}

// ---- UIApplication state ----
const app = m0(cls('UIApplication'), 'sharedApplication');
send({type: 'app', cls: cname(app)});
const del = m0(app, 'delegate');
send({type: 'delegate', cls: cname(del), ptr: del.toString()});

const kw = m0(app, 'keyWindow');
send({type: 'keyWindow', cls: cname(kw)});
if (!kw.isNull()) {
    const rvc = m0(kw, 'rootViewController');
    send({type: 'rootVC', cls: cname(rvc)});
    const vcView = m0(rvc, 'view');
    const subs = m0(vcView, 'subviews');
    send({type: 'rootvc_view', cls: cname(vcView), subviews: n_of(subs)});
    if (!subs.isNull() && n_of(subs) > 0) {
        const f = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
        const s0 = f(subs, sel('objectAtIndex:'), 0);
        send({type: 'sub0', cls: cname(s0), frame: desc(m0(s0, 'frame')).slice(0, 200)});
    }
}

const scenes = m0(app, 'connectedScenes');
const scn = n_of(scenes);
send({type: 'scenes', n: scn});
const msgBool = new NativeFunction(e('objc_msgSend'), 'uchar', ['pointer', 'pointer']);
const msgPtrIdx = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
if (scn > 0) {
    const anyS = msgPtrIdx(scenes, sel('anyObject'), 0);
    send({type: 'scene', cls: cname(anyS)});
    const windows = m0(anyS, 'windows');
    const wn = n_of(windows);
    send({type: 'scene_windows', n: wn});
    for (let i = 0; i < Math.min(wn, 4); i++) {
        const w = msgPtrIdx(windows, sel('objectAtIndex:'), i);
        const rvc = m0(w, 'rootViewController');
        send({type: 'win', i: i, cls: cname(w), hidden: Number(msgBool(w, sel('isHidden'))),
              root: cname(rvc), key: Number(msgBool(w, sel('isKeyWindow')))});
        if (!rvc.isNull()) {
            const v = m0(rvc, 'view');
            const subs = m0(v, 'subviews');
            send({type: 'rootvc', i: i, view: cname(v), subviews: n_of(subs),
                  vcview: desc(v).slice(0, 260)});
        }
    }
}

// ---- interesting classes + selectors ----
const ncls = objc_getClassList(ptr(0), 0);
const buf = Memory.alloc(ncls * Process.pointerSize);
objc_getClassList(buf, ncls);
const pick = [];
for (let i = 0; i < ncls; i++) {
    const c = buf.add(i * Process.pointerSize).readPointer();
    const nm = class_getName(c).readCString();
    if (/Driver|AppDelegate|SceneDelegate|Shield|Banned|GsmDriver|MdDriver|Main/i.test(nm)) pick.push(nm);
}
pick.sort();
send({type: 'classes', total: ncls, picked: pick});

// selectors of a few key classes
for (const nm of pick.slice(0, 12)) {
    try {
        const c = cls(nm);
        const cntPtr = Memory.alloc(Process.pointerSize);
        const list = class_copyMethodList(c, cntPtr);
        const n = cntPtr.readUInt();
        const sels = [];
        for (let i = 0; i < n && i < 40; i++) {
            const meth = list.add(i * Process.pointerSize).readPointer();
            sels.push(sel_getName(method_getName(meth)).readCString());
        }
        send({type: 'methods', cls: nm, n: n, sels: sels});
    } catch (er) { send({type: 'merr', cls: nm, e: String(er)}); }
}
"""


def main():
    Watchdog(90)
    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)[:1000], flush=True))
    s.load()
    time.sleep(10)
    sess.detach()


if __name__ == '__main__':
    main()
