#!/usr/bin/env python3
"""Build 44 launch map: verdict fns, branch decisions, shield VC lifecycle, Flutter start points."""
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 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 cname = o => o.isNull() ? '(nil)' : object_getClassName(o).readCString();
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
const counts = {};

function impHook(modName, off, label, logRet) {
    try {
        Interceptor.attach(Process.getModuleByName(modName).base.add(off), {
            onEnter(a) {
                counts[label] = (counts[label] || 0) + 1;
                this.n = counts[label];
                this.from = modOf(this.returnAddress);
                if (this.n <= 3) send({type: 'hit', label: label, n: this.n, from: this.from,
                                       x0: a[0].toString(), x1: a[1].toString(), x2: a[2].toString()});
            },
            onLeave(v) {
                if (logRet && this.n <= 3) send({type: 'ret', label: label, ret: v.toString()});
            }
        });
        send({type: 'hooked', label: label});
    } catch (er) { send({type: 'hookerr', label: label, e: String(er)}); }
}

const bi = 'build-info';
impHook(bi, 0xe0d0, 'verdict', true);
impHook(bi, 0xe074, 'notify', true);
impHook(bi, 0x4174, 'get', true);
impHook(bi, 0x5730, 'addListener', false);
impHook(bi, 0x2912b8, 'branch_tbnz', false);   // w0 read after 0x9608
impHook(bi, 0x291558, 'ban_entry', false);
impHook(bi, 0x2912c0, 'else_entry', false);
impHook(bi, 0x2914d0, 'else_to_ban', false);
impHook(bi, 0x28feb8, 'df_launch', true);
impHook(bi, 0x298158, 'sd_willConnect', false);

// shield VC lifecycle
for (const [s2, l2] of [['viewDidLoad', 'vc_viewDidLoad'], ['viewWillAppear:', 'vc_willAppear'],
                        ['viewDidAppear:', 'vc_didAppear'], ['viewWillLayoutSubviews', 'vc_willLayout'],
                        ['viewDidLayoutSubviews', 'vc_didLayout']]) {
    const c = cls('Function_slnYhAnDKk');
    if (c.isNull()) { send({type: 'miss', label: l2}); continue; }
    const m = class_getInstanceMethod(c, sel(s2));
    if (m.isNull()) { send({type: 'miss', label: l2}); continue; }
    const imp = method_getImplementation(m);
    try {
        Interceptor.attach(imp, {
            onEnter() { counts[l2] = (counts[l2] || 0) + 1; if (counts[l2] <= 3) send({type: 'hit', label: l2, n: counts[l2]}); }
        });
        send({type: 'hooked', label: l2, imp: modOf(imp)});
    } catch (er) { send({type: 'hookerr', label: l2, e: String(er)}); }
}

// Flutter + real app delegate
let flutterDone = false;
const hookFlutter = () => {
    if (flutterDone) return;
    const fe = cls('FlutterEngine');
    if (fe.isNull()) return;
    flutterDone = true;
    for (const [s2, l2] of [['run', 'fe_run'], ['runWithEntrypoint:', 'fe_run1'],
                            ['runWithEntrypoint:initialRoute:', 'fe_run2']]) {
        const m = class_getInstanceMethod(fe, sel(s2));
        if (!m.isNull()) {
            const imp = method_getImplementation(m);
            try {
                Interceptor.attach(imp, { onEnter() { send({type: 'FLUTTER', label: l2}); } });
                send({type: 'hooked', label: l2, imp: modOf(imp)});
            } catch (er) { send({type: 'hookerr', label: l2, e: String(er)}); }
        }
    }
    const fvc = cls('FlutterViewController');
    if (!fvc.isNull()) {
        const m = class_getInstanceMethod(fvc, sel('initWithEngine:nibName:bundle:'));
        if (!m.isNull()) {
            const imp = method_getImplementation(m);
            try { Interceptor.attach(imp, { onEnter() { send({type: 'FLUTTER', label: 'fvc_init'}); } }); } catch (er) {}
        }
    }
};
setInterval(hookFlutter, 400);
setTimeout(() => clearInterval(hookFlutter), 18000);

for (const [s2, l2] of [['application:didFinishLaunchingWithOptions:', 'real_ad_didFinish'],
                        ['application:configurationForConnectingSceneSession:options:', 'real_ad_config']]) {
    const m = class_getInstanceMethod(cls('Driver.AppDelegate'), sel(s2));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        try { Interceptor.attach(imp, { onEnter() { send({type: 'hit', label: l2}); } }); } catch (er) {}
    }
}
const sm = class_getInstanceMethod(cls('Driver.SceneDelegate'), sel('scene:willConnectToSession:options:'));
if (!sm.isNull()) {
    const imp = method_getImplementation(sm);
    try { Interceptor.attach(imp, { onEnter() { send({type: 'hit', label: 'real_sd_willConnect'}); } }); } catch (er) {}
}
"""


class Watchdog:
    def __init__(self, secs=120):
        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(120)
    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)
    out = open('map44.log', 'w', encoding='utf-8')
    def on_msg(m, d):
        line = json.dumps(m)
        out.write(line + '\n'); out.flush()
        p = m.get('payload') or {}
        t = p.get('type')
        if t in ('hit', 'ret', 'FLUTTER', 'hookerr'):
            print('[frida]', line[:300], flush=True)
    s.on('message', on_msg)
    s.load()
    dev.resume(pid)
    time.sleep(22)
    print('map done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
