#!/usr/bin/env python3
"""Build 43 patch step: revert build-42 brk probes in Driver, restore the three neutered
build-info stubs (setRootViewController:/makeKeyAndVisible/addSubview:) to working adrp.

Every write is verified by re-reading.
"""
import shutil, sys

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

DRIVER = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
ORIG = r'E:\ios\work319\patch_src_orig\Driver'
BI = r'E:\ios\work319\patch_src\Payload\Driver.app\Frameworks\build-info.framework\build-info'

# 1) revert brk probes -> original bytes
probes = [0x32900, 0x32918, 0x329cc, 0x33398, 0x33344, 0x33334]
od = open(ORIG, 'rb').read()
cd = bytearray(open(DRIVER, 'rb').read())
for off in probes:
    orig4 = od[off:off + 4]
    cur4 = bytes(cd[off:off + 4])
    if cur4 == orig4:
        print('probe 0x%x already original' % off)
        continue
    if cur4[3] == 0xd4 and cur4[2] == 0x20:  # brk #N encoding pattern ?00020d4
        cd[off:off + 4] = orig4
        print('probe 0x%x reverted -> %s' % (off, orig4.hex()))
    else:
        sys.exit('unexpected bytes at 0x%x: %s' % (off, cur4.hex()))
open(DRIVER, 'wb').write(bytes(cd))

# 2) restore neutered stubs in build-info
#    entry instruction `ret` (d65f03c0) -> adrp x1, 0x7fc000 (donor words, same adrp page)
restores = [
    (0x761460, bytes.fromhex('c10400f0'), 'setRootViewController:'),
    (0x760d20, bytes.fromhex('e1040090'), 'makeKeyAndVisible'),
    (0x760200, bytes.fromhex('e1040090'), 'addSubview:'),
]
RET = bytes.fromhex('c0035fd6')
b = bytearray(open(BI, 'rb').read())
for off, neww, name in restores:
    cur = bytes(b[off:off + 4])
    if cur == neww:
        print('stub 0x%x (%s) already restored' % (off, name))
        continue
    if cur != RET:
        sys.exit('stub 0x%x (%s) unexpected current bytes %s' % (off, name, cur.hex()))
    b[off:off + 4] = neww
    print('stub 0x%x (%s) restored -> %s' % (off, name, neww.hex()))
open(BI, 'wb').write(bytes(b))

# 3) verify
vd = open(DRIVER, 'rb').read()
vb = open(BI, 'rb').read()
ok = True
for off in probes:
    if vd[off:off + 4] != od[off:off + 4]:
        print('VERIFY FAIL driver 0x%x' % off)
        ok = False
for off, neww, name in restores:
    if vb[off:off + 4] != neww:
        print('VERIFY FAIL stub 0x%x (%s)' % (off, name))
        ok = False
print('ALL VERIFIED' if ok else 'VERIFY ERRORS')
