1.准备相关工具
sudo apt install build-essential
sudo apt 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
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相关选项
在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)
3.编译并且运行内核
make -j$(nproc)
qemu-system-x86_64 -kernel arch/x86/boot/bzImage
出现panic,需要挂载根文件系统
4.制作根文件系统
下载并编译安装busybox:
#首先从https://www.busybox.net下载 busybox源代码解压,解压完成后,跟内核一样先配置编译,并安装。
axel -n 20 https://busybox.net/downloads/busybox-1.31.1.tar.bz2
tar -jxvf busybox-1.31.1.tar.bz2
cd busybox-1.31.1
make menuconfig #Setting里的Build static binary (no shared libs)选中
make -j$(nproc) && sudo make install
制作根文件系统镜像
mkdir rootfs # 在/linux-5.4.34文件夹下新建rootfs文件夹
cd rootfs
cp ../busybox-1.31.1/_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 OS!”
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 ./arch/x86/boot/bzImage -initrd rootfs.cpio.gz
6.VSCode配置Linux内核调试环境
由于 Linux 内核高度定制化,所以没有办法直接通过配置 includePath 等让 Intellisense 正常提示,这里借助一个 Python 脚本来生成compile_commands.json 文件帮助 Intellisense 正常提示(包括头文件和宏定义等)。在Linux源代码目录下直接运行如下命令就可以生成compile_commands.json 了。
python ./scripts/gen_compile_commands.py
新建一个.vscode文件夹,将配置文件放入该文件夹内,配置如下五个文件:c_cpp_properties.json,init,launch.json,settings.json,tasks.json
c_cpp_properties.json
{
"configurations": [
{
"name": "Linux",