#!/usr/bin/env python3
"""
apply_patches_319_extra.py - second-stage closures for GSM Driver 3.19.0.

Applied on top of apply_patches_319.py (11 sites already in the tree).

Sites
  build-info +[ShieldData getDetectFlags]  -> return +[NSArray array] (empty)
  build-info +[ShieldAPI getShieldCode]    -> return 0
  build-info -[UIViewController presentViewController:animated:completion:]
                                            -> no-op (kills native block screen)
  MDMap      isSimulatedBySoftware stub    -> false
  MDMap      isProducedByAccessory stub    -> false

Every site is byte-verified before writing; a mismatch aborts the run.
"""
import os, sys, hashlib

BASE = r'E:\ios\work319\patch_src\Payload\Driver.app'

MOV_W0_0 = bytes.fromhex('00008052')   # movz w0, #0
MOV_X0_0 = bytes.fromhex('000080d2')   # movz x0, #0
RET      = bytes.fromhex('c0035fd6')   # ret
NOP      = bytes.fromhex('1f2003d5')   # nop

# getDetectFlags: adrp x8,#0x7fd000 ; ldr x0,[x8,#0x38] (NSArray) ; b 0x760260 ([NSArray array])
GET_FLAGS_STUB = bytes.fromhex('a83f00f0001d40f9bd671d14')

PATCHES = [
    # (relative path, offset, expected_bytes, replacement_bytes, label)
    (r'Frameworks\build-info.framework\build-info', 0x6364,
     bytes.fromhex('f00310aaf10311aaff8304d1'), GET_FLAGS_STUB,
     'ShieldData getDetectFlags -> empty NSArray'),
    (r'Frameworks\build-info.framework\build-info', 0x7970,
     bytes.fromhex('f00310aaf10311aaffc301d1'), MOV_X0_0 + RET + NOP,
     'ShieldAPI getShieldCode -> 0'),
    (r'Frameworks\build-info.framework\build-info', 0x760fa0,
     bytes.fromhex('e1040090'), RET,
     'presentViewController: -> no-op (block screen)'),
    (r'Frameworks\MDMap.framework\MDMap', 0x10816E0,
     bytes.fromhex('213f00f0211442f9702b00f010da43f900021fd6'),
     MOV_W0_0 + RET + NOP + NOP + NOP,
     'MDMap isSimulatedBySoftware -> false'),
    (r'Frameworks\MDMap.framework\MDMap', 0x1081100,
     bytes.fromhex('213f00f0215841f9702b00f010da43f900021fd6'),
     MOV_W0_0 + RET + NOP + NOP + NOP,
     'MDMap isProducedByAccessory -> false'),
    (r'Driver', 0x3281C,
     bytes.fromhex('3f2e6394'), NOP,
     'Driver scene-config abort call -> nop'),
    ('Driver', 0x31FA8,
     bytes.fromhex('37316394'), NOP,
     'Driver willEnterForeground abort call -> nop'),
    (r'Frameworks\build-info.framework\build-info', 0x5730,
     bytes.fromhex('c0035fd6'), bytes.fromhex('f10311aa'),
     'REVERT: ShieldData addListener: restored'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x4000,
     bytes.fromhex('220020d4'), bytes.fromhex('68000090'),
     'REVERT probe C'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x5b00,
     bytes.fromhex('200020d4'), bytes.fromhex('f657bda9'),
     'REVERT probe A'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x40c4,
     bytes.fromhex('210020d4'), bytes.fromhex('ff4301d1'),
     'REVERT probe B'),
    (r'Frameworks\build-info.framework\build-info', 0x4174,
     bytes.fromhex('000080d2c0035fd6'), bytes.fromhex('f00310aaf10311aa'),
     'REVERT: ShieldData get restored (scene fn needs a real state object)'),
    (r'Frameworks\build-info.framework\build-info', 0xe0d0,
     bytes.fromhex('a00354f8badfff97e13340f9e20300aae03740f967481d94e03b00f901000014'),
     bytes.fromhex('e03740f963481d94e03b00f91f2003d51f2003d51f2003d51f2003d501000014'),
     'verdict array -> [NSArray array] (clean verdict at source)'),
    ('Driver', 0x22C740,
     bytes.fromhex('fa67bba9'), RET,
     'BannedViewController presenter -> ret (gate)'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x5020,
     bytes.fromhex('680600b4'), bytes.fromhex('33000014'),
     'plugin readAssets branch -> always FlutterError (bridge kill)'),
    (r'Frameworks\build-info.framework\build-info', 0x4ca80,
     bytes.fromhex('c0035fd6'), bytes.fromhex('f10311aa'),
     'REVERT: build-info mod_init[0] restored'),
    (r'Frameworks\build-info.framework\build-info', 0x75a4b0,
     bytes.fromhex('c0035fd6'), bytes.fromhex('f44fbea9'),
     'REVERT: build-info mod_init[1] restored'),
    ('Driver', 0x333cc,
     bytes.fromhex('2e2c6394'), NOP,
     'Driver fatal tripwire 1 -> nop'),
    ('Driver', 0x35e4b4,
     bytes.fromhex('197f5694'), NOP,
     'Driver fatal tripwire 2 -> nop'),
    ('Driver', 0x3b8e0c,
     bytes.fromhex('9e155594'), NOP,
     'Driver fatal tripwire 3 -> nop'),
    ('Driver', 0x5de9c8,
     bytes.fromhex('48774c94'), NOP,
     'Driver fatal tripwire 4 (+load gate) -> nop'),
    ('Driver', 0x32bf8,
     bytes.fromhex('a03b00b4'), NOP,
     'Driver scene gate: field-zero bail -> nop (always run full setup)'),
    ('Driver', 0x32900,
     bytes.fromhex('e8fc00f0'), bytes.fromhex('2c0020d4'),
     'PROBE W1: window store -> brk'),
    ('Driver', 0x32918,
     bytes.fromhex('006b73f8'), bytes.fromhex('2d0020d4'),
     'PROBE W2: window reload -> brk'),
    ('Driver', 0x329cc,
     bytes.fromhex('29270e94'), bytes.fromhex('2e0020d4'),
     'PROBE W3: sub-tail (window nil) -> brk'),
    ('Driver', 0x33398,
     bytes.fromhex('00fd00d0'), bytes.fromhex('2f0020d4'),
     'PROBE W4: tail -> brk'),
    ('Driver', 0x33344,
     bytes.fromhex('e00319aa'), bytes.fromhex('300020d4'),
     'PROBE W5: tail -> brk'),
    ('Driver', 0x33334,
     bytes.fromhex('e0031caa'), bytes.fromhex('310020d4'),
     'PROBE W6: tail -> brk'),
    ('Driver', 0x3bc2c0,
     bytes.fromhex('270020d4'), bytes.fromhex('f657bda9'),
     'REVERT probe H'),
    ('Driver', 0x31e9c,
     bytes.fromhex('280020d4'), bytes.fromhex('f85fbca9'),
     'REVERT probe I'),
    ('Driver', 0x3271c,
     bytes.fromhex('290020d4'), bytes.fromhex('fc6fbaa9'),
     'REVERT probe K'),
    ('Driver', 0x246c58,
     bytes.fromhex('2a0020d4'), bytes.fromhex('f44fbea9'),
     'REVERT probe L'),
    ('Driver', 0x3b8da4,
     bytes.fromhex('2b0020d4'), bytes.fromhex('fc6fbaa9'),
     'REVERT probe M'),
    (r'Frameworks\build-info.framework\build-info', 0x4d458,
     bytes.fromhex('2c0020d4'), bytes.fromhex('01000014'),
     'REVERT probe N1'),
    (r'Frameworks\build-info.framework\build-info', 0x240040,
     bytes.fromhex('2d0020d4'), bytes.fromhex('fd7b41a9'),
     'REVERT probe N2'),
    (r'Frameworks\build-info.framework\build-info', 0x238084,
     bytes.fromhex('2e0020d4'), bytes.fromhex('fd7bc1a8'),
     'REVERT probe N3'),
    (r'Frameworks\build-info.framework\build-info', 0x25f2f0,
     bytes.fromhex('2f0020d4'), bytes.fromhex('e80300aa'),
     'REVERT probe N4'),
    (r'Frameworks\build-info.framework\build-info', 0x29900,
     bytes.fromhex('300020d4'), bytes.fromhex('08014239'),
     'REVERT probe N5 (state initializer runs for real)'),
    ('Driver', 0x32960,
     bytes.fromhex('230020d4'), bytes.fromhex('00a941f9'),
     'REVERT probe D'),
    ('Driver', 0x32a48,
     bytes.fromhex('240020d4'), bytes.fromhex('166d47f9'),
     'REVERT probe E'),
    ('Driver', 0x33374,
     bytes.fromhex('250020d4'), bytes.fromhex('bf4301d1'),
     'REVERT probe F'),
    ('Driver', 0x3336c,
     bytes.fromhex('260020d4'), bytes.fromhex('a08350f8'),
     'REVERT probe G'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x40b0,
     bytes.fromhex('000080d2'), bytes.fromhex('681b0014'),
     'plugin onListen hook -> cave (push clean event)'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0xae50,
     bytes(80), bytes.fromhex(
         '280000d0089947f98802088b000140f9e00100b4290000d029e145f9e00309aa2cf8ff97'
         'e10300aae80741f8000140f9600000b4090840f920013fd6000080d2fd7b42a9f44f41a9'
         'f657c3a8c0035fd6'),
     'plugin cave: sink(getDetectFlags()) -> clean event push'),
    (r'Frameworks\build-info.framework\build-info', 0x760200,
     bytes.fromhex('e1040090'), RET,
     'build-info addSubview: -> no-op (overlay kill)'),
    (r'Frameworks\build-info.framework\build-info', 0x760d20,
     bytes.fromhex('e1040090'), RET,
     'build-info makeKeyAndVisible -> no-op (overlay kill)'),
    (r'Frameworks\build-info.framework\build-info', 0x761460,
     bytes.fromhex('c10400f0'), RET,
     'build-info setRootViewController: -> no-op (overlay kill)'),
]


def sha(p):
    return hashlib.sha256(open(p, 'rb').read()).hexdigest()


def main():
    errors = []
    for rel, off, exp, rep, label in PATCHES:
        p = os.path.join(BASE, rel)
        if not os.path.exists(p):
            errors.append('missing ' + p)
            continue
        d = open(p, 'rb').read()
        got = d[off:off + len(exp)]
        if got != exp and got != rep[:len(exp)]:
            errors.append('%s @0x%x expected %s got %s' %
                          (label, off, exp.hex(), got.hex()))
    if errors:
        print('ABORT - verification failed:')
        for e in errors:
            print('  ', e)
        sys.exit(1)

    print('all %d sites verified. writing...' % len(PATCHES))
    by_file = {}
    for rel, off, exp, rep, label in PATCHES:
        by_file.setdefault(rel, []).append((off, rep, label))

    for rel, items in by_file.items():
        p = os.path.join(BASE, rel)
        d = bytearray(open(p, 'rb').read())
        before = sha(p)
        for off, rep, label in items:
            d[off:off + len(rep)] = rep
            print('  %-48s @0x%-8x %d B' % (label, off, len(rep)))
        open(p, 'wb').write(d)
        print('  file %s' % rel)
        print('    sha256 %s -> %s' % (before, sha(p)))
    print('\ndone.')


if __name__ == '__main__':
    main()
