#!/usr/bin/env python3
"""Pull the per-app dyld cache and check which patch bytes are live in it."""
import asyncio, sys
sys.stdout.reconfigure(encoding='utf-8')
from pymobiledevice3.lockdown import create_using_usbmux
from pymobiledevice3.services.house_arrest import HouseArrestService

BID = 'vn.gsm.md'
UDID = '00008130-001E084434DB803A'
OUT = r'E:\ios\work319\Driver.dyld4'


async def main():
    ld = await create_using_usbmux(serial=UDID)
    async with await HouseArrestService.create(ld, BID, documents_only=False) as afc:
        await afc.pull('/Library/Caches/com.apple.dyld/Driver.dyld4', OUT)
    print('pulled', OUT)


asyncio.run(main())

d = open(OUT, 'rb').read()
print('size', len(d))
print('magic', d[:16])
# find embedded mach-o headers (0xfeedfacf)
import struct
i = 0
mh = b'\xcf\xfa\xed\xfe'
hdrs = []
while True:
    i = d.find(mh, i)
    if i < 0:
        break
    hdrs.append(i)
    i += 4
print('mach-o headers at', [hex(h) for h in hdrs[:20]])
# check patch sites relative to each header (Driver image base 0x100000000)
for h in hdrs[:5]:
    # parse segments to map vmaddr->file offset inside this embedded image
    ncmds = struct.unpack_from('<I', d, h + 16)[0]
    off = h + 32
    sites = {0x22C740: 'presenter ret', 0x3271C: 'abort nop1', 0x3281C: 'abort nop2'}
    print('--- image at %#x ---' % h)
    for _ in range(ncmds):
        cmd, size = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            name = d[off + 8:off + 24].split(b'\0')[0].decode()
            vm, msz, fo, fsz = struct.unpack_from('<QQQQ', d, off + 24)
            if name == '__TEXT':
                for so, label in sites.items():
                    o = fo + so
                    if o + 4 <= len(d):
                        print('   %-16s %#x = %s' % (label, so, d[o:o + 4].hex()))
        off += size
