使用GDB调试Linux内核
1.自行静态编译init文件,该文件是内核执行的第一个进程
# include <stdio.h>
int main ( const int argc, const char * argv[ ] )
{
printf ( "hello, world\n" ) ;
return 0 ;
}
zhanghao@LAPTOP-7UL4ROG7:~/documents/demo/xiaomi$ gcc -static ./helloworld.c -o init
zhanghao@LAPTOP-7UL4ROG7:~/documents/demo/xiaomi$ file init
init: ELF 64 -bit LSB executable, x86-64, version 1 ( GNU/Linux) , statically linked, BuildID[ sha1] = 3ee48c7c46163b6131ff18c7765baf7468d8f65f, for GNU/Linux 3.2 .0, not stripped
echo init | cpio -H newc -o > init.cpio
2.编译内核
# 使用x86_64默认配置
make x86_64_defconfig
# 配置内核调试选项, [Kernel hacking] -> [Compile-time checks and compiler options] -> [Compile the kernel with debug info]&[Provide GDB scripts for kernel debugging]
make menuconfig
# 编译内核
make bzImage -j16
make scripts_gdb
3.使用qemu运行内核
qemu-system-x86_64 -kernel < path-to-linux> /arch/x86_64/boot/bzImage -initrd < path-to-init> /init.cpio -m 2048 -append "rdinit=/init console=ttyS0 no5lvl nokaslr" \
-nographic -s -S
gdb < path-to-linux> /vmlinux
target remote :1234
b ksys_write
c