#!/usr/bin/env python3
"""Spawn vn.gsm.md suspended and read the on-device bytes at the three restored stubs."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=60):
        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"""
const bi = Process.getModuleByName('build-info');
const out = {};
for (const off of [0x761460, 0x760d20, 0x760200, 0x7612a0, 0x760d00]) {
    const p = bi.base.add(off);
    const bytes = Array.from(new Uint8Array(p.readByteArray(16)))
        .map(b => b.toString(16).padStart(2, '0')).join(' ');
    out['0x' + off.toString(16)] = bytes;
}
send({type: 'bytes', base: bi.base.toString(), data: out});
"""


def main():
    Watchdog(60)
    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(2)
    pid = dev.spawn([BID])
    print('spawned (suspended)', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:800], flush=True))
    s.load()
    # do NOT resume; read and quit
    sess.detach()
    dev.kill(pid)
    print('killed without resume', flush=True)


if __name__ == '__main__':
    main()
