#!/usr/bin/env python3
"""Stalker call-trace the shield's -application:didFinishLaunchingWithOptions: (bounded window).
Records call events inside build-info to reveal the exact executed path."""
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 sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), '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 m = class_getInstanceMethod(cls('UIApplication'), sel('setDelegate:'));
const imp = method_getImplementation(m);
Interceptor.attach(imp, {
    onEnter(args) {
        const dn = object_getClassName ? '' : '';
        const cn = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer'])(args[2]).readCString();
        const mm = class_getInstanceMethod(cls(cn), sel('application:didFinishLaunchingWithOptions:'));
        if (mm.isNull()) return;
        const dfImp = method_getImplementation(mm);
        send({type: 'df_imp', imp: modOf(dfImp)});
        Interceptor.attach(dfImp, {
            onEnter(a2) {
                send({type: 'df_enter'});
                const tid = Process.getCurrentThreadId();
                const events = [];
                this.tid = tid;
                Stalker.follow(tid, {
                    events: {call: true},
                    onReceive(ev) {
                        const parsed = Stalker.parse(ev, {annotate: false, stringify: false});
                        const bi = Process.getModuleByName('build-info');
                        const lo = bi.base, hi = bi.base.add(bi.size);
                        for (const p of parsed) {
                            if (events.length < 200000 && p[1].compare(lo) >= 0 && p[1].compare(hi) < 0) events.push(p);
                        }
                    }
                });
                this.events = events;
            },
            onLeave(v) {
                try { Stalker.unfollow(this.tid); Stalker.flush(); } catch (er) {}
                send({type: 'df_leave', ret: modOf(v), n: this.events.length});
                const seq = this.events.map(p => p[1].sub(Process.getModuleByName('build-info').base).toString(16));
                send({type: 'calls', total_bi: seq.length,
                      head: seq.slice(0, 50), tail: seq.slice(-500)});
            }
        });
    }
});
"""


class Watchdog:
    def __init__(self, secs=180):
        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(180)
    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])
    print('spawned', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: (open('stalker_out.json', 'a').write(json.dumps(m) + '\n'),
                                  print('[frida]', json.dumps(m)[:300], flush=True)))
    s.load()
    dev.resume(pid)
    time.sleep(25)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
