# 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](https://github.com/capstone-engine/capstone/tree/5.0-rc2):

```bash
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):

```python
# 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))%          
```

```bash
$ 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:
```python
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](https://luplab.gitlab.io/rvcodecjs/)
2. [Capstone disassembly/disassembler framework](https://github.com/capstone-engine/capstone)
3. [Python tutorial for Capstone](https://www.capstone-engine.org/lang_python.html)

