#!/usr/bin/env python3
"""Dump every binary of the ORIGINAL vn.gsm.md 3.19.0 from the running process
on the RootHide iPhone X, straight out of memory (FairPlay pages are already
decrypted there), and write each as a reconstructed Mach-O file.

Reconstruction rule (this is what the old tool got wrong):
  * __TEXT  -> taken from MEMORY   (decrypted code)
  * __LINKEDIT -> taken from MEMORY (TRUE dyld_info + symtab + export trie;
                 the old dump zeroed these, which is exactly what produced the
                 4,568 dead imports)
  * __DATA / __DATA_CONST -> kept from the ON-DISK file, because those pages hold
                 pre-rebase internal pointers; rebasing is NOT idempotent, so the
                 on-disk values plus the intact rebase opcodes are what dyld needs.

Everything is written with fwrite straight from process memory into
/var/mobile/Media, so the 36 MB images never cross the Frida message channel.
"""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'
OUTDIR = '/var/mobile/Media/dump319'

JS = r"""
const libSystem = Process.getModuleByName('libSystem.B.dylib');
const f = (n, r, a) => new NativeFunction(libSystem.getExportByName(n), r, a);
const fopen_ = f('fopen', 'pointer', ['pointer', 'pointer']);
const fwrite_ = f('fwrite', 'ulong', ['pointer', 'ulong', 'ulong', 'pointer']);
const fclose_ = f('fclose', 'int', ['pointer']);
const mkdir_ = f('mkdir', 'int', ['pointer', 'int']);
const S = s => Memory.allocUtf8String(s);
const KEEP = [];
const keepStr = s => { const p = S(s); KEEP.push(p); return p; };

mkdir_(S(OUTDIR_STR), 0x1ff);

const mods = Process.enumerateModules();
// the app bundle directory, derived from the main executable's path
let appdir = null;
for (const m of mods) {
    if (m.name === 'Driver') { appdir = m.path.substring(0, m.path.lastIndexOf('/')); break; }
}
send({type: 'appdir', path: appdir});

function dumpModule(m) {
    const base = m.base, size = m.size;
    // parse load commands straight from memory
    const magic = base.readU32();
    if (magic !== 0xfeedfacf) { send({type: 'skip', name: m.name, why: 'bad magic'}); return; }
    const ncmds = base.add(16).readU32();
    let off = 32;
    const segs = [];
    let textVm = null;
    for (let i = 0; i < ncmds; i++) {
        const cmd = base.add(off).readU32();
        const cmdsize = base.add(off + 4).readU32();
        if (cmd === 0x19) {  // LC_SEGMENT_64
            const segname = base.add(off + 8).readCString(16).replace(/\0/g, '');
            const vmaddr = base.add(off + 24).readU64();
            const vmsize = base.add(off + 32).readU64();
            const fileoff = base.add(off + 40).readU64();
            const filesize = base.add(off + 48).readU64();
            segs.push({segname: segname, vmaddr: Number(vmaddr), vmsize: Number(vmsize),
                       fileoff: Number(fileoff), filesize: Number(filesize)});
            if (segname === '__TEXT') textVm = Number(vmaddr);
        }
        off += cmdsize;
    }
    if (textVm === null) { send({type: 'skip', name: m.name, why: 'no __TEXT'}); return; }
    const slide = Number(base) - textVm;

    const fname = OUTDIR_STR + '/' + m.name.replace(/\//g, '_') + '.bin';
    const fp = fopen_(keepStr(fname), keepStr('wb'));
    if (fp.isNull()) { send({type: 'fail', name: m.name, why: 'fopen'}); return; }

    // 1. start from a zeroed file of the right size: write the on-disk-friendly
    //    layout by emitting each segment's region.
    //    __TEXT and __LINKEDIT come from memory; everything else is written as
    //    zeros here and replaced on the host from the on-disk file.
    const total = Math.max.apply(null, segs.map(s => s.fileoff + s.filesize));
    const zero = Memory.alloc(0x10000);  // zero-filled
    let written = 0;
    while (written < total) {
        const n = Math.min(0x10000, total - written);
        fwrite_(zero, 1, n, fp);
        written += n;
    }

    for (const sg of segs) {
        if (sg.filesize === 0) continue;
        const fromMemory = (sg.segname === '__TEXT' || sg.segname === '__LINKEDIT');
        if (!fromMemory) continue;
        const addr = base.add(sg.vmaddr - textVm);
        // write in 1 MB chunks
        let done = 0;
        while (done < sg.filesize) {
            const n = Math.min(0x100000, sg.filesize - done);
            fwrite_(addr.add(done), 1, n, fp);
            done += n;
        }
        send({type: 'seg', name: m.name, seg: sg.segname, fileoff: sg.fileoff,
              size: sg.filesize, from: 'memory'});
    }
    fclose_(fp);
    send({type: 'dumped', name: m.name, path: m.path, size: total, segments: segs.length,
          slide: slide});
}

for (const m of mods) {
    if (appdir && m.path.indexOf(appdir) === 0) dumpModule(m);
}
send({type: 'done'});
"""


class Watchdog:
    def __init__(self, secs=600):
        self.deadline = time.time() + secs
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while True:
            time.sleep(0.5)
            if time.time() > self.deadline:
                print('HARD TIMEOUT', flush=True)
                os._exit(3)


def main():
    Watchdog(600)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    ps = {p.name: p.pid for p in dev.enumerate_processes()}
    pid = ps.get('Driver')
    if not pid:
        print('Driver is not running - launch it first', flush=True)
        return
    print('attach', pid, flush=True)
    sess = dev.attach(pid)
    body = JS.replace('OUTDIR_STR', json.dumps(OUTDIR))
    s = sess.create_script(body)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:500], flush=True))
    s.load()
    time.sleep(20)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
