#!/usr/bin/env python3
"""Find call sites of LAZY stubs (la_symbol_ptr-backed) preceded by sentinel checks."""
import struct, sys
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
P = r'patch_src\Payload\Driver.app\Driver'
b = lief.MachO.parse(P).at(0)
base = b.imagebase
d = open(P, 'rb').read()
text = b.get_section('__text')
lo, hi = text.virtual_address, text.virtual_address + text.size
STUB_LO, STUB_HI = 0x1018fcedc, 0x10190cd10
LA_PAGE = 0x101ed0000

md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
md.skipdata = True

stub_kind = {}  # stub addr -> 'lazy' | 'got'
insns = list(md.disasm(d[lo - base:hi - base], lo))
print('insns:', len(insns))

sites = []
known = {0x1018fc6e8, 0x10190c47c, 0x1018fe118, 0x1018fe484}
known_sites = {0x3281c, 0x31fa8, 0x333cc, 0x35e4b4, 0x3b8e0c, 0x5de9c8, 0x626ea0}

for idx, ins in enumerate(insns):
    if ins.mnemonic != 'bl' or not ins.operands or ins.operands[0].type != capstone.arm64.ARM64_OP_IMM:
        continue
    t = ins.operands[0].imm
    if not (STUB_LO <= t < STUB_HI):
        continue
    kind = stub_kind.get(t)
    if kind is None:
        # disassemble the stub: adrp x16, page ; ldr x16,[x16,#off] ; br x16
        si = list(md.disasm(d[t - base:t - base + 12], t))
        kind = 'lazy' if (len(si) >= 2 and si[0].mnemonic == 'adrp' and
                          si[0].operands[1].imm & ~0xFFF == LA_PAGE) else 'got'
        stub_kind[t] = kind
    if kind != 'lazy':
        continue
    # lazy import call: check window for sentinel fingerprint
    window = insns[max(0, idx - 8):idx]
    cmn1 = any(i.mnemonic == 'cmn' and len(i.operands) == 2 and
               i.operands[1].type == capstone.arm64.ARM64_OP_IMM and
               i.operands[1].imm == 1 for i in window)
    branch = None
    for i in window:
        if i.mnemonic in ('b.ne', 'b.eq', 'cbz', 'cbnz', 'tbz', 'tbnz'):
            branch = (i.mnemonic, i.address, i.operands[-1].imm if
                      i.operands[-1].type == capstone.arm64.ARM64_OP_IMM else None)
    sites.append((ins.address - base, t, cmn1, branch))

print('lazy-import call sites:', len(sites))
flagged = [s for s in sites if s[2] or (s[3] and s[3][2] is not None and abs(s[3][2] - s[3][1]) < 0x60)]
print('flagged (sentinel nearby):', len(flagged))
for a, t, c, br in flagged:
    mark = ''
    if a in known_sites:
        mark = ' <-- ALREADY PATCHED'
    if t in known:
        mark += ' <-- CONFIRMED ABORT'
    print('  %#x stub %#x cmn1=%s br=%s%s' % (a, t, c, br, mark))
