#!/usr/bin/env python3
"""Find candidate writers of the flag field at [reg+0x80] in build-info:
STRB (imm, unsigned) with imm12=0x80, and STR w (imm) with imm12=0x80/0x20 (byte 0x80 of a word field)."""
import struct
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN

PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Frameworks\build-info.framework\build-info'
data = open(PATH, 'rb').read()
md = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)

hits = []
n = len(data) // 4
for idx in range(n):
    off = idx * 4
    w = struct.unpack_from('<I', data, off)[0]
    top = w >> 22
    imm = (w >> 10) & 0xFFF
    # STRB (imm, unsigned offset): size=00 op=1 V=0 opc=01 -> 0b0011100100 = 228
    if top == 228 and imm == 0x80:
        hits.append((off, 'strb'))
    # STR (imm, unsigned offset) 32-bit: size=10 -> 0b1011100100 = 740
    elif top == 740 and imm == 0x20:
        hits.append((off, 'strw+0x20'))
    # STRB immediate with imm9 (post/pre) LDUR/STUR forms: 0b00111000000 imm9 00 Rn Rt
    elif (w >> 21) == 0b00111000000 and ((w >> 12) & 0x1FF) == 0x80 and ((w >> 10) & 3) in (0, 2):
        hits.append((off, 'sturb-imm9'))

print('candidate flag writes:', len(hits))
for off, kind in hits[:60]:
    txt = []
    for i in md.disasm(data[max(0, off - 12):off + 16], max(0, off - 12)):
        mark = '>>' if i.address == off else '  '
        txt.append('%s0x%06x %s %s' % (mark, i.address, i.mnemonic, i.op_str))
    print('--- %s @ 0x%x' % (kind, off))
    for t in txt:
        print('   ' + t)
