环境:ubuntu 20.04
下载工具
sudo apt install build-essential
sudo apt install qemu
sudo apt install libncurses5-dev bison flex libssl-dev libelf-dev
下载内核源码
sudo apt install axel
axel -n 20 https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.4.34.tar.xz
xz -d linux-5.4.34.tar.xz
tar -xvf linux-5.4.34.tar
tar -xvf linux-5.4.34.tar
配置内核
make defconfig
make menuconfig
配置选项如下
Kernel hacking --->
Compile-time checks and compiler options --->
[*] Compile the kernel with debug info
[*] Provide GDB scripts for kernel debugging
[*] Kernel debugging
关闭KASLR(随机地址),否则会导致打断点失败
Processor type and features ---->
[ ] Randomize the address of the kernel image (KASLR)
编译运行内核
make -j$(nproc)
制作根文件目录
下载busybox
wget https://busybox.net/downloads/busybox-1.35.0.tar.bz2
tar -jxvf busybox-1.35.0.tar.bz2
cd busybox-1.35.0/
配置选项
make menuconfig
Settings --->
[*] Build static binary (no shared libs)
make -j$(nproc) && make install
制作根文件镜像
mkdir rootfs
cd rootfs
cp ../busybox-1.35.0/_install/* ./ -rf
mkdir dev proc sys home
sudo cp -a /dev/{null,console,tty,tty1,tty2,tty3,tty4} dev/
准备init放在根文件根目录(rootfs/init)下
将以下内容添加到init中
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
echo "Wellcome YuOS!"
echo "--------------------"
cd home
/bin/sh
给init脚本添加可执行权限
chmod +x init
打包
find . -print0 | cpio --null -ov --format=newc | gzip -9 > ../rootfs.cpio.gz
执行
qemu-system-x86_64 -kernel linux-5.4.34/arch/x86/boot/bzImage -initrd rootfs.cpio.gz
VSCODE调试
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
下载安装好VSCODE以及相应的扩展
在使用VSCODE前先执行
python ./scripts/gen_compile_commands.py
新建.vscode,将配置文件加入
打开VSCODE
执行
qemu-system-x86_64 -kernel ./arch/x86/boot/bzImage -initrd rootfs.cpio.gz -S -s
然后设置断点start_kernel,在vscode中按F5进行调试