#!/usr/bin/env python3
"""Find usable Swift value-type metadata in the shipped Driver binary.

A value metadata object P satisfies:
  u64[P-8]  = VWT pointer (in-image)
  u32[P]    = MetadataKind (1 tuple, 2 struct, 3 enum, 4 optional, ...)
  u64[P+8]  = TypeDescriptor*
and the VWT at that pointer has:
  u32[VWT+0x40] = size,  u32[VWT+0x44] = stride >= size
  u32[VWT+0x48] = flags
We rank candidates by size because the stub replacement must allocate at least
as much stack as the real type needed.
"""
import struct, sys

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

PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
d = open(PATH, 'rb').read()
N = len(d)
BASE = 0x100000000


def u64(o):
    return struct.unpack_from('<Q', d, o)[0]


def u32(o):
    return struct.unpack_from('<I', d, o)[0]


def in_img(v):
    return BASE <= v < BASE + N


KINDS = {1: 'tuple', 2: 'struct', 3: 'enum', 4: 'optional', 5: 'foreign_class',
         64: 'class', 65: 'objcref'}

cands = []
# scan plausible __DATA_CONST/__DATA range for speed, fall back to whole file
lo, hi = 0x1ec0000, N
o = lo
step = 4
while o < hi - 0x60:
    k = u32(o)
    if k in (1, 2, 3, 4):
        vw = u64(o - 8)
        if in_img(vw):
            vo = vw - BASE
            if vo + 0x50 <= N:
                size = u32(vo + 0x40)
                stride = u32(vo + 0x44)
                flags = u32(vo + 0x48)
                if 0 < size <= 65536 and stride >= size and flags < 0x10000:
                    # VWT function slots must be 0, in-image, or shared-cache-like
                    ok = True
                    ptrs = []
                    for i in range(8):
                        p = u64(vo + i * 8)
                        ptrs.append(p)
                        if p == 0:
                            continue
                        if in_img(p):
                            continue
                        if p >= 0x180000000 and p < 0x280000000:
                            continue
                        ok = False
                        break
                    if ok:
                        cands.append((size, stride, o, vo, k, flags, ptrs))
    o += step

cands.sort(key=lambda c: -c[0])
print('candidates found:', len(cands))
print('\ntop 15 by size:')
for size, stride, o, vo, k, flags, ptrs in cands[:15]:
    print('  meta@file 0x%08x (va 0x%08x) kind=%-8s size=%-6d stride=%-6d flags=0x%x vwt@0x%08x'
          % (o, o + BASE, KINDS.get(k, k), size, stride, flags, vo))
    print('      vwt ptrs: ' + ' '.join('0x%x' % p for p in ptrs))

# also show a few small-but-valid ones for reference
print('\nsmallest 5:')
for size, stride, o, vo, k, flags, ptrs in cands[-5:]:
    print('  meta@file 0x%08x kind=%-8s size=%-6d vwt@0x%08x' % (o, KINDS.get(k, k), size, vo))
