#!/usr/bin/env python3
"""Build 61 - build 59 + zero the detection-flags accumulator in the Driver.

The Driver function at ~0x1708xxx assembles the shield's check-result bitmask
(each failing check sets a byte: 0x100/0x10000/0x1000000/0x100000000/...) and
delivers it via (1) a call to 0x1707e4c and (2) its return value.

Zeroing the accumulator (mov x0,xzr / mov x1,xzr at the two delivery points)
reports "all checks clean" to the engine - semantically the legit-app state.

Build 55 had these same 4 sites PLUS two function-destroying neuters
(0x22C740 -> ret, 0x1709780 -> mov w0,#0;ret) and aborted on iOS 27; this build
tests whether the accumulator zeroing ALONE is safe and sufficient.
"""
import os, sys, struct, zipfile, json

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

IPA45 = r'E:\ios\GSMDriver-3.19.0-patched45-unsigned.ipa'
PARTIAL_IPA = r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa'
DUMPDIR = r'E:\ios\work319\dump319'
APP = r'E:\ios\work319\patch_src\Payload\Driver.app'

FROM45 = ['Frameworks/bshield.framework/bshield',
          'Frameworks/MDAPILayer.framework/MDAPILayer',
          'Frameworks/geolocator_apple.framework/geolocator_apple',
          'Frameworks/MDOrderBusiness.framework/MDOrderBusiness',
          'Frameworks/MDMap.framework/MDMap',
          'Frameworks/flutter_bshield_callback.framework/flutter_bshield_callback']
DIRTY4 = ['Frameworks/FirebaseCoreExtension.framework/FirebaseCoreExtension',
          'Frameworks/MapboxCoreNavigationObjC.framework/MapboxCoreNavigationObjC',
          'Frameworks/MapboxDirectionsObjc.framework/MapboxDirectionsObjc',
          'Frameworks/MapboxNavigationObjC.framework/MapboxNavigationObjC']

# (offset, original bytes, replacement bytes) in the Driver
ACC_SITES = [
    (0x170867C, 'a00213aa', 'e0031faa'),  # orr x0, x21, x19  -> mov x0, xzr
    (0x1708684, 'e10316aa', 'e1031faa'),  # mov x1, x22       -> mov x1, xzr
    (0x17086BC, 'a00213aa', 'e0031faa'),  # orr x0, x21, x19  -> mov x0, xzr
    (0x17086C0, 'e10316aa', 'e1031faa'),  # mov x1, x22       -> mov x1, xzr
]


def find_enc(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:
            co, cs, ci = struct.unpack_from('<3I', d, off + 8)
            return co, cs, ci, off
        off += sz
    return None, None, None, None


def main():
    z45 = zipfile.ZipFile(IPA45)
    zp = zipfile.ZipFile(PARTIAL_IPA)
    prefixes = {}
    for z in (z45, zp):
        for n in z.namelist():
            if n.endswith('Driver.app/Info.plist'):
                prefixes[z] = n[:n.rfind('/')]
                break

    dumps = {}
    for fn in os.listdir(DUMPDIR):
        if fn.endswith('.bin'):
            dumps[fn[:-4]] = os.path.join(DUMPDIR, fn)

    done, n45, ncrypt, nacc = 0, 0, 0, 0
    for n in sorted(zp.namelist()):
        if not n.startswith(prefixes[zp] + '/'):
            continue
        rel = n[len(prefixes[zp]) + 1:]
        if not rel or rel.endswith('/') or rel.startswith('PlugIns/'):
            continue
        try:
            head = zp.open(n).read(4)
        except Exception:
            continue
        if head != b'\xcf\xfa\xed\xfe':
            continue

        if rel == 'Driver':
            d = bytearray(zp.read(n))
            for off, orig, rep in ACC_SITES:
                nb = len(orig) // 2
                cur = bytes(d[off:off + nb]).hex()
                if cur != orig:
                    sys.exit('ACC SITE MISMATCH Driver @0x%x: %s != %s' % (off, cur, orig))
                d[off:off + nb] = bytes.fromhex(rep)
                nacc += 1
            print('Driver: %d accumulator sites zeroed' % nacc)
        elif rel in FROM45:
            d = bytearray(z45.read(prefixes[z45] + '/' + rel))
            n45 += 1
        else:
            d = bytearray(zp.read(n))

        co, cs, ci, coff = find_enc(bytes(d))
        if co is None:
            continue
        if ci != 0:
            struct.pack_into('<I', d, coff + 16, 0)
        if rel in DIRTY4 and cs > 0:
            mem = open(dumps[os.path.basename(rel)], 'rb').read()
            d[co:co + cs] = mem[co:co + cs]
            ncrypt += 1

        dst = os.path.join(APP, rel.replace('/', os.sep))
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        open(dst, 'wb').write(bytes(d))
        done += 1

    print('processed: %d binaries (from45: %d, crypt-fixed: %d, acc-sites: %d)'
          % (done, n45, ncrypt, nacc))

    exp = [{'rel': 'Driver', 'off': off, 'exp': rep} for off, orig, rep in ACC_SITES]
    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned
    for rel, off, ex in make_unsigned.CHECKS:
        reln = rel.replace('\\', '/')
        if reln in FROM45:
            data = z45.read(prefixes[z45] + '/' + reln)
            if data[off:off + len(ex) // 2].hex() == ex:
                exp.append({'rel': reln, 'off': off, 'exp': ex})
    json.dump(exp, open(r'E:\ios\work319\expected_checks.json', 'w'), indent=1)
    print('expected_checks.json written (%d sites)' % len(exp))


if __name__ == '__main__':
    main()
