#!/usr/bin/env python3
"""Find the bind-stream entries that target __la_symbol_ptr slots.

__la_symbol_ptr lives in the __DATA segment (index 3) at segment offsets
0x0000..0xa8a8. A classic bind entry targeting it contains
    0x80 <uleb 3> <uleb offset-in-__DATA>
preceded by 0x40 <symbol name> NUL and followed by 0xA0 (DO_BIND).

Scan the whole on-disk original Driver for that shape and report the names."""
import sys, struct

sys.stdout.reconfigure(encoding='utf-8')
d = open(r'E:\ios\work319\patch_src_orig\Driver', 'rb').read()

# segment table (for mapping segment index -> fileoff) and the name of segment 3
ncmds, = struct.unpack_from('<I', d, 16)
off = 32
segs = []
for _ in range(ncmds):
    cmd, sz = struct.unpack_from('<II', d, off)
    if cmd == 0x19:
        nm = d[off + 8:off + 24].rstrip(b'\0').decode()
        vm, vs, fo, fs = struct.unpack_from('<QQQQ', d, off + 24)
        segs.append((nm, vm, fo))
    off += sz
print('segments:', [(i, n) for i, (n, v, f) in enumerate(segs)])

LP_LO, LP_HI = 0x0, 0xa8a8          # offsets within __DATA
DATA_SEG = 3

# scan for 0x80 <seg=3> <uleb off in LP range> ... 0xa0
results = []
i = 0x2040000
end = len(d) - 8
while i < end - 8:
    if d[i] == 0x80 and d[i + 1] == DATA_SEG:
        # decode the ULEB offset
        o = i + 2
        val = 0; sh = 0
        while True:
            b = d[o]; o += 1
            val |= (b & 0x7F) << sh
            sh += 7
            if not b & 0x80:
                break
        if LP_LO <= val <= LP_HI:
            # walk back to the preceding 0x40 symbol opcode
            j = i - 1
            name = None
            while j > i - 200:
                if d[j] == 0x40:
                    k = d.find(b'\x00', j + 1)
                    if k > 0 and k < i:
                        name = d[j + 1:k].decode('latin1')
                j -= 1
            # next byte should be 0xA0 (DO_BIND)
            nxt = d[o]
            results.append((val, name, nxt))
            i = o
    i += 1

print('bind entries targeting __la_symbol_ptr:', len(results))
for val, nm, nxt in results[:20]:
    print('   seg_off 0x%04x (slot %d)  next=0x%02x  name=%s' % (val, val // 8, nxt, (nm or '?')[:60]))

# cross-check: does slot 389 (seg offset 0xc28) appear?
want = 0xc28
hit = [r for r in results if r[0] == want]
print('\nentry for slot 389 (seg_off 0xc28):', hit if hit else 'NOT FOUND')
