#!/usr/bin/env python3
"""Find the enclosing function start of a build-info address (obfuscator pads starts with
'mov x16,x16' / 'mov x17,x17') and show its prologue."""
import sys, 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'
md = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)
data = open(PATH, 'rb').read()


def word(off):
    return struct.unpack_from('<I', data, off)[0]


def dis_at(va, n):
    out = []
    for i in md.disasm(data[va:va + n * 4], va):
        out.append((i.address, i.mnemonic, i.op_str))
        if len(out) >= n:
            break
    return out


def find_start(va, maxback=0x8000):
    # walk back in 4-byte steps looking for the padding pair that precedes function bodies
    for off in range(va & ~3, (va - maxback) & ~3, -4):
        w = word(off)
        # 'mov x16, x16' == ORR x16,x16,x16 -> 0xAA300BF0 ; 'mov x17, x17' -> 0xAA310BF1
        if w == 0xAA300BF0:
            w2 = word(off + 4)
            if w2 == 0xAA310BF1:
                return off
            # sometimes only x16 pad
            return off
    return None


if __name__ == '__main__':
    va = int(sys.argv[1], 16)
    st = find_start(va)
    print('enclosing start of 0x%x: %s' % (va, hex(st) if st else None))
    if st:
        for a, m, o in dis_at(st, 12):
            print('  0x%06x  %-8s %s' % (a, m, o))
