准备环境以及内核
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 10 https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.4.34.tar.xz
#改为10,下载完后右键提取
#cd到linux-5.4.34
make defconfig # Default configuration is based on 'x86_64_defconfig'
make menuconfig# 打开debug相关选项
配置内核选项
make defconfig # Default configuration is based on 'x86_64_defconfig'
make menuconfig
配置内容
# 打开debug相关选项 输入y和n进行选中或取消选中
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模拟根目录系统
ppt中的1.31.1版本的busybox安装后,内核编译初始化失败,应该是内核的原因,更新busybox版本后解决。
axel -n 20 https://busybox.net/downloads/busybox-1.32.0.tar.bz2
tar -jxvf busybox-1.32.0.tar.bz2
cd busybox-1.32.0
make menuconfig
Settings --->
[*] Build static binary (no shared libs)
# 记得要编译成静态链接,不用动态链接库
make -j$(nproc) && 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/
插入init脚本查看运行情况
新建init文件,在rootfs根目录下,编写脚本内容如下
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
echo "Wellcome Li‘s OS!"
echo "--------------------"
cd home
/bin/sh
为init文件添加权限
chmod +x init
运行脚本查看系统运行情况
qemu-system-x86_64 -kernel ../../linux-5.4.34/arch/x86/boot/bzImage -initrd ../rootfs.cpio.gz
vscode调试
执行脚本
python ./scripts/gen_compile_commands.py
调试过程
在start_kernel函数打断点进行执行
start_kernel将init_task设置为0号进程,并进行一系列的初始化和准备工作,包括初始化各种重要的数据结构、驱动程序、中断处理程序等。在这个阶段,内核会建立好一些必要的核心数据结构,如物理内存管理器、虚拟内存管理器,以及进程调度器等。
最后执行reset_init函数,此函数是由0号进程执行,并且新建 kernel_init 和 kthreadd 内核线程,调用了kernel_thread()。kthreadd负责管理调度其他创建的内核线程,这些线程直接或间接的以kthreadd为父进程。
整体过程为start_kernel直接创建0号进程,并进行系统配置, 再调用do_execve加载init进程,过程中由0号进程创建kthreadd进行内核态线程管理。