#!/usr/bin/env python3
"""Spawn vn.gsm.md under Frida and trace the engine init chain + Driver scene function.

Offsets are file-relative VAs from the 3.19.0 analysis:
  build-info: mod_init chain 0x2c5b40 -> 0x2c59a4 -> 0x2a12c4 -> 0x29900 (state init)
              verdict assembly 0xe0d0, notify 0xe074
  Driver:     scene fn 0x3271c, gate 0x32bf8, presenter 0x22c740
"""
import frida, sys, time, json

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

BID = 'vn.gsm.md'

HOOKS = [
    ('build-info', 0x2c5b40, 'bi_chain_1'),
    ('build-info', 0x2c59a4, 'bi_chain_2'),
    ('build-info', 0x2a12c4, 'bi_chain_3'),
    ('build-info', 0x29900, 'bi_state_init'),
    ('build-info', 0xe0d0, 'bi_verdict'),
    ('build-info', 0xe074, 'bi_notify'),
    ('Driver', 0x3271c, 'drv_scene'),
    ('Driver', 0x32bf8, 'drv_gate'),
    ('Driver', 0x22c740, 'drv_presenter'),
]

JS = r"""
const HOOKS = HOOKLIST;
const state = {hits: {}};

function modByName(n) {
    try { return Process.getModuleByName(n); } catch (e) { return null; }
}

send({type: 'modules', driver: !!modByName('Driver'), buildinfo: !!modByName('build-info'),
      count: Process.enumerateModules().length});

for (const h of HOOKS) {
    const m = modByName(h[0]);
    if (!m) { send({type: 'nohook', mod: h[0], name: h[2]}); continue; }
    const addr = m.base.add(h[1]);
    try {
        Interceptor.attach(addr, {
            onEnter(args) {
                const key = h[2];
                state.hits[key] = (state.hits[key] || 0) + 1;
                if (state.hits[key] <= 3) {
                    let bt = [];
                    try {
                        bt = Thread.backtrace(this.context, Backtracer.FUZZY)
                            .slice(0, 4).map(a => a.sub(m.base).toString());
                    } catch (e) {}
                    send({type: 'hit', name: key, mod: h[0], off: h[1].toString(16),
                          x0: args[0].toString(), x1: args[1].toString(), bt: bt});
                }
            }
        });
        send({type: 'hooked', mod: h[0], name: h[2], addr: addr.toString()});
    } catch (e) {
        send({type: 'hookerr', mod: h[0], name: h[2], err: String(e)});
    }
}

setInterval(function () { send({type: 'tick', hits: state.hits}); }, 5000);
"""


def main():
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    pid = dev.spawn([BID])
    print('spawned pid', pid)
    session = dev.attach(pid)
    script = session.create_script(JS.replace('HOOKLIST', json.dumps(HOOKS)))
    script.on('message', lambda m, d: print('[frida]', json.dumps(m)[:700]))
    script.load()
    dev.resume(pid)
    print('resumed; observing 25s')
    time.sleep(25)
    try:
        session.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
