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.68k stars 1.35k forks source link

x86 instruction incorrect simulation results #1862

Closed fjqisba closed 1 year ago

fjqisba commented 1 year ago

Try to simulate the following binary data: 68 80 4F FE 90 6A 00 6A 00 B9 FF FF 67 8C B8 00 00 00 00 D3 6C 04 08 72 05 B8 01 00 00 00. The assembly is this: QQ截图20230804160604 After unicorn runs,EAX is 0x0,which is wrong

wtdcode commented 1 year ago

Could you provide a reproduction script to illustrate more?

fjqisba commented 1 year ago
from unicorn import *
from unicorn.x86_const import *

X86_CODE32 = b"\x68\x80\x4F\xFE\x90\x6A\x00\x6A\x00\xB9\xFF\xFF\x67\x8C\xB8\x00\x00\x00\x00\xD3\x6C\x04\x08\x72\x05\xB8\x05\x00\x00\x00"

def mem_write_hook(uc, access, address, size, value, user_data):
    pass

def hook_code(uc, address, size, user_data):
    print("Executing instruction at 0x{:X}".format(address))

ADDRESS = 0x401000
STACK_ADDRESS = 0x180000
STACK_SIZE = 0x1000
mu = Uc(UC_ARCH_X86, UC_MODE_32)
mu.mem_map(STACK_ADDRESS, STACK_SIZE)
mu.mem_map(ADDRESS, 2 * 1024 * 1024)
mu.reg_write(UC_X86_REG_ESP, STACK_ADDRESS + STACK_SIZE - 4)
mu.reg_write(UC_X86_REG_EAX, 0)
mu.mem_write(ADDRESS, X86_CODE32)
mu.reg_write(UC_X86_REG_ECX, 0x1234)

mu.hook_add(UC_HOOK_CODE, hook_code)
mu.hook_add(UC_HOOK_MEM_WRITE,mem_write_hook)
mu.emu_start(ADDRESS, ADDRESS + len(X86_CODE32))
r_eax = mu.reg_read(UC_X86_REG_EAX)
print("eax:",r_eax)

The print result:

Executing instruction at 0x401000 Executing instruction at 0x401005 Executing instruction at 0x401007 Executing instruction at 0x401009 Executing instruction at 0x40100E Executing instruction at 0x401013 Executing instruction at 0x401017 eax: 0

But when I remove this code:

mu.hook_add(UC_HOOK_MEM_WRITE,mem_write_hook)

The print result will be:

Executing instruction at 0x401000 Executing instruction at 0x401005 Executing instruction at 0x401007 Executing instruction at 0x401009 Executing instruction at 0x40100E Executing instruction at 0x401013 Executing instruction at 0x401017 Executing instruction at 0x401019 eax: 5

wtdcode commented 1 year ago

I belive it's #1717.

wtdcode commented 1 year ago

Fixed in c889258d8eadf268325d31958b5f2c5ea99f73bb