#!/usr/bin/env python3
"""Inspect the SpringBoard alert controller: class methods, alert item, available dismiss paths."""
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 sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const objc_msgSend = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const class_copyMethodList = new NativeFunction(e('class_copyMethodList'), 'pointer', ['pointer', 'pointer']);
const class_copyIvarList = new NativeFunction(e('class_copyIvarList'), 'pointer', ['pointer', 'pointer']);
const ivar_getName = new NativeFunction(e('ivar_getName'), 'pointer', ['pointer']);
const method_getName = new NativeFunction(e('method_getName'), 'pointer', ['pointer']);
const sel_getName = new NativeFunction(e('sel_getName'), 'pointer', ['pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const class_getSuperclass = new NativeFunction(e('class_getSuperclass'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const cn = o => object_getClassName(o).readCString();

const app = objc_msgSend(cls('UIApplication'), sel('sharedApplication'));
const windows = objc_msgSend(app, sel('windows'));
const msgUL = new NativeFunction(e('objc_msgSend'), 'ulong', ['pointer', 'pointer']);
const idx = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
const n = Number(msgUL(windows, sel('count')));
let target = null;
for (let i = 0; i < n; i++) {
    const w = idx(windows, sel('objectAtIndex:'), i);
    const rvc = objc_msgSend(w, sel('rootViewController'));
    if (rvc.isNull()) continue;
    const p = objc_msgSend(rvc, sel('presentedViewController'));
    if (!p.isNull()) { target = p; break; }
}
if (!target) { send({type: 'noalert'}); } else {
    const c = object_getClassName(target).readPointer ? null : null;
    const clsObj = cls(cn(target));
    const cntP = Memory.alloc(Process.pointerSize);
    const list = class_copyMethodList(clsObj, cntP);
    const nm = cntP.readUInt();
    const sels = [];
    for (let i = 0; i < nm; i++) {
        const meth = list.add(i * Process.pointerSize).readPointer();
        sels.push(sel_getName(method_getName(meth)).readCString());
    }
    send({type: 'methods', cls: cn(target), n: nm, sels: sels});
    // ivars
    const ilist = class_copyIvarList(clsObj, cntP);
    const inm = cntP.readUInt();
    const ivs = [];
    for (let i = 0; i < inm; i++) {
        ivs.push(ivar_getName(ilist.add(i * Process.pointerSize)).readCString());
    }
    send({type: 'ivars', ivs: ivs});
    // alertItem?
    try {
        const ai = objc_msgSend(target, sel('alertItem'));
        if (!ai.isNull()) {
            const aiCls = cls(cn(ai));
            const l2 = class_copyMethodList(aiCls, cntP);
            const n2 = cntP.readUInt();
            const s2 = [];
            for (let i = 0; i < n2; i++) {
                s2.push(sel_getName(method_getName(l2.add(i * Process.pointerSize))).readCString());
            }
            send({type: 'alertItem', cls: cn(ai), sels: s2});
        } else send({type: 'alertItem', val: 'nil'});
    } catch (er) { send({type: 'ai_err', e: String(er)}); }
}
"""


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


if __name__ == '__main__':
    main()
