#!/usr/bin/env python3
import re
import subprocess
import sys

SECTION_RE = re.compile(r"^Section\n\s+sectname (.+)\n\s+segname (.+)\n\s+addr (0x[0-9A-Fa-f]+)\n\s+size (0x[0-9A-Fa-f]+)\n\s+offset (\d+)\n[\s\S]*?flags (0x[0-9A-Fa-f]+)")

S_NON_LAZY_SYMBOL_POINTERS = 0x6
S_LAZY_SYMBOL_POINTERS = 0x7

def parse_sections(path):
    out = subprocess.check_output(["otool", "-l", path], text=True, stderr=subprocess.DEVNULL)
    sections = []
    for match in SECTION_RE.finditer(out):
        sectname, segname, addr, size, offset, flags = match.groups()
        flags_val = int(flags, 16)
        sect_type = flags_val & 0xFF
        sections.append({
            "sectname": sectname.strip(),
            "segname": segname.strip(),
            "addr": int(addr, 16),
            "size": int(size, 16),
            "offset": int(offset),
            "flags": flags_val,
            "type": sect_type,
        })
    return sections

def main(paths):
    if not paths:
        print("Usage: scan_macho_pointers.py <mach-o> [<mach-o> ...]")
        return 1
    for p in paths:
        try:
            secs = parse_sections(p)
        except Exception as e:
            print(f"[!] Failed to parse {p}: {e}")
            continue
        print(f"\n=== {p} ===")
        found = False
        for s in secs:
            writable = (s["segname"] == "__DATA")
            t = s["type"]
            if t in (S_NON_LAZY_SYMBOL_POINTERS, S_LAZY_SYMBOL_POINTERS):
                found = True
                kind = "non-lazy" if t == S_NON_LAZY_SYMBOL_POINTERS else "lazy"
                wr = "WRITABLE" if writable else "READ-ONLY"
                print(f"- {s['segname']},{s['sectname']} {kind} ptrs @ vm {s['addr']:#x}, size {s['size']:#x}, fileoff {s['offset']} ({wr})")
        if not found:
            print("(no pointer sections found)")
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

