qemu搭建riscv的可调试环境

发布时间 2023-10-07 09:54:09作者: CodeTrap

qemu搭建riscv的可调试环境

  • riscv工具链

(网上大多数用Github直连的工具链,但是因为太大,download的时候老是出问题)

选择使用Cross-compilation toolchains for Linux - Home (bootlin.com)进行下载,之后解压。

bin目录下为可执行的工具链,将其添加到PATH中。

  • qemu

qemu压缩包下载:QEMU,之后解压。

默认的安装命令:

这样会生成qemu支持的所有体系架构的可执行文件。

如果需要只生成一种架构的,需要配置target-list选项。

make之后在build目录下有对应qemu可执行文件:

将其添加到PATH中。

  • opensbi

(opensbi用于系统启动代码跳转)

项目github地址:https://github.com/riscv-software-src/opensbi

make时指定交叉编译器CROSS_COMPILE=riscv64-linux。

同时,指定PLATFORM=generic。

想要模拟不同类型的设备,make该项目时的PLATFORM参数可以参考opensbi/docs/platform下的md文件。

make之后,在opensbi/build/platform/generic/firmware下生成如下文件:

主要有三种类型的firmware:dynamic、jump、payload。

这里主要使用jump类型的fw_jump.elf文件,启动时直接跳转到OS入口代码。

  • linux kernel

直接github上下载linus的分支:torvalds/linux: Linux kernel source tree (github.com)

然后切换到指定版本的tag。

make ARCH=riscv CROSS_COMPILE=riscv64-linux- defconfig,之后make ARCH=riscv CROSS_COMPILE=riscv64-linux- menuconfig。

要使用GDB+qemu调试内核的话,一般得选中kernel debug以及取消地址随机化KASLR(不过在riscv相关的配置中没有发现这个配置)。

看riscv社区的新闻:Linux 内核地址空间布局随机化 “KASLR” for RISC-V – RISC-V INTERNATIONAL (riscv.org),riscv至今没有添加该特性。

make之后,会在arch/riscv/boot下生成对应的Image镜像。

  • rootfs

(创建根文件系统)地址:Buildroot - Making Embedded Linux Easy

make menuconfig选择RISCV

之后sudo make,会在output/images下生成对应的文件:

  • 共享文件

qemu中运行的虚拟机往往需要和主机间传输数据,因此,最常使用的方式就是共享文件。

dd if=/dev/zero of=ext4.img bs=512 count=131072

mkfs.ext4 ext4.img

sudo mount -t ext4 -o loop ext4.img ./share

在当前目录下生成share目录,可用于虚拟机和主机间共享数据:

  • gdb调试
#!/bin/bash

qemu-system-riscv64 -M virt \
	-bios fw_jump.elf \
	-kernel Image \
	-append "rootwait root=/dev/vda ro" \
	-drive file=rootfs.ext2, format=raw,id=hd0 \
	-device virtio-blk-device, device=hd0 \
	-drive file=ext4.img, format=raw,id=hd1 \
	-device virtio-blk-device, driver=hd1 \
	-s -nographic

-s参数使主机端使用端口1234进行kernel调试。

运行命令后:

主机端调试,使用riscv64-linux-gdb调试编译kernel后生成的vmlinux。

target remote localhost:1234用于调试虚拟机。

以调度的关键函数finish_task_switch为断点为例:

此时挂载到从init_task切换到下一个进程的过程中了。

常规的gdb命令可以用于调试kernel,查看kernel运行时信息。