1#!/usr/bin/env ruby 2# Sample code for ARM64 of Unicorn. Nguyen Anh Quynh <aquynh@gmail.com> 3# Ruby sample ported by Sascha Schirra <sashs82@gmail.com> 4require 'unicorn_engine' 5require 'unicorn_engine/arm64_const' 6 7include UnicornEngine 8 9# code to be emulated 10ARM64_CODE = "\xab\x01\x0f\x8b" #add x11, x13, x15 11 12# memory address where emulation starts 13ADDRESS = 0x10000 14 15 16# callback for tracing basic blocks 17$hook_block = Proc.new do |uc, address, size, user_data| 18 puts(">>> Tracing basic block at 0x%x, block size = 0x%x" % [address, size]) 19end 20 21 22# callback for tracing instructions 23$hook_code = Proc.new do |uc, address, size, user_data| 24 puts(">>> Tracing instruction at 0x%x, instruction size = %u" % [address, size]) 25end 26 27 28# Test ARM64 29def test_arm64() 30 puts("Emulate ARM64 code") 31 begin 32 # Initialize emulator in ARM mode 33 mu = Uc.new UC_ARCH_ARM64, UC_MODE_ARM 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, 0x1234) 43 mu.reg_write(UC_ARM64_REG_X13, 0x6789) 44 mu.reg_write(UC_ARM64_REG_X15, 0x3333) 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) 51 52 # emulate machine code in infinite time 53 mu.emu_start(ADDRESS, ADDRESS + ARM64_CODE.bytesize) 54 55 # now print out some registers 56 puts(">>> Emulation done. Below is the CPU context") 57 58 x11 = mu.reg_read(UC_ARM64_REG_X11) 59 x13 = mu.reg_read(UC_ARM64_REG_X13) 60 x15 = mu.reg_read(UC_ARM64_REG_X15) 61 puts(">>> X11 = 0x%x" % x11) 62 63 rescue UcError => e 64 puts("ERROR: %s" % e) 65 end 66end 67 68 69test_arm64() 70