#!/usr/bin/env python3
"""Force-resolve a Driver lazy import stub, then ask dyld what it is.
Also reports the return value when called with x0=0 in the healthy (ban-screen) process."""
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 stubs = [0x18fe118, 0x18fe484, 0x19038a8, 0x18fe550, 0x18fe508];
for (const off of stubs) {
    const va = drv.base.add(off);
    // 1) what does the GOT hold before
    let gotBefore = null;
    try { gotBefore = va.readPointer().toString(); } catch (e) {}
    // 2) call it with x0 = 0
    let ret = null, err = null;
    try {
        const f = new NativeFunction(va, 'pointer', ['pointer']);
        ret = f(ptr(0)).toString();
    } catch (e) { err = String(e); }
    // 3) GOT after + symbol name
    let resolved = null, sym = null;
    try {
        const p = va.readPointer();
        resolved = p.toString();
        const ds = DebugSymbol.fromAddress(p);
        const m = Process.findModuleByAddress(p);
        sym = ds.name + (m ? '  [' + m.name + '+0x' + p.sub(m.base).toString(16) + ']' : '');
    } catch (e) { sym = 'ERR ' + e; }
    send({type: 'stub', off: '0x' + off.toString(16), gotBefore: gotBefore, ret: ret, err: err,
          resolved: resolved, sym: sym});
}
"""


class Watchdog:
    def __init__(self, secs=90):
        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(90)
    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)[:700], flush=True))
    s.load()
    time.sleep(2)
    sess.detach()


if __name__ == '__main__':
    main()
