#!/usr/bin/env python3
"""Spawn with Interceptor hooks only (no backtraces) and log verdict-path arguments."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

TARGETS = [
    ('build-info', 0xe0d0, 'verdict_assembly'),
    ('build-info', 0xe074, 'notify'),
    ('build-info', 0x29900, 'state_init'),
    ('build-info', 0x4174, 'get'),
    ('build-info', 0x5730, 'addListener'),
    ('Driver', 0x3271c, 'scene_fn'),
    ('Driver', 0x32bf8, 'gate'),
    ('Driver', 0x22c740, 'presenter'),
]

JS = r"""
const T = TARGETS;
const hits = {};
for (const t of T) {
    let m = null;
    try { m = Process.getModuleByName(t[0]); } catch (e) {}
    if (!m) { send({type: 'nohook', mod: t[0], name: t[2]}); continue; }
    const addr = m.base.add(t[1]);
    try {
        Interceptor.attach(addr, {
            onEnter(args) {
                const k = t[2];
                hits[k] = (hits[k] || 0) + 1;
                if (hits[k] <= 4) {
                    const a = [];
                    for (let i = 0; i < 6; i++) a.push(args[i].toString());
                    send({type: 'hit', name: k, n: hits[k], args: a});
                }
            }
        });
        send({type: 'hooked', name: t[2], addr: addr.toString()});
    } catch (e) {
        send({type: 'hookerr', name: t[2], err: String(e)});
    }
}
setInterval(function () { send({type: 'tick', hits: hits}); }, 4000);
"""


class Watchdog:
    def __init__(self, secs):
        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(120)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            print('killing stale Driver', p.pid, flush=True)
            dev.kill(p.pid)
    time.sleep(2)

    pid = dev.spawn([BID])
    print('spawned', pid, flush=True)
    sess = dev.attach(pid)
    script = sess.create_script(JS.replace('TARGETS', json.dumps(TARGETS)))
    script.on('message', lambda m, d: print('[frida]', json.dumps(m)[:400], flush=True))
    script.load()
    print('hooks installed, resuming', flush=True)
    dev.resume(pid)
    time.sleep(20)
    print('done observing', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
