#!/usr/bin/env python3
"""Hook -[NSString componentsSeparatedByString:] to capture the baked-in code-list string."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=70):
        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 desc(o) {
    try {
        if (o.isNull()) return 'nil';
        return objc_msgSend(o, sel('description')).readUtf8String().slice(0, 200);
    } catch (er) { return 'ptr:' + o.toString(); }
}

const m = class_getInstanceMethod(cls('NSString'), sel('componentsSeparatedByString:'));
const imp = method_getImplementation(m);
send({type: 'imp', imp: modOf(imp)});
let n = 0;
Interceptor.attach(imp, {
    onEnter(args) {
        this.sep = desc(args[2]);
        this.from = modOf(this.returnAddress);
    },
    onLeave(v) {
        n++;
        if (n <= 6) send({type: 'split', n: n, sep: this.sep, from: this.from, result: desc(v)});
    }
});
"""


def main():
    Watchdog(70)
    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(1.5)
    pid = dev.spawn(['vn.gsm.md'])
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:500], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(10)
    sess.detach()


if __name__ == '__main__':
    main()
