#!/usr/bin/env python3
"""Classify every __la_symbol_ptr entry in the shipped Driver binary as
RESOLVED (points outside Driver) or UNBOUND (points inside __stub_helper).
Tells us the scale of the broken lazy binding."""
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 base = drv.base, size = drv.size;
// __la_symbol_ptr: file off 0x1ed0000, size 0xa8a8 -> 5405 entries
const LA_OFF = 0x1ed0000, LA_SIZE = 0xa8a8;
const n = LA_SIZE / 8;
// __stub_helper: file off 0x190cd10 .. 0x190ca24 (end = 0x190cd10 + 0xfd14)
const SH_LO = base.add(0x190cd10), SH_HI = base.add(0x190cd10 + 0xfd14);
let unbound = [], resolved = 0, other = 0;
const la = base.add(LA_OFF);
for (let i = 0; i < n; i++) {
    let v;
    try { v = la.add(i * 8).readPointer(); } catch (er) { continue; }
    if (v.compare(SH_LO) >= 0 && v.compare(SH_HI) < 0) {
        unbound.push(i);
    } else if (v.compare(base) >= 0 && v.compare(base.add(size)) < 0) {
        other++;
    } else {
        resolved++;
    }
}
send({type: 'summary', total: n, unbound: unbound.length, resolvedElsewhere: resolved, inDriverOther: other});
// map a few unbound indexes back to stub VAs for reporting
const STUB_OFF = 0x18fcedc;
const report = unbound.slice(0, 60).map(i => '0x' + (STUB_OFF + i * 12).toString(16));
send({type: 'unbound_stubs', stubs: report});
"""


class Watchdog:
    def __init__(self, secs=120):
        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(120)
    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)
            try:
                dev.kill(p.pid)
            except Exception:
                pass
    time.sleep(1.5)
    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)[:3000], flush=True))
    s.load()
    time.sleep(3)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
