#!/usr/bin/env python3
"""Superclass chains for the shield + real delegate classes."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

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_getSuperclass = new NativeFunction(e('class_getSuperclass'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));

for (const nm of ['Function_UmcOPEDGyT', 'Function_JgvFbyFH', 'Function_slnYhAnDKk',
                  'Driver.AppDelegate', 'Driver.SceneDelegate', 'FlutterAppDelegate',
                  'FlutterViewController', 'UIWindowSceneDelegate', 'UIResponder']) {
    const c = cls(nm);
    if (c.isNull()) { send({type: 'cls', name: nm, exists: false}); continue; }
    const chain = [];
    let p = c, n = 0;
    while (!p.isNull() && n++ < 10) { chain.push(class_getName(p).readCString()); p = class_getSuperclass(p); }
    send({type: 'cls', name: nm, exists: true, chain: chain});
}
"""


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)


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('Driver')
    if not pid:
        pid = dev.spawn([BID]); dev.resume(pid); time.sleep(8)
    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)[:900], flush=True))
    s.load()
    time.sleep(2.5)
    sess.detach()


if __name__ == '__main__':
    main()
