#!/usr/bin/env python3
"""Resolve Driver import stubs by reading their GOT slots and asking dyld for symbol names."""
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');
const slots = {
  '0x18fe118': 0x1ed0c28,
  '0x190bd14': 0x1ed9e00,
  '0x190bd2c': 0x1ed9e10,
  '0x190bd50': 0x1ed9e28,
  '0x190bd20': 0x1ed9e08,
  '0x190c6b0': 0x1eda0468,
  '0x190c794': 0x1ed0000,   // placeholder, refined below
  '0x190a9d0': 0x1ed0000,
};
for (const [stub, off] of Object.entries(slots)) {
    try {
        const p = drv.base.add(off).readPointer();
        let ds = null;
        try { ds = DebugSymbol.fromAddress(p); } catch (e) {}
        send({type: 'stub', stub: stub, slot: '0x' + off.toString(16), ptr: p.toString(),
              sym: ds ? (ds.name + ' @ ' + ds.moduleName + '+0x' + p.sub(Process.getModuleByName(ds.moduleName).base).toString(16)) : '?'});
    } catch (e) { send({type: 'err', stub: stub, e: String(e)}); }
}
"""


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)[:800], flush=True))
    s.load()
    time.sleep(2)
    sess.detach()


if __name__ == '__main__':
    main()
