#!/usr/bin/env python3
"""Hook the shell VC's setErrorMessages:/errorMessages and dump the codes array + origin."""
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 objc_msgSend = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), '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(); };

function dumpArray(arr) {
    try {
        const d = objc_msgSend(arr, sel('description'));
        return d.readUtf8String().slice(0, 1500);
    } catch (er) { return 'ERR ' + er; }
}

const c = cls('Function_slnYhAnDKk');
for (const [s2, l2] of [['setErrorMessages:', 'setErr'], ['errorMessages', 'getErr']]) {
    const m = class_getInstanceMethod(c, sel(s2));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        Interceptor.attach(imp, {
            onEnter(args) {
                this.from = modOf(this.returnAddress);
                if (l2 === 'setErr') send({type: l2, from: this.from, val: dumpArray(args[2])});
            },
            onLeave(v) {
                if (l2 === 'getErr') send({type: l2, from: this.from, val: dumpArray(v)});
            }
        });
        send({type: 'hooked', label: l2, imp: modOf(imp)});
    }
}
"""


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)[:1500], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(14)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
