1. 程式人生 > >linux下qemu除錯linux核心

linux下qemu除錯linux核心

編譯核心

  • 下載kernel原始碼
git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
cd linux-stable/

-配置核心
make menuconfig:
在kernel hacking下的選項中選中(實用空格鍵,星號*代表選選中)compile the kernel with debug info
注意【記得提前安裝libncurses5-dev】,或者其他編譯核心需要的依賴包

│ │ [*] 64-bit kernel │ │
│ │ General setup —> │ │
│ │ [*] Enable loadable module support —> │ │
│ │ -*- Enable the block layer —> │ │
│ │ Processor type and features —> │ │
│ │ Power management and ACPI options —> │ │
│ │ Bus options (PCI etc.) —> │ │
│ │ Executable file formats / Emulations —> │ │
│ │ [*] Networking support —> │ │
│ │ Device Drivers —> │ │
│ │ Firmware Drivers —> │ │
│ │ File systems —> │ │
│ │ Kernel hacking —>

│ │
│ │ Security options —> │ │
│ │ -*- Cryptographic API —> │ │
│ │ [*] Virtualization —> │ │
│ │ Library routines —> │ │

按K鍵選中Kernel hacking之後按enter鍵進入子選項,按K鍵選移動到 Kernel debugging選項並按空格鍵選中為星號*(如下)

│ │
[*] Magic SysRq key │ │
│ │ (0x1) Enable magic SysRq key functions by default │ │
│ │ [*] Enable magic SysRq key over serial │ │
│ │ [*] Kernel debugging

│ │
│ │ Memory Debugging —> │ │
│ │ [ ] Code coverage for fuzzing │ │
│ │ [ ] Debug shared IRQ handlers │ │
│ │ Debug Lockups and Hangs —>
進入kernel debuging 選中compile the kernel with debug info選項
儲存退出

  • 執行編譯
    make -j16編譯核心
    編譯完成之後生成bzImage和vmlinux二進位制核心映象就可以用來除錯。
linux-stable$ ls arch/x86_64/boot/bzImage -lh
lrwxrwxrwx 1 emindsoft emindsoft 22 1022 14:32 arch/x86_64/boot/bzImage -> ../../x86/boot/bzImage
linux-stable$ ls -lh
-rwxrwxr-x   1 emindsoft emindsoft 443M 1021 11:52 vmlinux

更新gdb

詳細資訊可以檢視這裡修改方法這裡寫程式碼片
由gdb-7.8.tar.gz下載最新的gdb(7.8)到/opt目錄下【目錄隨意選】
解壓縮:tar zxvf gdb-7.8.tar.gz
修改程式碼【否則除錯核心會出現remote ‘g’ packet reply is too long的問題】
cd gdb-7.8/gdb
vim remote.c
按照如圖所示修改程式碼【針對7.8版本】:

程式碼如下:

if (buf_len > 2 * rsa->sizeof_g_packet) {    
      rsa->sizeof_g_packet = buf_len ;    
      for (i = 0; i < gdbarch_num_regs (gdbarch); i++)    
      {    
         if (rsa->regs->pnum == -1)    
         continue;    

         if (rsa->regs->offset >= rsa->sizeof_g_packet)    
         rsa->regs->in_g_packet = 0;    
         else    
         rsa->regs->in_g_packet = 1;    
      }    
   }    

安裝gdb
在主目錄gdb-7.8下依次執行命令(你也可以選擇自己想要的version):

./configure
make
make install

啟動qemu

  • 在啟動之前,我們需要initrd.img檔案,至於該檔案的作用大家可自行百度。這裡我們直接從宿主ubuntu系統中cp過來:
    cd linux-stable/
    cp /boot/initrd.img-4.4.0-97-generic ./
  • 開始啟動
    cd linux-stable/
    qemu-system-x86_64 -S -kernel arch/x86_64/boot/bzImage -initrd ./initrd.img-4.4.0-97-generic -m 1024
    // -m表示非配記憶體大小為128Mb, -S表示以除錯模式啟動,暫定在啟動介面
    // -S表示“冷凍”虛擬機器,等待偵錯程式發出繼續執行命令;
    // -kernel表示要除錯的核心映象
    注: 這裡並沒有製作檔案系統,大家可以更具自己的需求新增

同時摁ctrl+alt+2進入qemu命令列介面, 輸入gdbserver tcp::1234,建立並等待gdb連線(如下圖)
這裡寫圖片描述

  • 摁ctrl+alt+1返回qemu
    另外開一個終端到linux-stable主目錄下,輸入命令:gdb vmlinux
    在gdb下輸入:target remote localhost:1234 連線qemu中開啟的gdbserver(如下圖)
    這裡寫圖片描述
    設定斷點【舉例:b do_fork】
    輸入命令c開始執行到斷點處
    輸入命令n執行下一個語句