#!/usr/bin/env python3
"""Build 46: give the 5 unbindable Swift metadata accessors a working
implementation, without needing dyld to bind anything.

  * cave  = file 0x6600 (padding after the load commands, ~6.6 KB free)
  * VWT   = file 0x1fffb80 (zero run inside __DATA, writable at runtime)
  * stub  = `b cave_init` (+2 nops) so EVERY caller of the broken import gets
            a valid value-type metadata (size/stride 0x800) in x0.

cave_init is position-independent (adrp/add), so it is correct under ASLR:
  x8 = &VWT (__data), x9 = ret gadget, fill VWT, build metadata at VWT+0x58.
"""
import struct, json, sys

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

PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
d = bytearray(open(PATH, 'rb').read())

CAVE = 0x6600                 # file offset == VA-0x100000000
VWT = 0x1fffb80               # file offset inside __data zero run
SIZE = 0x800
STUBS = [0x18FE118, 0x18FE484, 0x19038A8, 0x18FE550, 0x18FE508]

BASE = 0x100000000


def adrp(rd, target_va, pc_va):
    imm = ((target_va & ~0xFFF) - (pc_va & ~0xFFF)) >> 12
    assert -(1 << 20) <= imm < (1 << 20), 'adrp range'
    field = imm & 0x1FFFFF
    return 0x90000000 | ((field & 3) << 29) | ((field >> 2) << 5) | rd


def add_imm(rd, rn, imm):
    assert 0 <= imm < 0x1000
    return 0x91000000 | (imm << 10) | (rn << 5) | rd


def str_imm_x(rt, rn, imm):
    assert imm % 8 == 0
    return 0xF9000000 | ((imm // 8) << 10) | (rn << 5) | rt


def str_imm_w(rt, rn, imm):
    assert imm % 4 == 0
    return 0xB9000000 | ((imm // 4) << 10) | (rn << 5) | rt


def movz_w(rd, imm):
    assert 0 <= imm < 0x10000
    return 0x52800000 | (imm << 5) | rd


def b(target_off, pc_off):
    off = (target_off - pc_off) >> 2
    assert -(1 << 25) <= off < (1 << 25), 'b range'
    return 0x14000000 | (off & 0x03FFFFFF)


# ---- find a `ret` gadget in __text (4-aligned) ----
ret_off = None
pat = b'\xc0\x03\x5f\xd6'
i = 0x8000
while i < 0x1800000:
    j = d.find(pat, i)
    if j < 0:
        break
    if j % 4 == 0:
        ret_off = j
        break
    i = j + 1
assert ret_off, 'no ret gadget found'
print('ret gadget @ file 0x%x (va 0x%x)' % (ret_off, ret_off + BASE))

RG = ret_off + BASE
X = VWT + BASE
CAVEVA = CAVE + BASE

code = []
code.append(adrp(8, X, CAVEVA))                    # adrp x8, VWT page
code.append(add_imm(8, 8, X & 0xFFF))              # add  x8, x8, #off
code.append(adrp(9, RG, CAVEVA))                   # adrp x9, ret gadget page
code.append(add_imm(9, 9, RG & 0xFFF))             # add  x9, x9, #off
for k in range(8):                                 # 8 x str x9,[x8,#0x00..0x38]
    code.append(str_imm_x(9, 8, k * 8))
code.append(movz_w(10, SIZE))                      # mov w10, #0x800
code.append(str_imm_w(10, 8, 0x40))                # size
code.append(str_imm_w(10, 8, 0x44))                # stride
code.append(add_imm(0, 8, 0x58))                   # x0 = &metadata
code.append(str_imm_x(8, 8, 0x50))                 # meta[-8] = &VWT
code.append(movz_w(11, 2))                         # kind = struct
code.append(str_imm_w(11, 8, 0x58))
code.append(str_imm_x(31, 8, 0x60))                # descriptor = 0
code.append(0xd65f03c0)                            # ret

blob = b''.join(struct.pack('<I', w) for w in code)
print('cave code: %d bytes at file 0x%x' % (len(blob), CAVE))
print('  ' + blob[:32].hex(' ') + ' ...')

# ---- write the cave ----
d[CAVE:CAVE + len(blob)] = blob

# ---- patch the stubs ----
out = {}
for s in STUBS:
    w = [b(CAVE, s), 0xd503201f, 0xd503201f]       # b cave ; nop ; nop
    body = b''.join(struct.pack('<I', x) for x in w)
    d[s:s + 12] = body
    out['0x%x' % s] = body.hex()
    print('stub 0x%08x -> %s' % (s, body.hex()))

open(PATH, 'wb').write(bytes(d))
json.dump(out, open(r'E:\ios\work319\stub46.json', 'w'))
print('WROTE %s (cave + %d stubs)' % (PATH, len(STUBS)))
print('VWT VA 0x%x  META VA 0x%x  size=%d' % (X, X + 0x58, SIZE))
