#!/usr/bin/env python3
"""Resolve build-info globals (expected scene class) vs the actual UIWindowScene class."""
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 object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const class_getSuperclass = new NativeFunction(e('class_getSuperclass'), 'pointer', ['pointer']);
const class_getName = new NativeFunction(e('class_getName'), 'pointer', ['pointer']);
const objc_msgSend = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const objc_getClass = new NativeFunction(e('objc_getClass'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const sel = s => (new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']))(S(s));
const cname = o => o.isNull() ? '(nil)' : object_getClassName(o).readCString();

function chain(c) {
    const out = [];
    let n = 0;
    while (!c.isNull() && n++ < 8) { out.push(class_getName(c).readCString()); c = class_getSuperclass(c); }
    return out;
}

const bi = Process.getModuleByName('build-info');

// globals the willConnect gate uses
for (const off of [0x7fd168, 0x7fd0d8, 0x7fd0f0, 0x7fd0e8]) {
    try {
        const p = bi.base.add(off).readPointer();
        if (p.isNull()) { send({type: 'global', off: off.toString(16), val: 'null'}); continue; }
        let clsName = '';
        try { clsName = object_getClassName(p).readCString(); } catch (er) { clsName = 'ERR'; }
        send({type: 'global', off: off.toString(16), ptr: p.toString(), cls: clsName,
              chain: chain(p)});
    } catch (er) { send({type: 'global', off: off.toString(16), err: String(er)}); }
}

// actual scene class of the live app
const app = objc_msgSend(objc_getClass(S('UIApplication')), sel('sharedApplication'));
const scenes = objc_msgSend(app, sel('connectedScenes'));
const anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
const sc = anyF(scenes, sel('anyObject'), 0);
send({type: 'scene', cls: cname(sc), chain: chain(sc)});

// the window the shield's scene delegate holds
const win = objc_msgSend(sc, sel('windows'));
const w0 = anyF(win, sel('anyObject'), 0);
send({type: 'window', cls: cname(w0)});
"""


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)[:700], flush=True))
    s.load()
    time.sleep(6)
    sess.detach()


if __name__ == '__main__':
    main()
