#!/usr/bin/env python3
"""Build 45 patch step (on top of build 44 state).

Root cause found (2026-11-23):
  The inherited patch set had NEUTERED four import stubs and six call sites in the
  Driver binary itself. Two of those call sites are the Swift value-type metadata
  accessors inside
      - Driver.SceneDelegate.scene:willConnectToSession:options:  (Driver+0x3271c, call @0x3281c)
      - Driver.AppDelegate.application:didFinishLaunchingWithOptions: (Driver+0x3b8da4, call @0x3b8e0c)
  NOPing the call leaves x0 = 0, and the next instruction `ldur x28,[x0,#-8]`
  (value-witness-table pointer of the Swift metadata) faults at 0xfffffffffffffff8.
  That is exactly the SIGSEGV seen when the real SceneDelegate was allowed to run,
  and the abort seen when the real AppDelegate didFinishLaunching was invoked.

This step:
  1. restores those call sites + stubs to the pristine bytes (real app launch path),
  2. patches build-info `application:configurationForConnectingSceneSession:options:`
     (build-info+0x292198) to `mov x0,#0; ret`, so UIKit falls back to the
     Info.plist scene manifest -> UISceneDelegateClassName = Driver.SceneDelegate.
     (Proven at runtime: this is what makes the real SceneDelegate run.)
"""
import sys

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

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

# offset -> expected SHIPPED (neutered) bytes, replacement = pristine bytes
DRV_RESTORE = [
    (0x031FA8, '1f2003d5', '37316394'),   # bl 0x18fe484  (metadata accessor)
    (0x03281C, '1f2003d5', '3f2e6394'),   # bl 0x18fe118  (SceneDelegate willConnect - the crash)
    (0x032BF8, '1f2003d5', 'a03b00b4'),   # cbz x0, #0x3336c  (restored null guard)
    (0x0333CC, '1f2003d5', '2e2c6394'),   # bl 0x18fe484
    (0x035E4B4, '1f2003d5', '197f5694'),  # bl 0x18fe118
    (0x03B8E0C, '1f2003d5', '9e155594'),  # bl 0x18fe484  (AppDelegate didFinishLaunching - the abort)
    (0x05DE9C8, '1f2003d5', '48774c94'),  # bl 0x18fc6e8  (metadata accessor thunk)
    (0x18FE118, 'c0035fd6', '902e00d0'),  # import stub: adrp x16
    (0x18FE484, 'c0035fd6', '902e00d0'),  # import stub: adrp x16
    (0x18FC6E8, 'c0035fd6', 'a03a00d0'),  # local accessor thunk: adrp x0
    (0x190C47C, 'c0035fd6', '702e00d0'),  # import stub: adrp x16
]

# build-info scene-config method -> return nil (UIKit falls back to Info.plist)
BI_OFF = 0x292198
BI_ORIG = 'f00310aaf10311aa'          # mov x16,x16 ; mov x17,x17
BI_NEW = '000080d2c0035fd6'           # mov x0, #0 ; ret

drv = bytearray(open(DRV, 'rb').read())
pristine = open(ORIG_DRV, 'rb').read()

for off, ship, want in DRV_RESTORE:
    cur = bytes(drv[off:off + 4]).hex()
    if cur == want:
        print('Driver 0x%06x already pristine' % off)
        continue
    if cur != ship:
        sys.exit('unexpected Driver bytes at 0x%x: %s (expected %s)' % (off, cur, ship))
    drv[off:off + 4] = bytes.fromhex(want)
    print('Driver 0x%06x %s -> %s' % (off, ship, want))

open(DRV, 'wb').write(bytes(drv))

# verify every restored site now matches the pristine binary exactly
chk = open(DRV, 'rb').read()
for off, _ship, _want in DRV_RESTORE:
    if chk[off:off + 4] != pristine[off:off + 4]:
        sys.exit('restore verify FAILED at 0x%x' % off)
print('restored %d Driver sites, byte-identical to pristine' % len(DRV_RESTORE))

bi = bytearray(open(BI, 'rb').read())
cur = bytes(bi[BI_OFF:BI_OFF + 8]).hex()
if cur == BI_NEW:
    print('build-info 0x%x already patched' % BI_OFF)
elif cur != BI_ORIG:
    sys.exit('unexpected build-info bytes at 0x%x: %s' % (BI_OFF, cur))
else:
    bi[BI_OFF:BI_OFF + 8] = bytes.fromhex(BI_NEW)
    open(BI, 'wb').write(bytes(bi))
    print('build-info 0x%x scene-config -> mov x0,#0; ret' % BI_OFF)

assert open(BI, 'rb').read()[BI_OFF:BI_OFF + 8].hex() == BI_NEW
print('VERIFIED')
