0xmozak / mozak-vm

Mozak RISC-V Virtual Machine
Apache License 2.0
12 stars 8 forks source link

Enhance runner for debugging abilities #949

Open vivekvpandya opened 11 months ago

vivekvpandya commented 11 months ago

When running a Rust code in VM , it becomes hard to trace back to Rust code from ELF. With debugging information it can be done. However we must enhance our runner to understand debugging information and ultimately provide our VM user nice debugging experience though debuggers like GDB.

vivekvpandya commented 11 months ago

We can also try to run our ELFs on some RiscV emulator which already provides debugging support. https://www.qemu.org/docs/master/system/target-riscv.html https://github.com/riscv-software-src/riscv-isa-sim

vivekvpandya commented 10 months ago

Debugging ELFs with spike:

Spike is a RISC-V ISA simulator and we can use it to debug our ELFs as it supports attaching gdb like debuggers with OpenOCD.

Get spike from https://github.com/riscv-software-src/riscv-isa-sim Build it with commands shown below, :

 apt-get install device-tree-compiler
 mkdir build
 cd build
 ../configure --prefix=<RISC-V tools install path>
 make
 [sudo] make install

Get Risc-V OpenOCD sources from https://github.com/riscv/riscv-openocd Built it with following commands

./bootstrap
./configure --prefix=<RISC-V tools install path> --enable-remote-bitbang --enable-jtag_vpi --disable-werror
make
[sudo] make install

Save following content to spike.cfg

 adapter driver remote_bitbang
remote_bitbang host localhost
remote_bitbang port 9824

set _CHIPNAME riscv
jtag newtap $_CHIPNAME cpu -irlen 5 -expected-id 0xdeadbeef

set _TARGETNAME $_CHIPNAME.cpu
target create $_TARGETNAME riscv -chain-position $_TARGETNAME

gdb_report_data_abort enable

init
halt

Start spike with following command:

./spike --isa=RV32IM --rbb-port=9824 <ELF_PATH>

Then start openocd with following command

./openocd -f spike.cfg 

Then start GDB with following command and attach it to remote target

./riscv64-unknown-elf-gdb <ELF_PATH>

target extended-remote :3333 

Now set breakpoints and rerun the program from gdb.

Notes: When running ELF in spike if you hit error like following Memory address 0x10000000 is invalid then mostly some addresses are reserved by spike for its certain feature and adjusting our memory map in linker script help avoid such errors. spike_memory_layout.patch.txt

Attached small patch that I used to adjust our ELF's memory map so that it works with spike.

vivekvpandya commented 9 months ago

Just to note as per https://github.com/riscv-software-src/riscv-isa-sim/issues/1426#issuecomment-1901395202 on spike, typically program should start its memory after 0x8000_0000