Linux内核分析 源码阅读、编译调试和启动过程

本文详细介绍了如何在WindowsSubsystemforLinux2(WSL2)的Ubuntu18.04环境下,使用VSCodeRemote进行Linux内核的编译、调试。首先,通过安装必要的工具如build-essential,QEMU和BusyBox来创建基础环境。然后,下载并配置内核源码,启用调试选项,关闭KASLR。接着,编译内核并在QEMU中运行测试。同时,制作了简单的根文件系统,并编写init脚本。最后,利用GDB进行内核调试,并展示了如何在VSCode中配置远程调试设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境搭建

wsl2 + ubuntu18.04 + vscode remote

开发环境

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 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相关选项
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) # nproc gives the number of CPU cores/threads available
# 测试一下内核能不能正常加载运行,因为没有文件系统最终会kernel panic
qemu-system-x86_64 -kernel arch/x86/boot/bzImage

在这里插入图片描述

制作根文件系统

下载并解压busybox。注意,如果busybox版本太低的话,在高版本Linux系统中静态编译会报错,所以本次实验选择busybox-1.36.0版本。

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

在这里插入图片描述
准备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脚本

qemu-system-x86_64 -kernel linux-5.4.34/arch/x86/boot/bzImage -initrd rootfs.cpio.gz

在这里插入图片描述

跟踪调试Linux内核

执行下列命令,其中-S意思是Stopped,-s为gdb提供一个调试端口tcp:1234

qemu-system-x86_64 -kernel ./arch/x86/boot/bzImage -initrd rootfs.cpio.gz -S -s

在这里插入图片描述
再打开一个窗口,启动gdb,把内核符号表加载进来,建立连接:

cd linux-5.4.34/
gdb vmlinux
(gdb) target remote:1234  //这是通过之前预留的tcp:1234建立连接
(gdb) b start_kernel       //这是设置了第一个断点
c、bt、list、next、step....  //具体查看gdb的命令

配置VSCode调试Linux内核

在这里插入图片描述
start_kernel()进行初始化工作。最后会调用reset_init(),并陷入该函数中的无限循环中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值