环境搭建
wsl2 + ubuntu18.04 + vscode remote
开发环境
sudo apt install build-essential
sudo apt install qemu # 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
cd linux-5.4.34
配置内核选项
make defconfig # Default configuration is based on 'x86_64_defconfig'
make menuconfig
# 打开debug相关选项
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) # nproc gives the number of CPU cores/threads available
# 测试一下内核能不能正常加载运行,因为没有文件系统最终会kernel panic
qemu-system-x86_64 -kernel arch/x86/boot/bzImage
制作根文件系统
下载并解压busybox。注意,如果busybox版本太低的话,在高版本Linux系统中静态编译会报错,所以本次实验选择busybox-1.36.0版本。
axel -n 20 https://busybox.net/downloads/busybox-1.36.0.tar.bz2
tar -jxvf busybox-1.36.0.tar.bz2
cd busybox-1.36.0
准备init脚本文件放在根文件系统跟目录下(rootfs/init),添加如下内容到init文件
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
echo "Wellcome MengningOS!"
echo "--------------------"
cd home
/bin/sh
测试挂载根文件系统,看内核启动完成后是否执行init脚本
qemu-system-x86_64 -kernel linux-5.4.34/arch/x86/boot/bzImage -initrd rootfs.cpio.gz
跟踪调试Linux内核
执行下列命令,其中-S意思是Stopped,-s为gdb提供一个调试端口tcp:1234
qemu-system-x86_64 -kernel ./arch/x86/boot/bzImage -initrd rootfs.cpio.gz -S -s
再打开一个窗口,启动gdb,把内核符号表加载进来,建立连接:
cd linux-5.4.34/
gdb vmlinux
(gdb) target remote:1234 //这是通过之前预留的tcp:1234建立连接
(gdb) b start_kernel //这是设置了第一个断点
c、bt、list、next、step.... //具体查看gdb的命令
配置VSCode调试Linux内核
start_kernel()进行初始化工作。最后会调用reset_init(),并陷入该函数中的无限循环中。