#!/usr/bin/env python3
"""Spawn vn.gsm.md on the RootHide device via the root frida-server and watch it live."""
import frida, sys, time, json

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

BID = 'vn.gsm.md'


def main():
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    try:
        pid = dev.spawn([BID])
    except Exception as e:
        print('spawn ERR', type(e).__name__, str(e)[:300])
        return
    print('spawned pid', pid)

    session = dev.attach(pid)
    print('attached')

    JS = r"""
    const m = Process.enumerateModules();
    send({type: 'modules', count: m.length, first: m.slice(0, 6).map(x => x.name)});
    const main = m.filter(x => x.name === 'Driver')[0];
    send({type: 'main', base: main ? main.base.toString() : null, size: main ? main.size : null});
    """
    script = session.create_script(JS)
    script.on('message', lambda msg, data: print('[frida]', json.dumps(msg)[:500]))
    script.load()

    dev.resume(pid)
    print('resumed')

    for i in range(12):
        time.sleep(1)
        try:
            procs = {p.pid: p.name for p in dev.enumerate_processes()}
            alive = pid in procs
        except Exception as e:
            print('enumerate err', e)
            alive = None
        print('t=%2ds alive=%s' % (i + 1, alive))
        if alive is False:
            break
    try:
        session.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
