Linux是一個非常棒的操作系統, 很多Linux的愛好者, 都想深入的學習它, 市面上的工具也很多, 今天給大家介紹一下怎么用KGDB來調試kernel的方法.
1. 下載新Linux內核
首先去Linux 官方網站 www.kernel.org 下載新的內核源碼, 現在新的版本是4.0. 我們以4.2.8為例.
假設缺省工作目錄為/home/linux/workspace
$ cd workspace
$ wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.2.8.tar.xz
$ tar -xvf linux-4.2.8.tar.xz
$ mv linux-4.2.8 linux
2. 配置內核選擇
如果要使能kgdb調試進行調試, 需要使用KGDB over the serial console 作為與gdb通信模塊。
$ cd linux
$ make defconfig
$ make menuconfig
選中 KGDB: use kgdb over the serial console 選項
General setup —>
[*] Prompt for development and/or incomplete code/driversKernel hacking —>
[*] Compile the kernel with debug info
[*] Compile the kernel with frame pointers
[*] KGDB: kernel debugger —>
<*> KGDB: use kgdb over the serial console
3. 編譯kernel
我們可以使用 -j選項, 根據CPU數來進行并行編譯,從而加快編譯速度,如果機器CPU是雙核4線程, -j后面跟上4.
如:
$ make -j4
如果想要保持linux目錄的clear,將編譯產生的二進制文件放到另一個目錄下,請參考使用下面的命令:
$ mkdir obj
$ cd linux
$ make O=../obj defconfig
$ make O=../obj -j4
編譯完成后,復制bzImage和vmlinux到工作目錄下備用
$ cp arch/x86/boot/bzImage ~/workspace
$ cp vmlinux ~/workspace
4. 安裝qemu
我們用的系統為ubuntu15.04. 也可以直接下載源碼進行編譯安裝.
$ sudo apt-get install qemu
5. 用qemu啟動Linux
用qemu啟動我們剛剛編譯的好的內核文件. 需要使用到根文件系統, 可以下載別人做好的, 也可以根據網上教程自己制作一個根文件系統.
$ qemu -kernel ~/workspace/bzImage -append "root=/dev/sda" -boot c -sda ~/workspace/busybox.img -k en-us
6. 啟用KGDB
我們已經使用qume啟動Linux系統了, 如果要使用kgdb需要在內核啟動時增加參數. 當然也可以在內核啟動后echo kgdboc模塊的參數來重新設置參數. 這兩種方式都可以, 在這里我們采用在內核啟動時增加啟動參數的方式:(kgdboc=ttyS0,115200 kgdbwait)
$ qemu -kernel ~/workspace/bzImage -append "root=/dev/hda kgdboc=ttyS0,115200kgdbwait" -boot c -sda ~/workspace/busybox.img -k en-us -serial tcp::5566,server
這時,運行qemu的終端將提示等待遠程連接到本地端口4321:
QEMU waiting for connection on: tcp:0.0.0.0:4321,server
這時使用另外一個控制臺執行:
$ gdb /usr/src/work/vmlinux(gdb) target remote localhost:4321
然后qemu就可以繼續正常運行下去,后停止內核,并顯示如下信息:
kgdb: Waiting for connection from remote gdb…
這時gdb這邊就可以看到如下的提示:
(gdb) target remote localhost:4321Remote debugging using localhost:4321kgdb_breakpoint () at kernel/debug/debug_core.c:983983 wmb(); /* Sync point after breakpoint */(gdb)
開始kernel的旅行吧!!!
注:和上面的文章不同的是,它將qemu的虛擬串口導向到本地的一個”pty”設備上,而前面我們是導向到一個socket端口上.
qemu -serial參數介紹如下:
-serial devRedirect the virtual serial port to host character device dev. The default devices "vc" in graphical mode and "stdio" in non graphical mode. This option can based several times to simulate up to 4 serials ports.
如果gdb提示如下信息:
warning: Invalid remote reply:
可以使用Ctrl+C來終止當前gdb的操作,再次使用下面命令重新連接一次kgdb即可:
(gdb) target remote localhost:4321
參考:
//kernel.org/pub/linux/kernel/people/jwessel/kgdb/
setting up kgdb using kvmqemu