#!/usr/bin/env python3
"""Compare the load commands of the PRISTINE App Store Driver (from ipatool -
never touched by any dump tool) against the PARTIAL dump's Driver.

The question: does the pristine binary use LC_DYLD_CHAINED_FIXUPS (0x80000034)?
If yes, the PARTIAL dump tool stripped that command and replaced it with a
broken LC_DYLD_INFO_ONLY - which is exactly why 4,568 imports cannot bind."""
import struct, sys, zipfile

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

NAMES = {
    0x80000034: 'LC_DYLD_CHAINED_FIXUPS',
    0x80000022: 'LC_DYLD_INFO_ONLY',
    0x00000022: 'LC_DYLD_INFO',
    0x0000002:  'LC_SYMTAB',
    0x000000B:  'LC_DYSYMTAB',
    0x00000019: 'LC_SEGMENT_64',
    0x0000002C: 'LC_ENCRYPTION_INFO_64',
}


def dump_lc(d, label):
    print('=== %s ===' % label)
    magic, = struct.unpack_from('<I', d, 0)
    print('  magic 0x%08x  filesize %d' % (magic, len(d)))
    ncmds, = struct.unpack_from('<I', d, 16)
    sizeofcmds, = struct.unpack_from('<I', d, 20)
    print('  ncmds %d  sizeofcmds 0x%x' % (ncmds, sizeofcmds))
    off = 32
    rows = []
    for _ in range(ncmds):
        if off + 8 > len(d):
            print('  !! overrun at 0x%x' % off)
            break
        cmd, sz = struct.unpack_from('<II', d, off)
        nm = NAMES.get(cmd, '')
        if nm:
            extra = ''
            if cmd == 0x80000034:
                dataoff, datasize = struct.unpack_from('<II', d, off + 8)
                extra = '  dataoff 0x%x datasize 0x%x' % (dataoff, datasize)
            elif cmd == 0x80000022:
                v = struct.unpack_from('<10I', d, off + 8)
                extra = '  rebase 0x%x/0x%x bind 0x%x/0x%x lazy 0x%x/0x%x export 0x%x/0x%x' % (
                    v[0], v[1], v[2], v[3], v[6], v[7], v[8], v[9])
            elif cmd == 0x2:
                v = struct.unpack_from('<4I', d, off + 8)
                extra = '  symoff 0x%x nsyms %d stroff 0x%x strsize 0x%x' % v
            rows.append('  0x%08x  %-26s cmdsize 0x%-5x%s' % (off, nm, sz, extra))
        off += sz
    for r in rows:
        print(r)
    return rows


with zipfile.ZipFile(r'E:\ios\work319\gsm-driver-3.19.0.ipa') as z:
    nm = [n for n in z.namelist() if n.endswith('Driver.app/Driver')][0]
    pristine = z.read(nm)
partial = open(r'E:\ios\work319\patch_src_orig\Driver', 'rb').read()

dump_lc(pristine, 'PRISTINE App Store Driver (ipatool)')
print()
dump_lc(partial, 'PARTIAL dump Driver (what we have been using)')
