#!/usr/bin/env python3
"""Dump the shield's shell VC class (Function_slnYhAnDKk) methods and hook its lifecycle."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'


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 class_copyMethodList = new NativeFunction(e('class_copyMethodList'), 'pointer', ['pointer', 'pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getName = new NativeFunction(e('method_getName'), 'pointer', ['pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const sel_getName = new NativeFunction(e('sel_getName'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

const NAME = 'Function_slnYhAnDKk';
const c = cls(NAME);
if (c.isNull()) { send({type: 'noclass'}); } else {
    const cntP = Memory.alloc(Process.pointerSize);
    const list = class_copyMethodList(c, cntP);
    const n = cntP.readUInt();
    const methods = [];
    for (let i = 0; i < n; i++) {
        const meth = list.add(i * Process.pointerSize).readPointer();
        methods.push({sel: sel_getName(method_getName(meth)).readCString(),
                      imp: modOf(method_getImplementation(meth))});
    }
    send({type: 'methods', cls: NAME, n: n, list: methods});
    for (const mm of methods) {
        const s = mm.sel;
        if (/viewDidLoad|viewWillAppear|viewDidAppear|viewWillLayout|viewDidLayout|initWith|loadView|traitCollection|timer|Tick|detect|start/i.test(s)) {
            const m = class_getInstanceMethod(c, sel(s));
            if (!m.isNull()) {
                const imp = method_getImplementation(m);
                try {
                    Interceptor.attach(imp, { onEnter() { send({type: 'enter', sel: s}); } });
                    send({type: 'hooked', sel: s, imp: mm.imp});
                } catch (er) { send({type: 'hookerr', sel: s, e: String(er)}); }
            }
        }
    }
}
"""


def main():
    Watchdog(90)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            print('kill stale', p.pid, flush=True)
            dev.kill(p.pid)
    time.sleep(2)
    pid = dev.spawn([BID])
    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()
    dev.resume(pid)
    time.sleep(16)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
