#!/usr/bin/env python3
"""Rebuild the classic LC_DYLD_INFO_ONLY lazy-bind stream for the properly dumped
Driver.

Why: the memory image's lazy-bind region was zeroed by dyld after processing, and
the on-disk dump had the whole dyld_info zeroed. With the real symtab recovered
from the memory __LINKEDIT we can reconstruct the stream exactly:

  for every slot of __la_symbol_ptr, in order:
      0x3E                                   SET_DYLIB_SPECIAL_IMM(-2)  flat lookup
      0x40 <name> 00                         SET_SYMBOL_TRAILING_FLAGS_IMM
      0x80 <uleb seg> <uleb off>             SET_SEGMENT_AND_OFFSET_ULEB
      0xA0                                   DO_BIND
      0x00                                   DONE

Flat lookup (-2) means dyld searches every loaded image for the symbol, so no
dylib ordinal is needed.

The stream is written over the zeroed region that lazy_bind_off already points
at, and lazy_bind_size is updated to the real length.
"""
import struct, sys

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

PATH = r'E:\ios\work319\proper319\Driver'


def uleb(n):
    out = bytearray()
    while True:
        b = n & 0x7F
        n >>= 7
        if n:
            out.append(b | 0x80)
        else:
            out.append(b)
            return bytes(out)


def parse_load_commands(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    segs, sections = [], []
    dysym = sym = None
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x19:  # LC_SEGMENT_64
            nm = d[off + 8:off + 24].rstrip(b'\0').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off + 24)
            nsects, = struct.unpack_from('<I', d, off + 64)
            segs.append(dict(index=len(segs), name=nm, vmaddr=vmaddr, vmsize=vmsize,
                             fileoff=fileoff, filesize=filesize, nsects=nsects))
            so = off + 72
            for i in range(nsects):
                sect = d[so:so + 16].rstrip(b'\0').decode()
                sg = d[so + 16:so + 32].rstrip(b'\0').decode()
                addr, asize = struct.unpack_from('<QQ', d, so + 32)
                foff = struct.unpack_from('<I', d, so + 48)[0]
                nreloc, flags, r1, r2 = struct.unpack_from('<IIII', d, so + 56)
                sections.append(dict(sect=sect, seg=sg, seg_index=len(segs) - 1, addr=addr,
                                     size=asize, fileoff=foff, flags=flags, reserved1=r1))
                so += 80
        elif cmd == 0x2:   # LC_SYMTAB
            sym = struct.unpack_from('<IIII', d, off + 8)
        elif cmd == 0xB:   # LC_DYSYMTAB
            dysym = struct.unpack_from('<' + 'I' * 18, d, off + 8)
        off += sz
    return segs, sections, sym, dysym


def main():
    d = bytearray(open(PATH, 'rb').read())
    segs, sections, sym, dysym = parse_load_commands(d)
    symoff, nsyms, stroff, strsize = sym
    indirectsymoff, nindirectsyms = dysym[12], dysym[13]
    print('segments: %s' % [s['name'] for s in segs])
    print('symtab symoff 0x%x nsyms %d stroff 0x%x strsize 0x%x' % (symoff, nsyms, stroff, strsize))
    print('dysymtab indirectsymoff 0x%x nindirectsyms %d' % (indirectsymoff, nindirectsyms))

    # find __la_symbol_ptr and the __DATA segment that contains it
    lp = next(s for s in sections if s['sect'] == '__la_symbol_ptr')
    seg = segs[lp['seg_index']]
    n_slots = lp['size'] // 8
    print('__la_symbol_ptr: fileoff 0x%x size 0x%x -> %d slots, indirect start %d, seg %s (index %d)'
          % (lp['fileoff'], lp['size'], n_slots, lp['reserved1'], seg['name'], seg['index']))

    def sym_name(idx):
        strx, typ, sect, desc, val = struct.unpack_from('<IBBHQ', d, symoff + idx * 16)
        e = d.find(b'\x00', stroff + strx)
        return d[stroff + strx:e].decode('utf-8', 'replace')

    # symbol name for each lazy pointer slot
    names = []
    for i in range(n_slots):
        si = struct.unpack_from('<I', d, indirectsymoff + (lp['reserved1'] + i) * 4)[0]
        if si >= nsyms:
            names.append(None)
        else:
            names.append(sym_name(si))
    unnamed = sum(1 for n in names if not n)
    print('slots: %d, without a name: %d' % (n_slots, unnamed))
    for i in range(6):
        print('   slot %d -> %s' % (i, names[i]))

    # build the stream
    seg_index = seg['index']
    base_fileoff = seg['fileoff']
    stream = bytearray()
    for i in range(n_slots):
        nm = names[i]
        if not nm:
            # emit a DONE-terminated no-op entry to keep the 1:1 slot mapping
            stream += b'\x00'
            continue
        stream += b'\x3e'                                   # SET_DYLIB_SPECIAL_IMM(-2) flat lookup
        stream += b'\x40' + nm.encode('utf-8') + b'\x00'    # symbol name
        slot_fileoff = lp['fileoff'] + i * 8
        rel = slot_fileoff - base_fileoff
        stream += b'\x80' + uleb(seg_index) + uleb(rel)     # SET_SEGMENT_AND_OFFSET_ULEB
        stream += b'\xa0'                                   # DO_BIND
    stream += b'\x00'                                       # DONE
    print('new lazy bind stream: %d bytes (region available 0x486d0 = %d)'
          % (len(stream), 0x486d0))
    if len(stream) > 0x486d0:
        sys.exit('stream does not fit in the existing lazy-bind region')

    # locate the dyld_info command and patch lazy_bind_off/size
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x80000022:
            cur_off, cur_size = struct.unpack_from('<II', d, off + 8 + 6 * 4)
            print('dyld_info lazy_bind_off was 0x%x size 0x%x' % (cur_off, cur_size))
            struct.pack_into('<II', d, off + 8 + 6 * 4, cur_off, len(stream))
            print('dyld_info lazy_bind_size -> 0x%x (offset kept 0x%x)' % (len(stream), cur_off))
            break
        off += sz

    # write the stream over the (currently zeroed) region
    d[cur_off:cur_off + len(stream)] = stream
    # keep the rest of the old region zero so dyld stops at our DONE
    open(PATH, 'wb').write(bytes(d))
    print('WROTE %s' % PATH)


if __name__ == '__main__':
    main()
