Unicorn CPU Emulator Engine

2.1.4 · active · verified Mon Apr 13

Unicorn is a lightweight, multi-platform, multi-architecture CPU emulator framework based on QEMU. It provides Python bindings for emulating various CPU architectures (ARM, AArch64, M68K, MIPS, PowerPC, RISCV, SPARC, S390x, TriCore, X86), which is widely used in security research, reverse engineering, and dynamic binary analysis. The library is actively maintained, with the current version being 2.1.4, and releases occurring frequently to address bugs, enhance features, and improve stability.

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize the Unicorn engine for x86 32-bit architecture, map memory, write machine code, set initial register values, execute the code, and then read the final register values. The code `INC ecx; DEC edx` increments ECX and decrements EDX.

from unicorn import *
from unicorn.x86_const import *

X86_CODE32 = b'\x41\x4a' # INC ecx; DEC edx
ADDRESS = 0x1000000

print('Emulate i386 code')

try:
    # Initialize emulator in X86-32bit mode
    mu = Uc(UC_ARCH_X86, UC_MODE_32)

    # Map 2MB memory for this emulation
    mu.mem_map(ADDRESS, 2 * 1024 * 1024)

    # Write machine code to be emulated to memory
    mu.mem_write(ADDRESS, X86_CODE32)

    # Initialize machine registers
    mu.reg_write(UC_X86_REG_ECX, 0x1234)
    mu.reg_write(UC_X86_REG_EDX, 0x7890)

    # Emulate code in infinite time & unlimited instructions
    mu.emu_start(ADDRESS, ADDRESS + len(X86_CODE32))

    # Print out some registers
    print('Emulation done. Below is the CPU context')
    r_ecx = mu.reg_read(UC_X86_REG_ECX)
    r_edx = mu.reg_read(UC_X86_REG_EDX)
    print(f'>>> ECX = 0x{r_ecx:x}')
    print(f'>>> EDX = 0x{r_edx:x}')

except UcError as e:
    print(f'ERROR: {e}')

view raw JSON →