capstone wrong regs_read/regs_write value

322 Views Asked by At

I'm trying to use regs_read and regs_write, but it doesn't work:

$ cat cs.py 
import capstone
Cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
Cs.detail = True

CODE = b"\x48\x89\x44\x24\x10"
for i in Cs.disasm(CODE,0):
    print(i)
    print(i.regs_read)
    print(i.regs_write)

This is what I get

$ python3.7 cs.py
<CsInsn 0x0 [4889442410]: mov qword ptr [rsp + 0x10], rax>
[] <----- why? rax is read
[]

2

There are 2 best solutions below

0
Dany Zatuchna On BEST ANSWER

I think you can go for something like this:

def has_write_to_dereference_of_register(
    instruction: capstone.CsInsn,
    register: int
) -> bool:
    for operand in instruction.operands:
        if operand.access & capstone.CS_AC_WRITE:
            if operand.type == capstone.CS_OP_REG:
                if operands.value.reg == register:
                    return True
            elif operand.type == capstone.CS_OP_MEM:
                mem = operand.value.mem
                if mem.base == register or mem.index == register:
                    return True
    return False
0
Eli On

You may use the regs_access() method instead to get both reads and writes lists for the current instruction:

import capstone

Cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
Cs.detail = True

CODE = b"\x48\x89\x44\x24\x10"
for i in Cs.disasm(CODE, 0):
    reads, writes = i.regs_access()

    print(f'reads = {reads}, writes = {writes}')