#!/usr/bin/env python3
"""In-memory test: synthesize a Swift value-type metadata + no-op VWT and point the
5 broken Driver import stubs at it. Then run the real launch chain by hand."""
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 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 KEEP = [];

const drv = Process.getModuleByName('Driver');
const B = drv.base;

// ---- 1. restore the 11 launch-path sites ----
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 = B.add(off); Memory.patchCode(a, 4, p => p.writeByteArray(hb(h))); }
send({type: 'driver_restored', n: sites.length});

// ---- 2. synthesize VWT + metadata ----
const SIZE = 0x800;                     // 2048 bytes, safely larger than any stack temp
const blob = Memory.alloc(0x200); KEEP.push(blob);
const retGadget = Memory.alloc(Process.pageSize); KEEP.push(retGadget);
Memory.patchCode(retGadget, 4, p => p.writeByteArray([0xc0, 0x03, 0x5f, 0xd6]));  // ret

const VWT = blob.add(0x00);
const META = blob.add(0x100);
for (let i = 0; i < 8; i++) VWT.add(i * 8).writePointer(retGadget);
VWT.add(0x40).writeU32(SIZE);           // size
VWT.add(0x44).writeU32(SIZE);           // stride
VWT.add(0x48).writeU32(0x00000700);     // flags (alignment 8-ish, unused by our sites)
VWT.add(0x4c).writeU32(0);              // extra inhabitants
META.add(-8).writePointer(VWT);
META.add(0).writeU32(2);                // MetadataKind.struct
META.add(8).writePointer(ptr(0));       // descriptor (unused by the sizing idiom)
send({type: 'meta_ready', vwt: VWT.toString(), meta: META.toString(), size: SIZE});

// ---- 3. point the 5 broken stubs at META ----
function adrpX0(target, pc) {
    let imm = (target - (pc & ~0xfff)) >> 12;
    const neg = imm < 0; if (neg) imm = -imm;
    const immlo = imm & 3, immhi = (imm >> 2) & 0x7ffff;
    let w = 0x90000000 | (immlo << 29) | (immhi << 5);
    if (neg) w = (0x90000000 | (immlo << 29) | (immhi << 5)) >>> 0;
    // handle negative via two's complement on the 21-bit field
    let field = ((target - (pc & ~0xfff)) >> 12) & 0x1fffff;
    const lo = field & 3, hi = (field >> 2) & 0x7ffff;
    return (0x90000000 | (lo << 29) | (hi << 5)) >>> 0;
}
function addX0(off) { return (0x91000000 | ((off & 0xfff) << 10)) >>> 0; }
function retW() { return 0xd65f03c0; }
const w = (x) => { const b = []; for (let i = 0; i < 4; i++) b.push((x >>> (8 * i)) & 0xff); return b; };

const STUBS = [0x18FE118, 0x18FE484, 0x19038A8, 0x18FE550, 0x18FE508];
for (const off of STUBS) {
    const a = B.add(off);
    const w0 = adrpX0(META, off);
    const w1 = addX0(META & 0xfff);
    const bytes = [].concat(w(w0), w(w1), w(retW()));
    Memory.patchCode(a, 12, p => p.writeByteArray(bytes));
    send({type: 'stub', off: '0x' + off.toString(16), words: [w0.toString(16), w1.toString(16), 'd65f03c0']});
}
send({type: 'stubs_redirected', n: STUBS.length});

// ---- 4. watchers ----
try { Interceptor.attach(B.add(0x3271c), { onEnter() { send({type: 'REAL_SCENE_FN'}); } }); } catch (er) {}
const hooked = {};
const iv = setInterval(() => {
  for (const [cn, sn, label] of [['FlutterEngine', 'run', 'fe_run'], ['FlutterEngine', 'runWithEntrypoint:', 'fe_run1'],
      ['FlutterViewController', 'initWithEngine:nibName:bundle:', 'fvc_init'], ['FlutterViewController', 'viewDidLoad', 'fvc_vdl']]) {
    const k = cn + '|' + sn; if (hooked[k]) continue;
    const c = cls(cn); if (c.isNull()) continue;
    const m = class_getInstanceMethod(c, sel(sn)); if (m.isNull()) continue;
    hooked[k] = true;
    try { Interceptor.attach(method_getImplementation(m), { onEnter() { send({type: 'HIT', label: label}); } });
          send({type: 'hooked', label: label}); } catch (er) {}
  }
}, 300);
setTimeout(() => clearInterval(iv), 25000);

// ---- 5. run the real chain by hand ----
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()});
        const win = m0(adInst, sel('window'));
        send({type: 'real_ad_window', w: win.isNull() ? 'nil' : object_getClassName(win).readCString()});
    } catch (er) { send({type: 'TRAP_AT_DFL', e: String(er)}); }
}, 'void', ['pointer', 'pointer', 'pointer', 'pointer', 'pointer']);
method_setImplementation(mWC, cb);
send({type: 'handoff_installed'});

setTimeout(function () {
    try {
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const scenes = m0(app, sel('connectedScenes'));
        const anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
        const sc = anyF(scenes, sel('anyObject'), 0);
        const sdg = sc.isNull() ? ptr(0) : m0(sc, sel('delegate'));
        let win = ptr(0), rvc = ptr(0);
        if (!sdg.isNull()) { win = m0(sdg, sel('window')); if (!win.isNull()) rvc = m0(win, sel('rootViewController')); }
        send({type: 'state',
              sceneDel: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString(),
              win: win.isNull() ? 'nil' : object_getClassName(win).readCString(),
              rvc: rvc.isNull() ? 'nil' : object_getClassName(rvc).readCString()});
    } catch (er) { send({type: 'state_err', e: String(er)}); }
}, 10000);
"""


class Watchdog:
    def __init__(self, secs=180):
        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(180)
    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)[:900], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(24)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
