#!/usr/bin/env python3
"""Compare the memory image vs the on-disk PARTIAL IPA binary for nanopb -
one of the 15 frameworks that ldid -S fails on - to find the structural
difference that breaks ldid."""
import os, sys, struct, zipfile

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

IPA = r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa'
MEM = r'E:\ios\work319\dump319\nanopb.bin'

z = zipfile.ZipFile(IPA)
nm = [n for n in z.namelist() if 'nanopb.framework/nanopb' in n and n.endswith('nanopb')]
print('entries in PARTIAL IPA:', nm)
disk = z.read(nm[0])
mem = open(MEM, 'rb').read()

print('on-disk : %d bytes' % len(disk))
print('memory  : %d bytes' % len(mem))
print()

for label, d in (('ON-DISK', disk), ('MEMORY', mem)):
    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
    for _ in range(ncmds):
        if off + 8 > len(d):
            print('  !! overrun at 0x%x' % off)
            break
        cmd, sz = struct.unpack_from('<II', d, off)
        nm2 = ''
        if cmd == 0x19:
            nm2 = d[off+8:off+24].rstrip(b'\0').decode()
            vm, vs, fo, fs = struct.unpack_from('<QQQQ', d, off+24)
            print('  SEG %-14s cmdsize 0x%-5x fo 0x%-6x fs 0x%-6x  end 0x%x%s' % (
                nm2, sz, fo, fs, fo+fs, '  !!>filesize' if fo+fs > len(d) else ''))
        elif cmd == 0x2C:
            cid, = struct.unpack_from('<I', d, off+16)
            print('  LC_ENCRYPTION_INFO_64 cryptid=%d' % cid)
        off += sz
        if off > len(d):
            print('  !! commands past EOF')
            break
    print()

# now check ldid compatibility: ldid -S needs the __LINKEDIT to be well-formed
# specifically it rewrites the CodeSignature blob at the end of __LINKEDIT
# check if the __LINKEDIT filesize covers the whole file
for label, d in (('ON-DISK', disk), ('MEMORY', mem)):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    max_end = 0
    le_fo = le_fs = 0
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            fo, fs = struct.unpack_from('<QQ', d, off+40)
            if fo + fs > max_end:
                max_end = fo + fs
            if fo + fs > len(d):
                print('%s: SEGMENT past EOF! fo=0x%x fs=0x%x filesize=0x%x' % (label, fo, fs, len(d)))
        off += sz
    print('%s: last segment ends 0x%x, filesize 0x%x, %s' % (
        label, max_end, len(d), 'MATCH' if max_end <= len(d) else 'OVERSIZE'))
