一、实验环境搭建
1.下载开发工具
sudo apt install build-essential
sudo apt install qemu # install QEMU#作为一个虚拟机
sudo apt install libncurses5-dev bison flex libssl-dev libelf-dev
#编译内核所需的依赖---一些基础库
2.下载源码
sudo apt install axel
axel -n 20 https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.4.34.tar.xz
3.解压内核源码
xz -d linux-5.4.34.tar.xz
tar -xvf linux-5.4.34.tar #解压源码
cd linux-5.4.34
4.配置内核选项
make defconfig # Default configuration is based on 'x86_64_defconfig'
make menuconfig# 打开debug相关选项
![](https://i-blog.csdnimg.cn/blog_migrate/b4501d4e095de727251cde29eeb03ffc.png)
Kernel hacking --->
Compile-time checks and compiler options --->
[*] Compile the kernel with debug info
[*] Provide GDB scripts for kernel debugging
[*] Kernel debugging
Processor type and features ---->
[] Randomize the address of the kernel image (KASLR)
5.编译
make -j$(nproc) #在linux-5.4.34文件夹下使用qemu测试内核是否能加载,结果会显示“kernel panic”
qemu-system-x86_64 -kernel arch/x86/boot/bzImage
![](https://i-blog.csdnimg.cn/blog_migrate/668bd6cd5d8c773b7e8a566bfe7a709e.png)
二、使用busyboy
使用busybox制作根文件系统
$ axel -n 20 https://busybox.net/downloads/busybox-1.32.0.tar.bz2 # download
$ tar -jxvf busybox-1.32.0.tar.bz2
$ cd busybox-1.32.0
2.编译配置
$ make menuconfig
Settings --->
[*] Build static binary (no shared libs)
$ make -j14 && make install
$ mkdir rootfs
$ cd rootfs
$ cp ../busybox-1.32.0/_install/* ./ -rf
$ mkdir dev proc sys home
$ sudo cp -a /dev/{null,console,tty,tty1,tty2,tty3,tty4} dev/
$ nvim init #添加以下内容
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
echo "Wellcome Mengning OS!"
echo "--------------------"
cd home
/bin/sh
$ chmod +x init
$ find . -print0 | cpio --null -ov --format=newc | gzip -9 > ../rootfs.cpio.gz
![](https://i-blog.csdnimg.cn/blog_migrate/5c9a0b0f59707ab98b4b8422a7425a92.png)
3.添加权限,打包成镜像,测试系统
chmod +x init
find . -print0 | cpio --null -ov --format=newc | gzip -9 > ../rootfs.cpio.gz
qemu-system-x86_64 -kernel ./arch/x86/boot/bzImage -initrd rootfs.cpio.gz
![](https://i-blog.csdnimg.cn/blog_migrate/706ce6ef826e6d823ae6db08c0b44013.png)
三、VS Code 调试
安装VS Code及插件
sudo apt install ./code_1.76.2-1678817801_amd64.deb #安装vscode
安装VSCode插件C/C++ Intellisense和C/C++ Themes。由于插件C/C++ Intellisense需要GNU Global,还需要使用如下命令安装GNU Global。
sudo apt install global
调试
python ./scripts/gen_compile_commands.py #linux目录下执行
VS Code添加配置文件.vscode/c_cpp_properties.json
启动调试
![](https://i-blog.csdnimg.cn/blog_migrate/99895a9fa5dc8557e5263ebac1c86ee7.png)