unicorn-engine / unicorn

Unicorn CPU emulator framework (ARM, AArch64, M68K, Mips, Sparc, PowerPC, RiscV, S390x, TriCore, X86)
http://www.unicorn-engine.org
GNU General Public License v2.0
7.33k stars 1.31k forks source link

Presence of UC_HOOK_MEM_WRITE hook breaks code emulation #1911

Closed ntqbit closed 6 months ago

ntqbit commented 7 months ago

Hello.

The following code snippet:

from unicorn import *
from unicorn.x86_const import *

def mem_write_hook(uc, a, b, c, d, e):
    pass

def run(with_memwrite_hook):
    uc = Uc(UC_ARCH_X86, UC_MODE_64)
    uc.mem_map(0xb5858fd000, 0x1000, UC_PROT_ALL)
    uc.mem_write(0xb5858fd667, b'\x5E\x00\x00\x00')

    if with_memwrite_hook:
        uc.hook_add(UC_HOOK_MEM_WRITE, mem_write_hook, begin=0x1, end=0x2)

    uc.mem_map(0x00007FF7F8D00000, 0x1000000, UC_PROT_ALL)
    uc.mem_write(0x00007FF7F8FE70D5, b"\xD3\xB4\x04\x5D\x00\x03\xC8")

    uc.reg_write(UC_X86_REG_RAX, 0x37FCFFB2)
    uc.reg_write(UC_X86_REG_CL, 0x46)
    uc.reg_write(UC_X86_REG_EFLAGS, 0x83)
    uc.reg_write(UC_X86_REG_RSP, 0xB5858FD658)

    uc.emu_start(0x00007FF7F8FE70D5, 0, 0, 1)

    print('EFLAGS:', hex(uc.reg_read(UC_X86_REG_EFLAGS)))

run(False)
run(True)

Outputs:

EFLAGS: 0x2
EFLAGS: 0x803

Unicorn version: 2.0

It looks like simply presence of UC_HOOK_MEM_WRITE hook breaks code emulation even if the hook is set on unrelated to the code emulation memory (in the code snippet hook is at at memory region 0x1-0x2).

ntqbit commented 6 months ago

Appears to be fixed on dev branch in https://github.com/unicorn-engine/unicorn/commit/c889258d8eadf268325d31958b5f2c5ea99f73bb.