#!/usr/bin/env python3
"""Hook the flag getter (build-info 0x298ec) at spawn time.

Records: total calls, retval histogram, first/last call sites, first/last raw flag byte,
plus retvals of the outer chain (0x2a12c4 / 0x2c59a4 / 0x2c5b40).
No backtraces (they hang). Watchdog-protected.
"""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const bi = Process.getModuleByName('build-info');
const FLAG = bi.base.add(0x298ec);

const st = {total: 0, rets: {}, first: null, last: null, ring: [], bytes: {}};

Interceptor.attach(FLAG, {
    onEnter(args) {
        this.obj = args[0];
        this.site = this.returnAddress.sub(bi.base).toString(16);
        st.total++;
        const b = this.obj.add(0x80).readU8();
        const key = this.site;
        if (!st.bytes[key]) st.bytes[key] = {n: 0, b: []};
        const rec = st.bytes[key];
        rec.n++;
        if (rec.b.length < 6) rec.b.push(b);
    },
    onLeave(retval) {
        const r = retval.toInt32() & 0xff;
        st.rets[r] = (st.rets[r] || 0) + 1;
        const e = {site: this.site, ret: r};
        if (!st.first) st.first = e;
        st.last = e;
        if (st.ring.length < 8) st.ring.push(e); else { st.ring.shift(); st.ring.push(e); }
    }
});

// outer chain retvals
for (const off of [0x2a12c4, 0x2c59a4, 0x2c5b40]) {
    try {
        Interceptor.attach(bi.base.add(off), {
            onLeave(v) { send({type: 'chain', off: off.toString(16), ret: v.toString()}); }
        });
    } catch (e) { send({type: 'chainerr', off: off.toString(16), err: String(e)}); }
}

setInterval(function () {
    send({type: 'tick', total: st.total, rets: st.rets,
          first: st.first, last: st.last, ring: st.ring, bytes: st.bytes});
}, 4000);
"""


class Watchdog:
    def __init__(self, secs=150):
        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)


def main():
    Watchdog(150)
    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', pid, flush=True)
    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(25)
    print('observation done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
