Contents

Capstone 101 - Decoding RISC-V instructions

Capstone & RISC-V

Just a few notes about playing with Capstone for RISC-V ISA. Be aware that RISC-V support has been added recently in Capstone. If you want to use Python bindings, you must install a v5 release candidate:

1
pip3 install capstone==5.0-rc2

[1] is an online RISC-V ISA decoder. In the context of a research project, we had to decode instructions with Capstone [2]. Here is a simple example with two instructions (same instruction copied twice):

1
2
3
4
5
6
# Instruction fa010113
CODE = b"\x13\x01\x01\xfa\x13\x01\x01\xfa"

md = Cs(CS_ARCH_RISCV, CS_MODE_RISCV64)
for i in md.disasm(CODE, 0x1000):
    print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))%          
1
2
3
$ python riscv1.py 
0x1000:	addi	sp, sp, -0x60
0x1000:	addi	sp, sp, -0x60

Be careful of the endianess. Unlike other ISA, we cannot use the endianess constants yet. For instance, in MIPS:

1
2
3
4
5
6
7
from capstone import *

CODE = b"\x56\x34\x21\x34\xc2\x17\x01\x00"

md = Cs(CS_ARCH_MIPS, CS_MODE_MIPS64 + CS_MODE_LITTLE_ENDIAN)
for i in md.disasm(CODE, 0x1000):
	print("%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))

Other basic scripts can be found on Capstone website [3].

References

  1. rvcodec.js · RISC-V Instruction Encoder/Decoder
  2. Capstone disassembly/disassembler framework
  3. Python tutorial for Capstone