#!/usr/bin/env python3
"""Spawn, wait N seconds, attach, FUZZY thread dump (fast, before the 20s watchdog)."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
function fmt(a) {
    const m = Process.findModuleByAddress(a);
    return m ? (m.name + '+0x' + a.sub(m.base).toString(16)) : a.toString();
}
const threads = Process.enumerateThreads();
send({type: 'count', n: threads.length});
for (const t of threads) {
    const out = {type: 'thread', id: t.id, state: t.state, pc: fmt(t.context.pc)};
    try {
        out.frames = Thread.backtrace(t.context, Backtracer.FUZZY).slice(0, 16).map(fmt);
    } catch (e) { out.frames = ['ERR ' + e]; }
    send(out);
}
"""


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)


def main():
    delay = float(sys.argv[1]) if len(sys.argv) > 1 else 12.0
    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([BID])
    dev.resume(pid)
    t0 = time.time()
    print('spawned+resumed', pid, flush=True)
    time.sleep(max(0.5, delay - (time.time() - t0)))
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    msgs = []
    s.on('message', lambda m, d: msgs.append(m))
    s.load()
    time.sleep(2)
    sess.detach()
    for m in msgs:
        p = m.get('payload') or {}
        if p.get('type') == 'count':
            print('\nthreads: %d' % p['n'])
        elif p.get('type') == 'thread':
            print('\n== thread %s state=%s pc=%s' % (p['id'], p['state'], p['pc']))
            for i, f in enumerate(p.get('frames', [])):
                print('   #%-2d %s' % (i, f))


if __name__ == '__main__':
    main()
