本文翻譯自“Prepare the environment for developing Linux kernel with qemu”,在原文基礎上進行了部分精簡和修正。
編譯Linux Kernel
- 軟件包安裝
$ sudo apt install git
$ sudo apt install build-essential kernel-package fakeroot libncurses5-dev libssl-dev ccache flex bison libelf-dev
- 同步Linux kernel 源代碼
$ git clone https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git $ cd linux-next $ git checkout master $ git fetch origin $ git reset --hard remotes/origin/master
- 生成Linux kernel配置
$ make ARCH=x86_64 x86_64_defconfig
- 使用menuconfig配置GDB debugger選項
$ make ARCH=x86_64 menuconfig
- 進入“Kernel hacking”菜單
- 勾選“Compile the kernel with debug info”
- 勾選“Provide GDB scripts for kernel debugging” ,同時保持“Reduce debugging information”不勾選狀態,保存並退出。
- 編譯Linux kernel鏡像
$ make -j8
- 安裝qemu
$ sudo apt install qemu qemu-system
- 使用qemu-system-x86_64測試生成的Linux kernel鏡像,按“Ctrl + c”退出qemu。
$ qemu-system-x86_64 -no-kvm -kernel arch/x86/boot/bzImage -hda /dev/zero -append "root=/dev/zero console=ttyS0" -serial stdio -display none
使用GDB調試Linux Kernel
- 安裝GDB
$ sudo apt install gdb
- 在調試模式下啟動qemu,其中“-s”選項表示:使用tcp 1234端口;“-S”選項表示只有在GDB連上tcp 1234端口后,CPU才會繼續執行。
$ qemu-system-x86_64 -s -S -no-kvm -kernel arch/x86/boot/bzImage -hda /dev/zero -append "root=/dev/zero console=ttyS0 nokaslr" -serial stdio -display none
- 新建terminal並運行GDB
$ cd linux-next
$ gdb vmlinuz
- 在GDB命令中輸入“target remote localhost:1234”
(gdb) target remote localhost:1234
- 設置斷點為"start_kernel"
(gdb) break start_kernel
- GDB相關命令
’n’ (next)
‘c’ (continue)
使用Buildroot來創建根文件系統
- 使用git同步Buildroot源代碼(訪問buildroot網站可能需要代理,請根據實際情況自行配置)
$ git clone git://git.buildroot.net/buildroot $ cd buildroot
- 配置Buildroot
$ make menuconfig
- 將文件系統配置為ext4
“Target Options” → “Target Architecture” → “Filesystem images” → “ext2/3/4 root file system” → “ext4”
- 編譯Buildroot
$ make -j8
- 使用qemu運行Linux kernel和Buildroot根文件系統(注意buildroot路徑)
$ cd linux-next $ qemu-system-x86_64 -kernel arch/x86/boot/bzImage -boot c -m 2049M -hda ../buildroot/output/images/rootfs.ext4 -append "root=/dev/sda rw console=ttyS0,115200 acpi=off nokaslr"-serial stdio -display none
- 登錄用戶名為root
Welcome to Buildroot buildroot login:
使用GDB調試帶Buildroot根文件系統的Linux Kernel
- 使用qemu啟動Linux Kernel和Buildroot根文件系統
$ qemu-system-x86_64 -s -kernel arch/x86/boot/bzImage -boot c -m 2049M -hda ../buildroot/output/images/rootfs.ext2 -append "root=/dev/sda rw console=ttyS0,115200 acpi=off nokaslr" -serial stdio -display none ... Welcome to Buildroot buildroot login:
- 新建terminal並運行GDB,並在GDB命令中輸入“target remote localhost:1234”連接qemu
$ gdb ./vmlinux ... (gdb) target remote :1234
總結
使用qemu可以方便地使用GDB調試Linux Kernel。