#!/usr/bin/env python3
"""Attach to the running Driver and dump every thread with a FUZZY backtrace (hang-safe)."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=45):
        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"""
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), lr: fmt(t.context.lr), sp: t.context.sp.toString()};
    try {
        out.frames = Thread.backtrace(t.context, Backtracer.FUZZY).slice(0, 24).map(fmt);
    } catch (e) {
        out.frames = ['ERR ' + e];
    }
    send(out);
}
"""


def main():
    Watchdog(60)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    procs = {p.name: p.pid for p in dev.enumerate_processes()}
    pid = procs.get('Driver')
    if not pid:
        print('Driver not running')
        return
    print('attaching to', pid, flush=True)
    sess = dev.attach(pid)
    script = sess.create_script(JS)
    msgs = []
    script.on('message', lambda m, d: msgs.append(m))
    script.load()
    time.sleep(3)
    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' % (p['id'], p['state']))
            print('   pc=%s  lr=%s  sp=%s' % (p['pc'], p['lr'], p['sp']))
            for i, f in enumerate(p.get('frames', [])):
                print('   #%-2d %s' % (i, f))


if __name__ == '__main__':
    main()
