1.前期准备
1.1安装开发工具
sudo apt install build-essential
sudo apt install qemu # install QEMU
sudo apt install libncurses5-dev bison flex libssl-dev libelf-dev
1.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
1.3配置内核选项
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)
1.4编译运行内核
make -j$(nproc) # nproc gives the number of CPU cores/threads available
# 测试一下内核能不能正常加载运行,因为没有文件系统最终会kernel panic
qemu-system-x86_64 -kernel arch/x86/boot/bzImage
2制作内存根文件系统
2.1首先从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
记得要编译成静态链接,不用动态链接库。
Settings --->
[*] Build static binary (no shared libs)
然后编译安装,默认会安装到源码目录下的 _install 目录中。
make -j$(nproc) && make install
2.2制作内存根文件系统镜像,大致过程如下:
mkdir 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/
2.3准备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脚本添加可执行权限
chmod +x init
打包成内存根文件系统镜像
find . -print0 | cpio --null -ov --format=newc | gzip -9 > ../rootfs.cpio.gz
测试挂载根文件系统,看内核启动完成后是否执行init脚本
qemu-system-x86_64 -kernel ../linux-5.4.34/arch/x86/boot/bzImage -initrd rootfs.cpio.gz
3用VScode调试内核
3.1添加配置文件
在VSCode中以打开文件夹打开源码文件夹,点击run->add configuration自动生成.vscode文件夹,并出现launch.json文件,修改其中内容,其他文件可手动添加也可以点击左下角齿轮->command palette输入相关信息得到其他配置文件。
3.2开始调试
在start_kernel出打断点开始调试。
执行到这一步,set_task_stack_end_magic(&init_task)函数,这个函数中该结构体(init_task)在linux启动时被设置为current_task。(此时idle进程已经启动)
在 /linux-5.4.34/arch/x86/kernel/cpu/common.c中:
DEFINE_PER_CPU(struct task_struct *, current_task) ____cacheline_aligned = &init_task;
然后对其他的信息也进行初始化。接着进行到了rest_init();这个地方。
kernel_init中
由kernel_init再通过do_execve启动/sbin/init或是其他init。这就是我们看到的init进程,进程号为1。初始化完成后linux调用scheule整个系统就运行起来了。
总结
idle是一个进程,其pid为0。是Linux引导中创建的第一个进程,完成加载系统后,演变为进程调度、交换及存储管理进程。主处理器上的idle由原始进程(pid=0)演变而来。从处理器上的idle由init进程fork得到,但是它们的pid都为0。Idle进程为最低优先级,且不参与调度,只是在运行队列为空的时候才被调度。Idle循环等待need_resched置位。1号进程是init 进程,由0进程创建,完成系统的初始化. 是系统中所有其它用户进程的祖先进程。