#!/usr/bin/env python3
"""Build 46: use the PROPERLY DUMPED Driver (valid dyld_info + real symtab) and
re-apply only the detector-neuter patches that we deliberately keep. Everything
else in the new Driver is already pristine, which is exactly what the real launch
path needs.

Also verifies every Driver patch site that make_unsigned.py checks.
"""
import struct, sys

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

SRC = r'E:\ios\work319\proper319\Driver'
DST = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'

# detector blinding we deliberately keep (same as build 45)
NEUTERS = [
    (0x22C740, 'fa67bba9', 'c0035fd6'),                     # stp x26,x25 -> ret
    (0x1709780, 'ff4302d1fc6f03a9', '00008052c0035fd6'),    # sub sp,sp,#0x90 -> mov w0,#0; ret
    (0x170867C, 'a00213aa', 'e0031faa'),                    # orr x0,x21,x19 -> mov x0,xzr
    (0x1708684, None, 'e1031faa'),
    (0x17086BC, 'a00213aa', 'e0031faa'),
    (0x17086C0, None, 'e1031faa'),
]

# sites that must ALREADY be pristine in the fresh dump (the real launch path)
MUST_BE_PRISTINE = [
    (0x031FA8, '37316394'), (0x03281C, '3f2e6394'), (0x032BF8, 'a03b00b4'),
    (0x0333CC, '2e2c6394'), (0x035E4B4, '197f5694'), (0x03B8E0C, '9e155594'),
    (0x05DE9C8, '48774c94'), (0x18FE118, '902e00d0'), (0x18FE484, '902e00d0'),
    (0x18FC6E8, 'a03a00d0'), (0x190C47C, '702e00d0'),
]

d = bytearray(open(SRC, 'rb').read())
print('fresh dumped Driver: %d bytes' % len(d))

bad = 0
for off, want in MUST_BE_PRISTINE:
    cur = bytes(d[off:off + len(want) // 2]).hex()
    if cur != want:
        print('  !! 0x%06x is %s, expected pristine %s' % (off, cur, want))
        bad += 1
print('pristine launch-path sites verified: %d/%d' % (len(MUST_BE_PRISTINE) - bad, len(MUST_BE_PRISTINE)))
if bad:
    sys.exit('the fresh dump does not match the expected pristine bytes')

for off, orig, new in NEUTERS:
    n = len(new) // 2
    cur = bytes(d[off:off + n]).hex()
    d[off:off + n] = bytes.fromhex(new)
    print('  0x%06x %s -> %s' % (off, cur[:len(new)], new))

open(DST, 'wb').write(bytes(d))
print('wrote %s' % DST)

# verify the whole Driver check set from make_unsigned
chk = open(DST, 'rb').read()
sys.path.insert(0, r'E:\ios\work319')
import make_unsigned  # noqa - just to read CHECKS
drv_checks = [c for c in make_unsigned.CHECKS if c[0] == 'Driver']
fails = []
for rel, off, exp in drv_checks:
    got = chk[off:off + len(exp) // 2].hex()
    if got != exp:
        fails.append((off, got, exp))
print('Driver check sites: %d, failures: %d' % (len(drv_checks), len(fails)))
for off, got, exp in fails:
    print('   FAIL 0x%06x got %s want %s' % (off, got, exp))
