使用 QEMU 运行 Linux kernel

让我们使用 qemu 来运行 Linux 吧。

安装 QEMU

首选安装 QEMU,如果不是 x86 就改成自己的架构。

1
2
sudo apt-get update
sudo apt-get install gqemu-system-x86

下载 Linux Kernel 和编译

  1. 先下载 Linux,这里选择一个自己的版本

    1
    2
    3
    wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.54.tar.xz
    tar xvf linux-5.10.54.tar.xz
    cd linux-5.10.54
  2. 构建linux

1
2
3
4
5
make defconfig # 创建默认配置
make kvmconfig # 设置 QEMU 相关的编译配置
make olddefconfig

make -j`nproc` # nproc 使用的编译线程

最终执行完成之后,就会有一个内核镜像

1
ls arch/x86_64/boot/bzImage

RootFS

这有一个 https://github.com/google/syzkaller/blob/master/docs/linux/setup_ubuntu-host_qemu-vm_x86-64-kernel.md 构建博客指导。

1
2
3
4
5
sudo apt-get install debootstrap
mkdir image && cd image
wget https://raw.githubusercontent.com/google/syzkaller/master/tools/create-image.sh -O create-image.sh
chmod +x create-image.sh
./create-image.sh

这里默认去默认的源下载,这里如果在国内,修改 create-image.sh

1
2
3
4
5
6
# riscv64 is hosted in the debian-ports repository
# debian-ports doesn't include non-free, so we exclude firmware-atheros
if [ $DEBARCH == "riscv64" ]; then
DEBOOTSTRAP_PARAMS="--keyring /usr/share/keyrings/debian-ports-archive-keyring.gpg --exclude firmware-atheros $DEBOOTSTRAP_PARAMS http://deb.debian.org/debian-ports"
fi
sudo debootstrap $DEBOOTSTRAP_PARAMS <这里填入相对应的Mirrors地址>
1
sudo debootstrap $DEBOOTSTRAP_PARAMS https://mirrors.ustc.edu.cn/debian/

运行 Kenerl

1
2
3
4
5
6
7
8
9
10
11
qemu-system-x86_64 \
-m 2G \
-smp 2 \
-kernel $1/arch/x86/boot/bzImage \
-append "console=ttyS0 root=/dev/sda earlyprintk=serial net.ifnames=0 nokaslr" \
-drive file=$2/stretch.img,format=raw \
-net user,host=10.0.2.10,hostfwd=tcp:127.0.0.1:10021-:22 \
-net nic,model=e1000 \
-enable-kvm \
-nographic \
-pidfile vm.pid

如果在虚拟机中执行,去除 -enable-kvm

1
2
chmod +x run.sh
./run.sh . image/

从外部访问

1
2
# 在QEMU 内
service ssh restart

然后在本机执行

1
ssh -i image/stretch.id_rsa -p 10021 -o "StrictHostKeyChecking no" root@localhost

参考