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

Relaxed criteria: the VWT pointer at [P-8] may be an in-image address OR a
shared-cache address left over from the decryption dump (those are valid at
runtime on the same OS build). We only need [P] kind sane; the VWT size is
measured at runtime later.
"""
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


def looks_cache(v):
    return 0x180000000 <= v < 0x280000000


KINDS = {1: 'tuple', 2: 'struct', 3: 'enum', 4: 'optional'}

out = []
o = 0x1000
while o < N - 0x20:
    k = u32(o)
    if k in (1, 2, 3, 4):
        vw = u64(o - 8)
        tag = None
        if in_img(vw):
            tag = 'in-image'
        elif looks_cache(vw):
            tag = 'shared-cache'
        if tag:
            desc = u64(o + 8)
            out.append((o, k, vw, tag, desc))
    o += 4

print('value-metadata candidates:', len(out))
from collections import Counter
c = Counter(k for _, k, _, _, _ in out)
print('by kind:', {KINDS.get(k, k): n for k, n in c.items()})

# group by tag
t = Counter(tag for _, _, _, tag, _ in out)
print('by vwt tag:', dict(t))

# prefer struct with shared-cache VWT (definitely functional at runtime)
sel = [x for x in out if x[1] == 2 and x[3] == 'shared-cache']
print('\nstruct + shared-cache VWT:', len(sel))
for o, k, vw, tag, desc in sel[:25]:
    print('  meta@file 0x%08x  va 0x%08x  vwt=0x%012x  desc=0x%012x' % (o, o + BASE, vw, desc))

# also list a spread of in-image ones (we can validate size statically)
sel2 = [x for x in out if x[1] == 2 and x[3] == 'in-image']
print('\nstruct + in-image VWT:', len(sel2))
for o, k, vw, tag, desc in sel2[:15]:
    vo = vw - BASE
    if vo + 0x50 <= N:
        size = u32(vo + 0x40)
        stride = u32(vo + 0x44)
        print('  meta@file 0x%08x  vwt@0x%08x size=%d stride=%d' % (o, vo, size, stride))

json.dump([[o, k] for o, k, _, _, _ in out], open(r'E:\ios\work319\vtmeta_cands.json', 'w'))
print('\nwrote vtmeta_cands.json')
