#!/usr/bin/env python3
"""Bisect the Frida hang with a hard watchdog: enumerate -> kill -> attach(empty) -> threads-only.

Every step has a deadline; if exceeded the process exits immediately instead of hanging.
"""
import os, sys, time, json, threading

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

PORT = '127.0.0.1:7777'
BID = 'vn.gsm.md'


class Watchdog:
    def __init__(self):
        self.deadline = time.time() + 30
        self.label = 'init'
        threading.Thread(target=self._loop, daemon=True).start()

    def step(self, label, seconds):
        self.label = label
        self.deadline = time.time() + seconds
        print('--- %s (limit %ds) ---' % (label, seconds), flush=True)

    def _loop(self):
        while True:
            time.sleep(0.25)
            if time.time() > self.deadline:
                print('HARD TIMEOUT in step: %s' % self.label, flush=True)
                os._exit(3)


wd = Watchdog()

wd.step('connect', 15)
dev = frida.get_device_manager().add_remote_device(PORT)
print('device object ready', flush=True)

wd.step('enumerate_processes', 20)
t0 = time.time()
procs = list(dev.enumerate_processes())
print('enumerate OK: %d processes in %.1fs' % (len(procs), time.time() - t0), flush=True)
driver = [p for p in procs if p.name == 'Driver']
print('Driver instances:', [(p.pid) for p in driver], flush=True)

wd.step('kill Driver', 20)
for p in driver:
    dev.kill(p.pid)
    print('killed', p.pid, flush=True)
time.sleep(2)

wd.step('enumerate_after_kill', 20)
procs2 = list(dev.enumerate_processes())
print('enumerate after kill OK: %d' % len(procs2), flush=True)

wd.step('spawn', 30)
pid = dev.spawn([BID])
print('spawned', pid, flush=True)

wd.step('attach_empty', 20)
sess = dev.attach(pid)
print('attached', flush=True)

wd.step('load_empty_script', 20)
s = sess.create_script('send({type:"hi", n: Process.enumerateModules().length});')
s.on('message', lambda m, d: print('[msg]', json.dumps(m)[:200], flush=True))
s.load()
print('empty script loaded', flush=True)

wd.step('resume', 20)
dev.resume(pid)
print('resumed', flush=True)
time.sleep(6)

wd.step('threads_only', 25)
s2 = sess.create_script('''
const th = Process.enumerateThreads();
send({type:'threads', n: th.length, ids: th.map(t => t.id), states: th.map(t => t.state)});
''')
s2.on('message', lambda m, d: print('[threads]', json.dumps(m)[:400], flush=True))
s2.load()
print('threads script loaded', flush=True)

wd.step('detach', 15)
sess.detach()
print('DONE - all steps passed', flush=True)
