#!/usr/bin/env python3
"""Capture dyld's halt with full argument/memory dumping: the StructuredError
that dyld passes to abort_with_payload carries the missing symbol's name."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const dyld = Process.getModuleByName('dyld');
const KEEP = [];
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
function hexs(p, n) {
    try { const b = p.readByteArray(n); const u = new Uint8Array(b);
          return Array.from(u).map(x => x.toString(16).padStart(2, '0')).join(' '); }
    catch (e) { return 'ERR'; }
}
function ascii(p, n) {
    try { return p.readCString(); } catch (e) { return '?'; }
}

function hookAt(off, label, nargs) {
    const a = dyld.base.add(off);
    try {
        Interceptor.attach(a, { onEnter(args) {
            const info = { at: label, args: [] };
            for (let i = 0; i < nargs; i++) {
                const p = args[i];
                let desc = { raw: p.toString() };
                try { desc.str = p.readCString(); } catch (e) {}
                try { desc.hex = hexs(p, 1024); } catch (e) {}
                info.args.push(desc);
            }
            info.bt = Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 10).map(modOf);
            send({type: 'DYLD_ABORT', info: info});
        }});
        send({type: 'hooked', at: label, addr: modOf(a)});
    } catch (er) { send({type: 'hook_fail', at: label, e: String(er)}); }
}

hookAt(0x6ebfc, 'abort_with_payload', 6);
hookAt(0x6ebcc, 'abort_with_payload_wrapper_internal', 4);
hookAt(0x64ee4, '__abort_with_payload', 6);
hookAt(0x17f1c, 'dyld4::halt', 3);
hookAt(0x3e280, '_dyld_missing_symbol_abort', 1);
"""


class Watchdog:
    def __init__(self, secs=150):
        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 onmsg(m, d=None):
    print('[frida]', json.dumps(m)[:1600], flush=True)


def main():
    Watchdog(150)
    dev = frida.get_usb_device(timeout=15)
    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 (suspended)', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', onmsg)
    s.load()
    dev.resume(pid)
    time.sleep(20)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
