make menuconfig
# 确保以下选项开启:
# Kernel hacking -> Compile-time checks and compiler options ->
# [*] Compile the kernel with debug info
# [*] Provide GDB scripts for kernel debugging
编译内核后会生成包含完整符号信息的vmlinux
文件(位于内核源码根目录),这是GDB调试的关键文件。
qemu-system-x86_64 -kernel arch/x86/boot/bzImage \
-append "console=ttyS0 nokaslr" \
-hda rootfs.img \
-nographic \
-s -S # -s: 在1234端口监听GDB; -S: 启动时暂停CPU
gdb vmlinux
(gdb) target remote :1234
(gdb) break start_kernel # 设置初始断点
(gdb) continue
# 断点管理
break function_name
break *address
watch variable
delete breakpoint_num
# 执行控制
continue (c)
next (n)
step (s)
finish
# 信息查看
info registers
info breakpoints
backtrace (bt)
lx-symbols # 自动加载内核模块符号
lx-lsmod # 列出已加载模块
lx-dmesg # 查看内核日志
p task_struct->comm # 查看当前进程名
在~/.gdbinit
或当前目录下的.gdbinit
中添加:
add-auto-load-safe-path /path/to/kernel/source
set print pretty on
set disassembly-flavor intel
add-symbol-file /path/to/module.ko 0xffffffffc0000000 # 模块加载地址可从/sys/module/module_name/sections/.text获取
lx-symbols # 自动加载所有模块符号
当内核崩溃时,可以使用GDB分析Oops信息:
list *address # 查看崩溃位置的代码
bt # 查看调用栈
GDB支持Python脚本扩展,内核源码中的scripts/gdb
目录包含许多实用脚本:
source scripts/gdb/vmlinux-gdb.py
符号加载失败:
断点不生效:
nokaslr
)hbreak
代替break
单步执行异常:
nexti
/stepi
指令级单步ignore N 100
暂时跳过频繁触发的断点远程连接问题:
-s
选项通过以上配置和技巧,可以高效地使用GDB调试Linux内核,分析内核行为或排查问题。