#!/usr/bin/env python3
"""Read the shield delegate's fields around the 0x2912b0 decision."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'


class Watchdog:
    def __init__(self, secs=80):
        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 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 cn = o => o.isNull() ? '(nil)' : object_getClassName(o).readCString();

function desc(p) {
    if (p.isNull()) return 'null';
    try { return cn(p) + ' :: ' + (objc_msgSend(p, sel('description')).readUtf8String() || '').slice(0, 160); }
    catch (er) { return 'ptr ' + p.toString(); }
}

const app = objc_msgSend(cls('UIApplication'), sel('sharedApplication'));
const dl = objc_msgSend(app, sel('delegate'));
send({type: 'delegate', cls: cn(dl), ptr: dl.toString()});
if (!dl.isNull()) {
    for (const off of [0x520, 0x550, 0x3c8, 0x3b0, 0x3b8, 0x590, 0x68, 0x60]) {
        let v;
        try { v = dl.add(off).readPointer(); } catch (er) { send({type: 'f', off: off.toString(16), err: String(er)}); continue; }
        send({type: 'f', off: off.toString(16), raw: v.toString(), desc: desc(v)});
    }
    for (const off of [0x347, 0x327, 0x580]) {
        try { send({type: 'b', off: off.toString(16), val: dl.add(off).readU8()}); }
        catch (er) { send({type: 'b', off: off.toString(16), err: String(er)}); }
    }
}
"""


def main():
    delay = float(sys.argv[1]) if len(sys.argv) > 1 else 8.0
    Watchdog(80)
    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('Driver')
    if pid:
        print('attach existing', pid, flush=True)
        sess = dev.attach(pid)
    else:
        pid = dev.spawn([BID])
        dev.resume(pid)
        time.sleep(delay)
        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()
    time.sleep(2.5)
    sess.detach()


if __name__ == '__main__':
    main()
