#!/usr/bin/env python3
"""Rebuild proper binaries from the contiguous memory dump taken on device.

The on-device dump for each module is the raw memory image [base, base+size),
which maps 1:1 onto the original file offsets because these images satisfy
    vaddr - 0x100000000 == fileoff.

So for every dumped module:
  * start from the ON-DISK original (App Store / PARTIAL payload) -- its
    __DATA / __DATA_CONST hold the pre-rebase internal pointers that dyld's
    rebase opcodes require (rebasing is NOT idempotent);
  * overwrite __TEXT     with dump bytes  (decrypted code);
  * overwrite __LINKEDIT with dump bytes  (TRUE dyld_info + symtab + export trie
    -- the old dump had these zeroed, which is what killed 4,568 imports).

Usage: python rebuild_dump.py [dump_dir] [out_dir]
"""
import os, struct, sys, zipfile

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

DUMPDIR = sys.argv[1] if len(sys.argv) > 1 else r'E:\ios\work319\dump319'
OUTDIR = sys.argv[2] if len(sys.argv) > 2 else r'E:\ios\work319\proper319'
ORIG_IPA = r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa'
os.makedirs(OUTDIR, exist_ok=True)


def segments(data):
    magic, = struct.unpack_from('<I', data, 0)
    if magic != 0xFEEDFACF:
        raise ValueError('not a 64-bit Mach-O')
    ncmds, = struct.unpack_from('<I', data, 16)
    off = 32
    out = []
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', data, off)
        if cmd == 0x19:
            name = data[off + 8:off + 24].rstrip(b'\0').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', data, off + 24)
            out.append((name, vmaddr, vmsize, fileoff, filesize))
        off += sz
    return out


def dyldinfo(data):
    ncmds, = struct.unpack_from('<I', data, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', data, off)
        if cmd == 0x80000022:
            return struct.unpack_from('<10I', data, off + 8)
        off += sz
    return None


def main():
    orig = {}
    with zipfile.ZipFile(ORIG_IPA) as z:
        for n in z.namelist():
            b = os.path.basename(n)
            if b and not n.endswith('/'):
                orig.setdefault(b, n)
    print('indexed %d files from the original payload' % len(orig))

    for fn in sorted(os.listdir(DUMPDIR)):
        if not fn.endswith('.bin'):
            continue
        modname = fn[:-4]
        dump = open(os.path.join(DUMPDIR, fn), 'rb').read()
        if dump[:4] != b'\xcf\xfa\xed\xfe':
            print('%-28s : not a Mach-O, skipped' % modname)
            continue
        if modname not in orig:
            print('%-28s : no on-disk counterpart, skipped' % modname)
            continue
        with zipfile.ZipFile(ORIG_IPA) as z:
            base_data = z.read(orig[modname])
        segs = segments(base_data)
        total = max(s[3] + s[4] for s in segs)

        out = bytearray(total)
        out[:len(base_data)] = base_data[:total]

        copied = []
        # Overwrite EVERY segment with the raw memory image, mapped per segment:
        #   source offset in the dump = vmaddr - vmaddr(__TEXT)
        #   destination in the file   = fileoff
        # (__LINKEDIT does not follow the linear vaddr==fileoff relation, so this
        #  per-segment mapping is required rather than a flat copy.)
        text_vm = next(s[1] for s in segs if s[0] == '__TEXT')
        for name, vmaddr, vmsize, fileoff, filesize in segs:
            if filesize == 0:
                continue
            src = vmaddr - text_vm
            if src < 0 or src + filesize > len(dump):
                print('%-28s : dump too short for %s (need 0x%x, have 0x%x)'
                      % (modname, name, src + filesize, len(dump)))
                continue
            avail = min(filesize, len(dump) - src)
            out[fileoff:fileoff + avail] = dump[src:src + avail]
            copied.append('%s(src 0x%x -> 0x%x,+0x%x/%s0x%x)'
                          % (name, src, fileoff, avail,
                             '' if avail == filesize else 'of ', filesize))

        di = dyldinfo(bytes(out))
        tag = ''
        if di:
            ro, rs, bo, bs, wo, ws, lo, ls, eo, es = di
            tag = 'dyld_info: rebase 0x%x/0x%x bind 0x%x/0x%x lazy 0x%x/0x%x export 0x%x/0x%x' % (
                ro, rs, bo, bs, lo, ls, eo, es)
            ok = rs > 0x100 and bs > 0x100 and ls > 0x100 and es > 0x100
            tag += '   [%s]' % ('LOOKS VALID' if ok else 'STILL GARBAGE')

        dst = os.path.join(OUTDIR, modname)
        open(dst, 'wb').write(bytes(out))
        print('%-28s : wrote %d bytes  %s' % (modname, len(out), ' '.join(copied)))
        print('%-28s   %s' % ('', tag))


if __name__ == '__main__':
    main()
