#!/usr/bin/env python3
"""Identify Driver import stubs: dump Module.enumerateImports('Driver') and map GOT slots."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const drv = Process.getModuleByName('Driver');
send({type: 'base', base: drv.base.toString()});
let imps = [];
try { imps = Module.enumerateImports('Driver'); } catch (e) { send({type: 'err', e: String(e)}); }
const want = [0x1ed0c28, 0x1ed0e00, 0x1ed0e08, 0x1ed0e10, 0x1ed0e28, 0x1eda0468, 0x1ed0b78, 0x1ed0ba0];
const out = [];
for (const im of imps) {
    if (im.address) {
        const off = im.address.sub(drv.base).toInt32();
        out.push([off, im.name, im.module || '']);
    }
}
send({type: 'imports', n: out.length});
for (const w of want) {
    const hit = out.filter(x => x[0] === w);
    send({type: 'want', off: w, hits: hit});
}
// also dump a window of imports near our stub GOT area
send({type: 'sample', rows: out.slice(0, 12)});
"""


class Watchdog:
    def __init__(self, secs=80):
        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(80)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    ps = {p.name: p.pid for p in dev.enumerate_processes()}
    pid = ps.get('Driver')
    if not pid:
        pid = dev.spawn([BID]); dev.resume(pid); time.sleep(8)
    print('attach', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:3000], flush=True))
    s.load()
    time.sleep(2)
    sess.detach()


if __name__ == '__main__':
    main()
