Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux 伺服器

如何定位可動態載入核心模組的 OOPS 出錯程式碼行

一、從 vmlinux 取得確切程式碼行

論壇的 albcamus 版主提過,用 gdb 追查出錯行需要自己編譯的 vmlinux,而且編譯時必須開啟 compile with debug info。開啟後 vmlinux 會比不帶除錯資訊時大一些(示範環境中帶除錯資訊者約 49M)。若你打算用 gdb 定位出錯行,這個選項一定要勾。

有了帶除錯資訊的 vmlinux,就能依標準流程把 OOPS 還原到具體的 C 程式碼行。

二、從模組本身的出錯資訊反推程式碼行

以下以 LDD3 提供的 misc-modules/faulty.c 為例,分析其中的 faulty_write 函式。原作者的範例過於簡潔,這裡加上一點判斷與賦值:

ssize_t faulty_write (struct file *filp, const char __user *buf, size_t count,
                      loff_t *pos)
{
    /* make a simple fault by dereferencing a NULL pointer */
    if (count > 0x100)
        count = 0x100;
    *(int *)0 = 0;
    return count;
}

(1)編譯模組並建立裝置節點

編譯完成後用 mknod /dev/faulty 建立對應的裝置檔。

(2)觸發 OOPS

echo 1 > /dev/faulty

核心隨即拋出 OOPS,關鍵片段如下:

<1>BUG: unable to handle kernel NULL pointer dereference at virtual address 00000000
Oops: 0002 [#3]
Modules linked in: faulty autofs4 hidp rfcomm l2cap ...
EIP: 0060:[<f8e8000e>] Not tainted VLI
EIP is at faulty_write+0xe/0x19 [faulty]
Process bash (pid: 6084, ...)
Call Trace:
  [<c1065914>] vfs_write+0xa1/0x143
  [<c1065f06>] sys_write+0x3c/0x63
  [<c1003d0b>] syscall_call+0x7/0xb
EIP: [<f8e8000e>] faulty_write+0xe/0x19 [faulty]  SS:ESP 0068:f4dc5f84

該看的是兩處:第一行告訴我們程式 dereference 了 NULL 指標;第二行 EIP is at faulty_write+0xe/0x19 指出問題發生在 faulty 模組的 faulty_write 函式。後半的 0xe/0x19 中,0x19 是函式大小(組合語言位元組數),0x0e 則是出錯的位移位置。

(3)反組譯模組

objdump -d faulty.ko > faulty.s
# 或
objdump -d faulty.o > faulty.s

打開 faulty.s,我們關注的部分正好在檔案開頭:

faulty.o:     file format elf32-i386
Disassembly of section .text:

00000000 <faulty_write>:
   0:  81 f9 00 01 00 00    cmp    $0x100,%ecx
   6:  b8 00 01 00 00       mov    $0x100,%eax
   b:  0f 46 c1             cmovbe %ecx,%eax
   e:  c7 05 00 00 00 00 00 00 00  movl   $0x0,0x0
  15:  00 00 00
  18:  c3                   ret

00000019 <cleanup_module>:
  19:  a1 00 00 00 00       mov    0x0,%eax
  ...
00000028 <faulty_init>:
  28:  a1 00 00 00 00       mov    0x0,%eax
  ...
  53:  c3                   ret

由此可見 faulty_write 的大小確實是 0x18 − 0x00 + 1 = 0x19,而 EIP 出問題的位置在 0x0e,對應的指令是:

movl $0x0,0x0

也就是把 0 寫入位址 0,這顯然是非法的。對回 C 程式碼,就是原始碼中的:

*(int *)0 = 0;

(4)方法的限制

這個做法有兩個前提:一是 EIP 出錯位置必須落在模組內部,才能用模組自身定位;二是需要一定的組合語言基礎,當函式很長、組譯結果龐大時,要準確對回 C 行需要經驗與時間。

實務上最好的方式是把兩種方法結合:先用 vmlinux 加上除錯資訊定位核心本身的問題,再用 objdump 反組譯處理動態模組,通常能顯著縮短排查時間。若分析中有疏漏,歡迎指正,也歡迎分享更有效率的做法。

Copyright © Linux教程網 All Rights Reserved