#!/usr/bin/env python3
"""Splice the PRISTINE lazy-bind stream from the original App Store IPA into the
properly dumped Driver.

The App Store IPA's Driver has an encrypted __TEXT but a PLAINTEXT __LINKEDIT,
so its lazy-bind stream - the one piece that every dump taken after launch has
lost (dyld zeroes it after processing) - is intact there.

Both files are the same binary (same app version), so the file layout is
identical and the stream can be copied at the same file offset.

usage: python splice_lazybind.py <original.ipa>
"""
import os, sys, zipfile, struct

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

IPA = sys.argv[1] if len(sys.argv) > 1 else None
TARGET = r'E:\ios\work319\proper319\Driver'
OUT = r'E:\ios\work319\proper319\Driver_final'


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


def cryptid(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:
            return struct.unpack_from('<I', d, off + 16)[0]
        off += sz
    return None


def main():
    if not IPA or not os.path.exists(IPA):
        sys.exit('usage: python splice_lazybind.py <original.ipa>')
    with zipfile.ZipFile(IPA) as z:
        names = [n for n in z.namelist() if n.endswith('Driver.app/Driver') or n == 'Payload/Driver.app/Driver']
        if not names:
            sys.exit('Driver not found in the IPA')
        orig = z.read(names[0])
    print('original (App Store, encrypted __TEXT): %d bytes' % len(orig))
    print('  cryptid = %s' % cryptid(orig))

    (ro, rs, bo, bs, wo, ws, lo, ls, eo, es), cmdoff = dyldinfo(orig)
    print('  dyld_info: rebase 0x%x/0x%x  bind 0x%x/0x%x  weak 0x%x/0x%x  lazy 0x%x/0x%x  export 0x%x/0x%x'
          % (ro, rs, bo, bs, wo, ws, lo, ls, eo, es))
    if not lo or not ls:
        sys.exit('the original has no lazy bind stream?!')

    stream = orig[lo:lo + ls]
    nz = sum(1 for c in stream if c)
    print('  lazy bind stream: %d bytes, non-zero %d (%.1f%%)' % (ls, nz, 100.0 * nz / ls))
    if nz < ls * 0.2:
        sys.exit('the stream looks empty - wrong IPA?')

    target = bytearray(open(TARGET, 'rb').read())
    tinfo, toff = dyldinfo(bytes(target))
    print('\ntarget (properly dumped): %d bytes' % len(target))
    print('  dyld_info: rebase 0x%x/0x%x  bind 0x%x/0x%x  lazy 0x%x/0x%x  export 0x%x/0x%x'
          % (tinfo[0], tinfo[1], tinfo[2], tinfo[3], tinfo[6], tinfo[7], tinfo[8], tinfo[9]))
    if lo != tinfo[6] or ls != tinfo[7]:
        print('  NOTE: lazy bind offset/size differ between the two files:')
        print('        original 0x%x/0x%x   target 0x%x/0x%x' % (lo, ls, tinfo[6], tinfo[7]))
        print('        -> splicing at the ORIGINAL offset and size.')

    # sanity: the target region must be the zeroed one
    tseg = bytes(target[lo:lo + ls])
    tnz = sum(1 for c in tseg if c)
    print('  target region non-zero: %d' % tnz)

    # splice
    out = bytearray(target)
    out[lo:lo + ls] = stream
    # keep the dyld_info command identical to the original for the lazy fields
    struct.pack_into('<II', out, toff + 8 + 6 * 4, lo, ls)
    open(OUT, 'wb').write(bytes(out))
    print('\nwrote %s (%d bytes)' % (OUT, len(out)))
    print('lazy bind stream restored: %d bytes at file offset 0x%x' % (ls, lo))


if __name__ == '__main__':
    main()
