使用Qemu模拟Arm处理器,运行Linux系统
Qemu是一个强大的虚拟化系统,可以在Linux和Windows宿主机上运行,可以模拟各种硬件处理器,比如x86、x64、Arm、Arm64、Risc-v等等,本身代码开源。一个嵌入式系统,需要先设计硬件开发板,然后软件开发人员在开发板上调试程序,开发周期会很长。有了Qemu,硬件板子开发制作阶段,软件开发人员可以在基于Qemu的模拟机上调试程序,有利于缩短开发周期。
一 Qemu模拟器安装
要模拟一个Arm处理器,需要先有一个安装一个qemu-system-arm。在乌班图系统里,可以通过下面的命令安装:
sudo apt install qemu-system-arm
但是这个版本可能不是最新的,有时需要自己编译产生。首先下载源代码,然后解压。
wget
https://download.qemu.org/qemu-8.1.4.tar.xz
tar -xvf qemu-8.1.4.tar.xz
接着运行配置脚本,产生符合宿主机(Host)的Makefile和.config.
./configure --target-list=arm-softmmu --enable-sdl --enable-kvm --enable-linux-aio \
--prefix=/us r/local/qemu-vexpress --disable-werror
然后编译安装
make -j$(nproc)
sudo make install
将安装目录加入执行路径
echo 'export PATH=/usr/local/qemu-vexpress/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
咱们验证一下是否成功
qemu-system-arm --version
安装成功会输出正确的版本号。
QEMU emulator version 8.1.4
Copyright (c) 2003-2023 Fabrice Bellard and the QEMU Project developers
二 制作嵌入式Linux内核和根文件系统镜像
获取源码
git clone --recursive https://gitee.com/han263012/linux-sty.git
获取代码后的目录结构如下:
.
├── all.sh
├── busybox
│ ├── build.sh
│ ├── busybox-1.35.0
│ ├── busybox-1.35.0.tar.bz2
│ ├── Config.in
│ └── prep-busyboxsrc.sh
├── clonesubmodule.sh
├── LICENSE
├── linux-kernel
│ ├── arch
│ ├── block
│ ├── certs
│ ├── COPYING
│ ├── CREDITS
│ ├── crypto
│ ├── Documentation
│ ├── drivers
│ ├── fs
│ ├── include
│ ├── init
│ ├── ipc
│ ├── Kbuild
│ ├── Kconfig
│ ├── kernel
│ ├── lib
│ ├── LICENSES
│ ├── MAINTAINERS
│ ├── Makefile
│ ├── mm
│ ├── net
│ ├── README
│ ├── samples
│ ├── scripts
│ ├── security
│ ├── sound
│ ├── tools
│ ├── usr
│ └── virt
├── linux-work
│ ├── aqemu
│ ├── build.sh
│ ├── cpkernelsrc.sh
│ └── rootfs
└── README.md
all.sh 是一个脚本文件,运行它,会准备代码、编译内核、创建虚拟sd卡,调用run-nolcd.sh运行虚拟机
三 运行Arm虚拟机
qemu-system-arm -nographic -sd sde.raw -M vexpress-a9 -m 512M -kernel zImage -dtb vexpress-v2p-ca9.dtb -smp 4 -append "root=/dev/mmcblk0p1 rw rootwait earlyprintk console=ttyAMA0"
这是运行Arm虚拟机的命令及参数,-sd sde.raw 表示使用sd卡镜像文件sde.raw, 它包含一个分区映射到/dev/mmcblk0 ,包含已经制作好的根文件系统。"root=/dev/mmcblk0p1 rw rootwait earlyprintk console=ttyAMA0"是传给内核的参数,-M vexpress-a9是指定开发板,-kernel zImage指定内核镜像,-dtb vexpress-v2p-ca9.dtb指定设备树文件。
Arm虚拟机运行输出的日志:
Booting Linux on physical CPU 0x0
Linux version 5.10.0 (h@ub2004) (arm-linux-gnueabihf-gcc (Linaro GCC 7.5-2019.12) 7.5.0, GNU ld (Linaro_Binutils-2019.12) 2.28.2.20170706) #1 SMP Mon Jul 21 16:26:04 CST 2025
ext4 filesystem being mounted at /root supports timestamps until 2038 (0x7fffffff)
VFS: Mounted root (ext4 filesystem) on device 179:1.
Freeing unused kernel memory: 1024K
Run /sbin/init as init process
random: crng init done
Please press Enter to activate this console.
四 在虚拟机上加载用户程序和驱动程序
根目录有一个hello程序,在镜像制作时已经加入,现在可以运行,它会输出内核的版本。
/ # ./hello
内核版本号: 5.10.0
我们再加载一个驱动,有一个hellodriver.ko的可加载驱动,使用insmod加载。
/ # cd /lib/modules/
/lib/modules # insmod hellodriver.ko
HanJ drivers/hellodriver/hellodriver.c hellodriver_init
/lib/modules # rmmod hellodriver
HanJ drivers/hellodriver/hellodriver.c hellodriver_exit