#!/usr/bin/env python3
"""Capture dyld's halt message on the X: hook dyld's internal
abort_with_payload / dyld4::halt (offsets taken from the 15 Pro crash report)
and dump the payload strings - dyld names the missing symbol there."""
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 S = s => Memory.allocUtf8String(s);
const KEEP = [];
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
function cs(p) { try { return p.isNull() ? '(null)' : p.readCString(); } catch (e) { return '(unreadable)'; } }

function hookAt(off, label, nargs) {
    const a = dyld.base.add(off);
    try {
        Interceptor.attach(a, { onEnter(args) {
            const parts = [];
            for (let i = 0; i < nargs; i++) {
                try { parts.push('a%d=%s'.replace('%d', i).replace('%s', cs(args[i]))); }
                catch (e) { parts.push('a%d=?'.replace('%d', i)); }
            }
            send({type: 'DYLD_MSG', at: label, args: parts.join(' | ').slice(0, 900),
                  bt: Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 8).map(modOf)});
        }});
        send({type: 'hooked', at: label, addr: modOf(a)});
    } catch (er) { send({type: 'hook_fail', at: label, e: String(er)}); }
}

// offsets from the 15 Pro crash report (same dyld build family as iOS 16.7.16?)
hookAt(0x6ebfc, 'abort_with_payload', 6);
hookAt(0x6ebcc, 'abort_with_payload_wrapper_internal', 4);
hookAt(0x17f1c, 'dyld4::halt', 3);
hookAt(0x64ee4, '__abort_with_payload', 6);
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)[:900], flush=True)


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


if __name__ == '__main__':
    main()
