#!/usr/bin/env python3
"""Assemble the onListen clean-event cave with keystone; verify with capstone."""
import struct, sys
import capstone
from keystone import Ks, KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN

sys.stdout.reconfigure(encoding='utf-8')

HOOK = 0x40b0
CAVE = 0xae50
ks = Ks(KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN)

asm = f"""
    adrp x8, #0x10000
    ldr  x8, [x8, #0xf30]
    add  x8, x20, x8
    ldr  x0, [x8]
    cbz  x0, done
    adrp x9, #0x10000
    ldr  x9, [x9, #0xbc0]
    mov  x0, x9
    bl   0x8f20
    mov  x1, x0
    ldr  x8, [sp], #16
    ldr  x0, [x8]
    cbz  x0, done2
    ldr  x9, [x0, #0x10]
    blr  x9
done2:
    mov  x0, #0
    ldp  x29, x30, [sp, #0x20]
    ldp  x20, x19, [sp, #0x10]
    ldp  x22, x21, [sp], #0x30
done:
    ret
"""

# pass 1: get sizes by assembling with placeholder offsets resolved after layout:
# keystone resolves branches automatically given the base address.
enc, count = ks.asm(asm, CAVE)
blob = bytes(enc)
print('assembled %d instructions, %d bytes' % (count, len(blob)))

md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
for i in md.disasm(blob, CAVE):
    print('%#x %-8s %s' % (i.address, i.mnemonic, i.op_str))

hook = ks.asm('b %#x' % CAVE, HOOK)[0]
print('hook bytes:', bytes(hook).hex())
print('cave bytes:', blob.hex())
open(r'E:\ios\work319\cave.bin', 'wb').write(blob)
