#!/usr/bin/env python3
"""Decode LC_DYLD_INFO lazy-bind opcode stream -> per-la_symbol_ptr import names."""
import struct, sys
sys.stdout.reconfigure(encoding='utf-8')

PATH = r'patch_src\Payload\Driver.app\Driver'
d = open(PATH, 'rb').read()
base = 0x100000000

ncmds = struct.unpack_from('<I', d, 16)[0]
off = 32
info = None
for _ in range(ncmds):
    cmd, size = struct.unpack_from('<II', d, off)
    if cmd in (0x22, 0x80000022):  # LC_DYLD_INFO / LC_DYLD_INFO_ONLY
        info = struct.unpack_from('<10I', d, off + 8)
    off += size
rebase_off, rebase_size, bind_off, bind_size, weak_off, weak_size, lazy_off, lazy_size, exp_off, exp_size = info
print('lazy bind at %#x size %#x' % (lazy_off, lazy_size))

pos = lazy_off
entries = []
cur = []
name = None
while pos < lazy_off + lazy_size:
    op = d[pos]
    imm = op & 0x0F
    opc = op & 0xF0
    if opc == 0x00:  # DONE
        pos += 1
        entries.append(name)
        name = None
    elif opc == 0x10 or opc == 0x80:  # set segment and offset (uleb)
        pos += 1
        shift = 0
        while True:
            b = d[pos]; pos += 1
            shift += 7
            if not (b & 0x80):
                break
    elif opc == 0x50:  # set symbol trailing flags imm (name follows)
        pos += 1
        e = d.find(b'\0', pos)
        name = d[pos:e].decode()
        pos = e + 1
    elif opc == 0x20:  # do bind
        pos += 1
    elif opc == 0x60 or opc == 0x70 or opc == 0x40:  # type/addend imm
        pos += 1
    elif opc == 0x90:  # add addr uleb
        pos += 1
        while True:
            b = d[pos]; pos += 1
            if not (b & 0x80):
                break
    elif opc == 0xA0:  # do bind add addr uleb
        pos += 1
        while True:
            b = d[pos]; pos += 1
            if not (b & 0x80):
                break
    elif opc == 0xB0:  # do bind add addr imm scaled
        pos += 1
    elif opc == 0xC0:  # do bind uleb times skipping uleb
        pos += 1
        while True:
            b = d[pos]; pos += 1
            if not (b & 0x80):
                break
        while True:
            b = d[pos]; pos += 1
            if not (b & 0x80):
                break
    else:
        print('unknown opcode %#x at %#x' % (op, pos))
        break
print('lazy entries decoded:', len(entries))
for idx in (389, 462):
    print('la_symbol_ptr[%d] -> %s' % (idx, entries[idx] if idx < len(entries) else '?'))
# also print neighbors for context
for idx in range(385, 394):
    print('  [%d] %s' % (idx, entries[idx] if idx < len(entries) else '?'))
