1.linux内核调试环境搭建

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)
# 测试一下内核能不能正常加载运行,因为没有文件系统最终会kernel panic
qemu-system-x86_64 -kernel arch/x86/boot/bzImage

在这里插入图片描述

1.5制作根文件系统

https://www.busybox.net下载busybox源代码,并解压。

axel -n 20 https://busybox.net/downloads/busybox-1.30.0.tar.bz2
tar -jxvf busybox-1.36.0.tar.bz2
cd busybox-1.36.0

配置和编译安装。

make menuconfig
下面进行配置:
(记得要编译成静态链接,不用动态链接库。)
Settings  --->
    [*] Build static binary (no shared libs)
然后编译安装,默认会安装到源码目录下的 _install 目录中。
make -j$(nproc) && make install

制作内存根文件镜像。

mkdir rootfs
cd rootfs
cp ../busybox-1.36.0/_install/* ./ -rf
mkdir dev proc sys home
sudo cp -a /dev/{null,console,tty,tty1,tty2,tty3,tty4} dev/

在根文件系统根目录下(rootfs/…)准备init文件。
添加以下内容到init文件中

#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
echo "Wellcome LinuxOS!"
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

测试结果为:
在这里插入图片描述

2.通过vscode进行调试分析

2.1vscode终端输入以下代码

python ./scripts/gen_compile_commands.py

2.2在linux-5.4.34文件夹创建.vscode文件夹并将配置文件放入

配置文件
在这里插入图片描述

2.3设置start_kernel断点,通过vscode调试分析

在start_kernel处设置断点,并启动调试,程序停止在start_kernel处。
在这里插入图片描述

点击单步跳过,可以看到初始进程是整个系统的第一个进程。它在内核引导时会被创建和启动,是所有进程的起点。
在这里插入图片描述

继续点击单步跳过,会发现在start_kernel函数中执行了一系列初始化的操作,包括初始化数据结构,驱动程序,中断处理程序等。最后来到了start_kernel函数的最后函数arch_call_rest_init()。至此start_kernel调试结束。
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐