#!/usr/bin/env python3
"""Capture the fatal message: iOS fatal errors go through abort_with_payload /
abort_with_reason (libsystem_kernel), which carry the message and reason string.
Reproduces the launch-path trap (real AppDelegate didFinishLaunching) and reports
exactly which condition fails."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const libobjc = Process.getModuleByName('libobjc.A.dylib');
const e = n => libobjc.getExportByName(n);
const objc_getClass = new NativeFunction(e('objc_getClass'), 'pointer', ['pointer']);
const sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const method_setImplementation = new NativeFunction(e('method_setImplementation'), 'pointer', ['pointer', 'pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
const m0 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const m2 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'pointer', 'pointer']);
const hb = h => { const b = []; for (let i = 0; i < h.length; i += 2) b.push(parseInt(h.substr(i, 2), 16)); return b; };
const cs = p => { try { return p.isNull() ? '(null)' : p.readCString(); } catch (er) { return '(unreadable)'; } };

// ---- fatal-path reporters ----
function tryHook(modName, symName, label, argSpec) {
    let p = null;
    try { p = Process.getModuleByName(modName).getExportByName(symName); }
    catch (er) { send({type: 'missing', label: label, sym: symName}); return; }
    try {
        Interceptor.attach(p, { onEnter(a) {
            const info = {};
            for (const [idx, kind] of argSpec) {
                try {
                    if (kind === 's') info['a' + idx] = cs(a[idx]);
                    else if (kind === 'u') info['a' + idx] = a[idx].toInt32();
                    else if (kind === 'p') info['a' + idx] = a[idx].toString();
                } catch (er) { info['a' + idx] = '?'; }
            }
            send({type: 'FATAL', label: label, info: info,
                  bt: Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 14).map(modOf)});
        }});
        send({type: 'hooked', label: label, at: modOf(p)});
    } catch (er) { send({type: 'hookfail', label: label, e: String(er)}); }
}

const K = 'libsystem_kernel.dylib', C = 'libsystem_c.dylib', SW = 'libswiftCore.dylib';
tryHook(K, 'abort_with_payload', 'abort_with_payload',
        [[0,'u'],[1,'u'],[2,'s'],[3,'s'],[4,'s'],[5,'u']]);
tryHook(K, 'abort_with_payload_constant_cstring', 'awp_cstr',
        [[0,'u'],[1,'u'],[2,'s'],[3,'s'],[4,'s'],[5,'u']]);
tryHook(K, 'abort_with_reason', 'abort_with_reason',
        [[0,'u'],[1,'u'],[2,'s'],[3,'u']]);
tryHook(K, '__abort_with_payload', '__abort_with_payload',
        [[0,'u'],[1,'u'],[2,'s'],[3,'s'],[4,'s'],[5,'u']]);
tryHook(C, 'abort_report_np', 'abort_report_np', [[0,'s']]);
tryHook(C, '__assert_rtn', 'assert_rtn', [[0,'s'],[1,'s'],[2,'u'],[3,'s']]);
tryHook(C, '__assert_fail', 'assert_fail', [[0,'s'],[1,'s'],[2,'u'],[3,'s']]);
tryHook(SW, 'swift_reportError', 'swift_reportError', [[0,'u'],[1,'s'],[2,'s'],[3,'u']]);
tryHook(SW, '_swift_stdlib_reportFatalErrorInFile', 'swift_stdlib_fatal', [[0,'s'],[1,'s'],[2,'u']]);
tryHook(SW, 'swift_unexpectedError', 'swift_unexpectedError', [[0,'s']]);
tryHook('libc++abi.dylib', 'abort_message', 'abort_message', [[0,'s']]);
tryHook('libc++abi.dylib', 'demangling_terminate_handler', 'cxx_terminate', []);
tryHook('libobjc.A.dylib', 'objc_exception_throw', 'objc_throw', [[0,'p']]);
tryHook(C, 'exit', 'exit', [[0,'u']]);

// ---- restore Driver launch-path sites ----
const drv = Process.getModuleByName('Driver');
const sites = [[0x031fa8, '37316394'], [0x03281c, '3f2e6394'], [0x032bf8, 'a03b00b4'],
               [0x0333cc, '2e2c6394'], [0x035e4b4, '197f5694'], [0x03b8e0c, '9e155594'],
               [0x05de9c8, '48774c94'], [0x18fe118, '902e00d0'], [0x18fe484, '902e00d0'],
               [0x18fc6e8, 'a03a00d0'], [0x190c47c, '702e00d0']];
for (const [off, h] of sites) { const a = drv.base.add(off); Memory.patchCode(a, 4, p => p.writeByteArray(hb(h))); }
send({type: 'driver_restored', n: sites.length});

// ---- reproduce ----
const realAD = cls('Driver.AppDelegate');
const shieldSD = cls('Function_JgvFbyFH');
const mWC = class_getInstanceMethod(shieldSD, sel('scene:willConnectToSession:options:'));
var cb = new NativeCallback(function (self, cmd, scene, session, options) {
    send({type: 'HANDOFF'});
    try {
        const adInst = m0(m0(realAD, sel('alloc')), sel('init'));
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const r = m2(adInst, sel('application:didFinishLaunchingWithOptions:'), app, ptr(0));
        send({type: 'real_dfl_ok', r: r.toString()});
    } catch (er) { send({type: 'TRAP_AT_DFL', e: String(er)}); }
}, 'void', ['pointer', 'pointer', 'pointer', 'pointer', 'pointer']);
method_setImplementation(mWC, cb);
send({type: 'handoff_installed'});
"""


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 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', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:1600], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(22)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
