#!/usr/bin/env python3
"""
apply_patches_319.py — GSM Driver 3.19.0 (build 566) bypass patch set.

Operates on the extracted PARTIAL IPA tree (patch_src). Every site is
prologue-verified against the expected bytes before writing; a mismatch
aborts the whole run (no partial writes).

Patch families
  bshield   : violation handler + abort helper  -> return 0 (no crash, no callback)
  ScreenShield: aggregator mask/bool -> 0 at both report and return
  high_risk : gate -> false
  mock GPS  : isSimulatedBySoftware / isProducedByAccessory stubs -> false
"""
import os, sys, struct, hashlib, shutil

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

# ---- encodings ----
MOV_X0_ZR = bytes.fromhex('e0031faa')   # mov x0, xzr
MOV_X1_ZR = bytes.fromhex('e1031faa')   # mov x1, xzr
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

# (relative path, file offset, expected_hex, replacement_bytes, label)
PATCHES = [
    # --- bshield: kill the two punishment convergence points (code-identical 3.15->3.19) ---
    (r'Frameworks\bshield.framework\bshield', 0x2A3868,
     'ff8302d1fd7b09a9', MOV_X0_0 + RET, 'bshield violation handler'),
    (r'Frameworks\bshield.framework\bshield', 0x1DB0EC,
     'ffc300d1fd7b02a9', MOV_X0_0 + RET, 'bshield abort helper'),

    # --- ScreenShield aggregator: zero mask (x0) + bool (x1) at report and return ---
    ('Driver', 0x170867C, 'a00213aa', MOV_X0_ZR, 'aggregator mask -> 0 (report)'),
    ('Driver', 0x1708684, 'e10316aa', MOV_X1_ZR, 'aggregator bool -> 0 (report)'),
    ('Driver', 0x17086BC, 'a00213aa', MOV_X0_ZR, 'aggregator mask -> 0 (return)'),
    ('Driver', 0x17086C0, 'e10316aa', MOV_X1_ZR, 'aggregator bool -> 0 (return)'),

    # --- high_risk gate: force false ---
    ('Driver', 0x1709780, 'ff4302d1fc6f03a9', MOV_W0_0 + RET, 'high_risk gate -> false'),

    # --- mock GPS stubs: 5-insn objc selector trampolines -> mov w0,#0 ; ret ---
    (r'Frameworks\MDAPILayer.framework\MDAPILayer', 0x126100,
     None, MOV_W0_0 + RET + NOP + NOP + NOP, 'MDAPILayer isSimulatedBySoftware -> false'),
    (r'Frameworks\MDAPILayer.framework\MDAPILayer', 0x1260E0,
     None, MOV_W0_0 + RET + NOP + NOP + NOP, 'MDAPILayer isProducedByAccessory -> false'),
    (r'Frameworks\geolocator_apple.framework\geolocator_apple', 0x8080,
     None, MOV_W0_0 + RET + NOP + NOP + NOP, 'geolocator isSimulatedBySoftware -> false'),
    (r'Frameworks\MDOrderBusiness.framework\MDOrderBusiness', 0x234840,
     None, MOV_W0_0 + RET + NOP + NOP + NOP, 'MDOrderBusiness isSimulatedBySoftware -> false'),
]

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

def main():
    if not os.path.isdir(BASE):
        sys.exit('base tree missing: ' + BASE)
    if not os.path.isdir(BACKUP):
        print('backing up pristine tree ->', BACKUP)
        shutil.copytree(BASE, BACKUP)

    # group patches per file
    by_file = {}
    for rel, off, exp, rep, label in PATCHES:
        by_file.setdefault(rel, []).append((off, exp, rep, label))

    # verify everything first
    errors = []
    for rel, items in by_file.items():
        p = os.path.join(BASE, rel)
        if not os.path.exists(p):
            errors.append('missing ' + p); continue
        d = open(p, 'rb').read()
        for off, exp, rep, label in items:
            got = d[off:off+len(rep)].hex()
            if exp is not None and got != exp:
                errors.append('%s @0x%x expected %s got %s' % (label, off, exp, got))
            elif exp is None:
                # sanity: stub must begin with adrp (0x90xxxxxx)
                w0 = struct.unpack_from('<I', d, off)[0]
                if (w0 & 0x9F000000) != 0x90000000:
                    errors.append('%s @0x%x not an adrp stub: %08x' % (label, off, w0))
    if errors:
        print('ABORT — verification failed:')
        for e in errors:
            print('  ', e)
        sys.exit(1)

    print('all sites verified. writing patches...')
    for rel, items in by_file.items():
        p = os.path.join(BASE, rel)
        d = bytearray(open(p, 'rb').read())
        before = sha(p)
        for off, exp, 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()
