#!/usr/bin/env python3
"""Capture dyld's lazy-bind failure message: dyld writes its halt message to fd 2
using write(2) from its OWN copy (not libsystem_kernel), so hook the syscall
wrapper and dump everything written to fd 2 while the trap happens."""
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; };

// capture everything written to fd 2
let captured = [];
try {
    const w = Process.getModuleByName('libsystem_kernel.dylib').getExportByName('write');
    Interceptor.attach(w, { onEnter(a) {
        const fd = a[0].toInt32();
        if (fd !== 2) return;
        const len = a[2].toInt32();
        if (len <= 0 || len > 8192) return;
        try {
            const s = a[1].readUtf8String(Math.min(len, 1500));
            captured.push(s);
            send({type: 'WRITE2', len: len, text: s.slice(0, 1200)});
        } catch (er) {
            const b = a[1].readByteArray(Math.min(len, 400));
            captured.push('<binary ' + len + '>');
            send({type: 'WRITE2BIN', len: len});
        }
    }});
    send({type: 'hooked_write'});
} catch (er) { send({type: 'write_hook_fail', e: String(er)}); }

// also try dyld's own exported halt path
for (const n of ['dyld_stub_binder', '__dyld_stub_binder']) {
    try {
        const p = e(n);
        Interceptor.attach(p, { onEnter() { send({type: 'STUB_BINDER', at: modOf(p)}); } });
        send({type: 'hooked_binder', at: modOf(p)});
    } catch (er) { send({type: 'no_binder', n: n}); }
}

// 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', e: String(er), captured: captured.slice(0, 6)}); }
}, '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)[:1500], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(22)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
