# -*- coding: utf-8 -*-
"""Debug objc class layout of build-info, class ShieldData."""
import struct, os

PAY = r'E:\ios\dump_tool\out\Payload\Driver.app\Frameworks'
path = os.path.join(PAY, 'build-info.framework', 'build-info')
d = open(path, 'rb').read()
ncmds = struct.unpack_from('<I', d, 16)[0]
pos = 32; symtab = None; segs = []
for _ in range(ncmds):
    cmd, sz = struct.unpack_from('<II', d, pos)
    if cmd == 2:
        symtab = struct.unpack_from('<IIII', d, pos+8)
    elif cmd == 0x19:
        segname = d[pos+8:pos+24].rstrip(b'\0').decode()
        vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, pos+24)
        segs.append((segname, vmaddr, fileoff, filesize))
        print('SEG %-12s vm=%#x fo=%#x size=%#x' % (segname, vmaddr, fileoff, filesize))
    pos += sz

symoff, nsyms, stroff, strsize = symtab
smap = {}
for i in range(nsyms):
    n_strx, n_type, n_sect, n_desc, n_value = struct.unpack_from('<IBBHQ', d, symoff + i*16)
    end = d.find(b'\0', stroff + n_strx)
    name = d[stroff + n_strx:end].decode('ascii', 'ignore')
    if n_value: smap[n_value] = name

def v2f(vm):
    for segname, va, fo, fs in segs:
        if va and va <= vm < va + fs:
            return vm - va + fo
    return None

def hexdump(off, n):
    for row in range(0, n, 16):
        b = d[off+row:off+row+16]
        print('%08x  %s  %s' % (off+row, b.hex(' '), ''.join(chr(c) if 32 <= c < 127 else '.' for c in b)))

cls_addr = 0x7fd248  # _OBJC_CLASS_$_ShieldData (symbol value = vmaddr in __DATA)
cf = v2f(cls_addr)
print('\nShieldData class at vm %#x -> file %#x' % (cls_addr, cf))
hexdump(cf, 48)
isa, sup, c1, c2, bits = struct.unpack_from('<QQQQQ', d, cf)
print('isa=%#x super=%#x bits=%#x' % (isa, sup, bits))
ro = bits
rof = v2f(ro)
print('ro vm=%#x -> file=%s' % (ro, hex(rof) if rof else None))
if rof:
    hexdump(rof, 48)
    flags, s1, s2, name_rel, bm_rel = struct.unpack_from('<IIIII', d, rof)
    print('ro flags=%#x name_rel=%#x baseMethods_rel=%#x' % (flags, name_rel, bm_rel))
    name_vm = ro + name_rel
    nf = v2f(name_vm)
    if nf:
        end = d.find(b'\0', nf)
        print('class name:', d[nf:end])
    ml_vm = ro + bm_rel
    mf = v2f(ml_vm)
    print('methodlist vm=%#x file=%s' % (ml_vm, hex(mf) if mf else None))
    if mf:
        entsize, count = struct.unpack_from('<II', d, mf)
        print('entsize=%#x count=%d' % (entsize, count))
