#!/usr/bin/env python3
import struct, sys
import lief

sys.stdout.reconfigure(encoding='utf-8')
path = sys.argv[1]
b = lief.MachO.parse(path).at(0)
base = b.imagebase
blob = open(path, 'rb').read()
secs = {s.name: s for s in b.sections}


def rd(va, n):
    return blob[va - base:va - base + n]


def u64(va):
    return struct.unpack('<Q', rd(va, 8))[0]


def u32(va):
    return struct.unpack('<I', rd(va, 4))[0]


def cstr(va):
    o = va - base
    e = blob.find(b'\0', o)
    return blob[o:e].decode('utf-8', 'replace')


cl = secs['__objc_classlist']
for i in range(cl.size // 8):
    cls = u64(cl.virtual_address + i * 8)
    if not cls:
        continue
    data = u64(cls + 32) & ~7
    name = cstr(u64(data + 24))
    if 'Shield' not in name:
        continue
    print('CLASS', name)
    meta = u64(cls)
    for label, c in ((' +', meta), (' -', cls)):
        cdata = u64(c + 32) & ~7
        methods = u64(cdata + 32)
        if not methods:
            continue
        fe = u32(methods)
        count = u32(methods + 4)
        rel = bool(fe & 0x80000000)
        entsize = fe & 0xffff or 12
        for k in range(count):
            e = methods + 8 + k * entsize
            if rel:
                noff = struct.unpack('<i', rd(e, 4))[0]
                sel = cstr(e + noff)
                toff = struct.unpack('<i', rd(e + 4, 4))[0]
                types = cstr(e + 4 + toff)
                ioff = struct.unpack('<i', rd(e + 8, 4))[0]
                imp = e + 8 + ioff
            else:
                sel = cstr(u64(e))
                types = cstr(u64(e + 8))
                imp = u64(e + 16)
            print('  %s %-28s %-18s imp 0x%x' % (label, sel, types, imp - base))
