#!/usr/bin/env python3
"""Locate the REAL symtab/strtab inside the memory __LINKEDIT of the dumped Driver.

The LC_SYMTAB offsets in the rebuilt file point at a zeroed region, but the memory
image clearly holds dense symbol-name content. Find it by looking for a long run of
consecutive NUL-terminated identifier strings (that is what a strtab looks like),
then locate the matching nlist array (16-byte records whose n_strx points back into
that run) and the indirect symbol table."""
import sys, re, struct

sys.stdout.reconfigure(encoding='utf-8')
d = open(r'E:\ios\work319\dump319\Driver.bin', 'rb').read()
lo, hi = 0x20a8000, 0x2313fa0
seg = d[lo:hi]

# 1) find dense identifier runs: >= 40 consecutive printable+NUL strings
best = []
for m in re.finditer(rb'(?:[A-Za-z_$][A-Za-z0-9_$]{3,60}\x00){20,}', seg):
    best.append((m.start(), m.end() - m.start(), len(best)))
best.sort(key=lambda t: -t[1])
print('dense identifier runs:', len(best))
for s, l, _ in best[:6]:
    print('   mem 0x%08x len 0x%x' % (lo + s, l))
    print('      start:', repr(seg[s:s + 90]))

# 2) for the biggest run, try to locate an nlist array pointing into it
if best:
    s0, l0, _ = best[0]
    strtab_abs = lo + s0          # absolute offset in the dump
    print('\nprobing for an nlist array whose n_strx lands inside that run...')
    found = []
    for off in range(lo, hi - 16, 4):
        strx, = struct.unpack_from('<I', d, off)
        if strx < 8 or strx >= l0:
            continue
        # candidate nlist record: n_strx at +0, n_type at +4 should look sane
        ntype = d[off + 4]
        if ntype & 0xE0 != 0xE0 and ntype != 0:      # N_EXT or N_PEXT bits
            continue
        found.append(off)
        if len(found) >= 3:
            break
    for f in found:
        print('   candidate nlist array at mem 0x%08x' % f)
        # walk back to the array start: consecutive records whose n_strx are valid
        start = f
        while start > lo:
            strx, = struct.unpack_from('<I', d, start - 16)
            if strx < l0 and d[start - 16 + 4] & 0xE0:
                start -= 16
            else:
                break
        cnt = (f - start) // 16 + 400
        print('      array start ~mem 0x%08x' % start)
        for i in range(6):
            strx, ntype, nsect, ndesc, val = struct.unpack_from('<IBBHQ', d, start + i * 16)
            e = d.find(b'\x00', strtab_abs + strx)
            nm = d[strtab_abs + strx:e]
            print('        sym[%d] %s' % (i, nm[:60]))
        print('      dump-relative offset of array start: 0x%x' % start)
