1#!/usr/bin/env python 2# Sample code for ARM64 of Unicorn. Nguyen Anh Quynh <aquynh@gmail.com> 3# Python sample ported by Loi Anh Tuan <loianhtuan@gmail.com> 4# AARCH64 Python sample ported by zhangwm <rustydaar@gmail.com> 5 6from __future__ import print_function 7from unicorn import * 8from unicorn.arm64_const import * 9 10 11# code to be emulated 12ARM64_CODE = b"\xab\x05\x00\xb8\xaf\x05\x40\x38" # str x11, [x13]; ldrb x15, [x13] 13 14# memory address where emulation starts 15ADDRESS = 0x10000 16 17 18# callback for tracing basic blocks 19def hook_block(uc, address, size, user_data): 20 print(">>> Tracing basic block at 0x%x, block size = 0x%x" %(address, size)) 21 22 23# callback for tracing instructions 24def hook_code(uc, address, size, user_data): 25 print(">>> Tracing instruction at 0x%x, instruction size = 0x%x" %(address, size)) 26 27 28# Test ARM64 29def test_arm64(): 30 print("Emulate ARM64 Big-Endian code") 31 try: 32 # Initialize emulator in ARM mode 33 mu = Uc(UC_ARCH_ARM64, UC_MODE_ARM | UC_MODE_BIG_ENDIAN) 34 35 # map 2MB memory for this emulation 36 mu.mem_map(ADDRESS, 2 * 1024 * 1024) 37 38 # write machine code to be emulated to memory 39 mu.mem_write(ADDRESS, ARM64_CODE) 40 41 # initialize machine registers 42 mu.reg_write(UC_ARM64_REG_X11, 0x12345678) 43 mu.reg_write(UC_ARM64_REG_X13, 0x10008) 44 mu.reg_write(UC_ARM64_REG_X15, 0x33) 45 46 # tracing all basic blocks with customized callback 47 mu.hook_add(UC_HOOK_BLOCK, hook_block) 48 49 # tracing all instructions with customized callback 50 mu.hook_add(UC_HOOK_CODE, hook_code, begin=ADDRESS, end=ADDRESS) 51 52 # emulate machine code in infinite time 53 mu.emu_start(ADDRESS, ADDRESS + len(ARM64_CODE)) 54 55 # now print out some registers 56 print(">>> Emulation done. Below is the CPU context") 57 print(">>> As big endian, X15 should be 0x12:") 58 59 x11 = mu.reg_read(UC_ARM64_REG_X11) 60 x13 = mu.reg_read(UC_ARM64_REG_X13) 61 x15 = mu.reg_read(UC_ARM64_REG_X15) 62 print(">>> X15 = 0x%x" %x15) 63 64 except UcError as e: 65 print("ERROR: %s" % e) 66 67 68if __name__ == '__main__': 69 test_arm64() 70