#!/usr/bin/env python3
"""Capture the engine state object (via a poll call-site), snapshot its memory, and diff live."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=100):
        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 st = {obj: null, snap: null, lastdiff: null};

function snapshot() {
    return Array.from(new Uint8Array(st.obj.readByteArray(0x200)))
        .map(b => b.toString(16).padStart(2, '0')).join('');
}

// poll call site inside the wait loops -> x0 = state object
Interceptor.attach(bi.base.add(0x1a9a0), {
    onEnter(args) {
        if (!st.obj) {
            st.obj = args[0];
            st.snap = snapshot();
            send({type: 'captured', obj: st.obj.toString(), snap: st.snap.slice(0, 200)});
        }
    }
});

setInterval(function () {
    if (!st.obj) return;
    try {
        const now = snapshot();
        if (now === st.snap) return;
        const diffs = [];
        for (let i = 0; i < now.length; i += 8) {
            if (now.substr(i, 8) !== st.snap.substr(i, 8)) {
                diffs.push('+0x' + (i / 2).toString(16) + ': ' +
                           st.snap.substr(i, 8) + ' -> ' + now.substr(i, 8));
            }
        }
        send({type: 'diff', changes: diffs.slice(0, 40)});
        st.snap = now;
    } catch (e) { send({type: 'err', e: String(e)}); }
}, 1500);
"""


def main():
    Watchdog(100)
    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(['vn.gsm.md'])
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:900], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(18)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
