# -*- coding: utf-8 -*-
"""nohook_probe.py — attach vào Driver đang chạy, script KHÔNG patch gì.
Chỉ: đếm threads định kỳ, đọc 24 byte registry (Driver+0x452260), probe API HWBP.
Mục đích: xác nhận patch-code (không phải sự hiện diện của frida) là trigger thoát-3s.
Usage: python nohook_probe.py <run-id> [--dur=60] [ghi_chu...]
"""
import frida, sys, os, time, json, datetime

UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'
OUTDIR = r'E:\ios\dump_tool\runs'

JS = r'''
'use strict';
var result = { ev: 'probe', hwbp_api: 'none', exc_api: 'none', thread_api: 'none' };
try { if (typeof Process.setHardwareBreakpoint === 'function') result.hwbp_api = 'available'; } catch (e) {}
try { if (typeof Process.setExceptionHandler === 'function') result.exc_api = 'available'; } catch (e) {}
try { if (typeof Process.enumerateThreads === 'function') result.thread_api = 'available'; } catch (e) {}
send(result);

var driver = null, bi = null;
Process.enumerateModules().forEach(function (m) {
  if (m.path.indexOf('/Driver.app/Driver') !== -1 && m.name === 'Driver') driver = m;
  if (m.path.indexOf('build-info.framework/build-info') !== -1) bi = m;
});
send({ ev: 'modules', driver: driver ? driver.base.toString() : null,
       bi: bi ? bi.base.toString() : null });

// đọc registry 24 byte (bảng cấu hình tại Driver+0x452260) — chỉ đọc
function readReg() {
  try {
    if (!driver) return null;
    var ab = Memory.readByteArray(driver.base.add(0x452260), 24);
    var u = new Uint8Array(ab), s = '';
    for (var i = 0; i < u.length; i++) s += ('0' + u[i].toString(16)).slice(-2);
    return s;
  } catch (e) { return 'ERR:' + String(e).slice(0, 80); }
}

var n = 0;
var timer = setInterval(function () {
  n++;
  var th = null;
  try { th = Process.enumerateThreads().length; } catch (e) { th = -1; }
  send({ ev: 'tick', n: n, threads: th, reg24: readReg(),
         t: new Date().toISOString() });
  if (n >= 30) clearInterval(timer);
}, 2000);
send({ ev: 'probe_ready' });
'''

def main():
    args = sys.argv[1:]
    run_id = args[0] if args else 'run-nohook'
    dur = 60
    note = []
    for a in args[1:]:
        if a.startswith('--dur='):
            dur = int(a.split('=', 1)[1])
        else:
            note.append(a)
    note = ' '.join(note)
    os.makedirs(OUTDIR, exist_ok=True)
    logfile = os.path.join(OUTDIR, '%s-%s.log' % (run_id, datetime.datetime.now().strftime('%H%M%S')))
    f = open(logfile, 'w', encoding='utf-8', buffering=1)

    def w(line):
        f.write(line + '\n')
        try: print(line[:300])
        except Exception: pass

    def on_message(msg, data):
        if msg.get('type') == 'send':
            p = msg['payload']
            if isinstance(p, dict):
                p['_log'] = logfile; p['_run'] = run_id; p['_note'] = note
            w(json.dumps(p, ensure_ascii=False))
        elif msg.get('type') == 'error':
            w(json.dumps({'ev': 'script_error', 'desc': msg.get('description')}, ensure_ascii=False))

    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    pid = None
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            pid = p.pid; break
    if not pid:
        print('KHONG thay Driver dang chay'); sys.exit(1)
    w(json.dumps({'ev': 'attach', 'pid': pid, 'note': note,
                  'at': datetime.datetime.now().isoformat()}))
    s = dev.attach(pid)
    s.on('detached', lambda reason, *a: w(json.dumps(
        {'ev': 'DETACHED', 'reason': reason, 'at': datetime.datetime.now().isoformat()})))
    sc = s.create_script(JS)
    sc.on('message', on_message)
    sc.load()
    w(json.dumps({'ev': 'probe_script_loaded', 'pid': pid}))
    t0 = time.time()
    try:
        while time.time() - t0 < dur:
            time.sleep(1)
    except KeyboardInterrupt:
        pass
    w(json.dumps({'ev': 'run_stop', 'at': datetime.datetime.now().isoformat()}))
    try: s.detach()
    except Exception: pass
    f.close()
    # app còn sống không?
    time.sleep(2)
    alive = any(p.pid == pid for p in dev.enumerate_processes())
    print('APP SAU %ds: %s' % (dur, 'ALIVE' if alive else 'CHET'))

if __name__ == '__main__':
    main()
