Linux是如此美妙,如此有趣。Like Matrix,It’s Everywhere !
编译环境
- Windows10, Vmware16, Ubuntu20.04,虚拟环境。
- PC机,内存32G,CPU 16 核心,I7八代。
源码下载
检查Ubuntu虚拟环境的内核版本,本人编译环境内核版本为 version-5.8.0
然后到 https://www.kernel.org 下载接近的版本,本人下载的是5.4.80版。下载完后拷贝到home目录解压得到linux-5.4.80的源代码文件夹。
源码编译
进入解压后的源代码文件夹执行如下
make menuconfig
进入编译配置,打开下面的编译选项
Kernel hacking --->
[*] Kernel debugging
Compile-time checks and compiler options --->
[*] Compile the kernel with debug info
[*] Provide GDB scripts for kernel debugging
执行编译
make
制作根文件系统
根据具体Linux源码版本选择busybox源码版本,本人下载的1.32.0, 地址:https://busybox.net/,下载后拷贝到home目录解压。
$ cd busybox-1.32.0
$ make menuconfig
配置生成静态库
Settings --->
[*] Build static binary (no shared libs)
执行编译安装,安装到了_install下面
$ make
$ make install
创建initramfs
$ mkdir initramfs
$ cd initramfs
$ cp ../_install/* -rf ./
$ mkdir dev proc sys
$ sudo cp -a /dev/{null, console, tty, tty1, tty2, tty3, tty4} dev/
$ rm linuxrc
$ vim init
$ chmod a+x init
$ ls
$ bin dev init proc sbin sys usr
init 文件内容
#!/bin/busybox sh
mount -t proc none /proc
mount -t sysfs none /sys
exec /sbin/init
打包文件系统
$ find . -print0 | cpio --null -ov --format=newc | gzip -9 > ../initramfs.cpio.gz
进入busybox1.32.0目录,启动内核
qemu-system-x86_64 -s -kernel /home/charlie/linux-5.4.80/vmlinux -initrd initramfs.cpio.gz -nographic -append "console=ttyS0"
gdb 调试
安装qemu
sudo apt-get install qemu
进入到linux-5.4.80目录
gdb vmlinux
target remote localhost:1234
Eclipse 调试
下载Eclipse for c/c++ 版本,本人下载的是2020版本的,启动Eclipse。
- 到 Window->Preferences->General->Workspace 中将Build Automatically选项去掉,
- 到Window->Preferences->C/C++ -> Indexer中,将默认的Fast c/c++ indexer改为No indexer。
- 从菜单中选择File -> New -> Project… -> C/C++ -> C Project 然后单击Next按钮
- 在Project Name 一栏填入一个工程名,比如 linux-kernel. 然后将 Use default location 选项给勾掉。在Location一栏填入刚才解压的内核源码的路径。Project type选择Makefile project -> Empty project。Toolchains 选择 Linux GCC。
- 在右键菜单中点击“Debug As”->“Debug Configurations…”,在弹出的对话框中双击“C/C++ Remote Application”
- 将“C/C++ Application:”栏设置为 Linux Kernel 源码编译出来的 vmlinux 文件所在路径(包含文件名),然后将“Disable auto build”选上。注意最下面一行select other 用于切换手动和自动配置。
-
切换到“Debugger”页,将“Stop on startup at”设置为 start_kernel(Linux Kernel 的入口函数),将“Port number:”设置为之前 QEMU 运行时的默认端口号 1234,“Apply”后再点击上图中的“Debug”按钮开始调试。注意此时qemu内核调试环境还没起来,会弹出错误。
-
现在在中断进入busybox1.32.0执行如下命令,让内核进入调试等待状态
qemu-system-x86_64 -s -S -kernel /home/charlie/linux-5.4.80/vmlinux -initrd initramfs.cpio.gz -nographic -append "console=ttyS0"
- 现在到eclipse中 Run->Debug Configurations, 执行Debug后
总结
至此Linux内核调试环境已搭建完毕。工欲善其事必先利其器,有了一个方便的调试环境,能够让后面的事轻松义点。Linux是一个有趣的系统,一个框架,一种思想,一种文化。从Linux内核中可以学到大量先贤优秀的设计理念和思想,Linux也在不断地发展演化,从嵌入式系统到手机操作系统,桌面系统再到工作站,大型服务器,Linux无处不在。