歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Kprobe在Linux kernel debug中的應用

Kprobe在Linux kernel debug中的應用

日期:2017/3/1 10:03:37   编辑:Linux編程

一直在做kernel開發方面的工作,也一直苦於kernel debug的困惑,到底如何進行kernel開發的debug的工作?今天經美國同事的推薦,我認為kprobe是一個非常好的debug工具。其本質原理就是在你需要probe的地方放入斷點指令,然後在斷點處調用你的調試/測試程序,從而可以實現對kernel程序的調試/測試。

Kprobe只是提供了一種機制,使得用戶可以在系統運行時調試/測試內核程序。使用Kprobe需要做如下幾件事情:

1,需要找到測試點所對應的內存地址。這件工作可能是最麻煩的,如果測試點是函數,那麼可以通過/proc/kallsyms接口得到需要測試函數的內存地址,當然也可以通過kallsyms_lookup_name函數找到函數的內存地址。如果測試點是函數中間的某個位置,那麼需要通過通過反匯編找到這個內存地址,這一步可以通過objdump來完成。目前,我不知道是不是有現成的程序可以完成測試點內存地址的查找工作,我覺得完全可以開發一個perl腳本對ko文件解析,從而獲取測試點的內存地址。

2,寫一個kernel module,完成信息收集,測試等工作,所有的測試代碼需要在這個kernel module中完成。

下面是我今天的一個測試程序,用Kprobe測試一個內核函數所用的jiffies時間,基本上是一個Kprobe kernel module的基本框架,僅供參考:

/*
* kprobe_jiffies.c
*/

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/kprobes.h>
#include <linux/kallsyms.h>

/* global probe object */
struct kprobe probe;

/* jiffies record */
unsigned long jiffies_enter = 0;
unsigned long jiffies_exit = 0;

/*
* enter the probe pointer
*/
static int pre_probe(struct kprobe *probe, struct pt_regs *regs)
{
jiffiesjiffies_enter = jiffies;
return 0;
}

/*
* exit the probe pointer
*/
static void post_probe(struct kprobe *probe, struct pt_regs *regs, unsigned long flags)
{
unsigned long diff;

jiffiesjiffies_exit = jiffies;
diff = jiffies_exit - jiffies_enter;
printk("spending time: %lu, enter: %lu, exit: %lu\n",
diff, jiffies_enter, jiffies_exit);
}

static int __init kprobe_jiffies_init(void)
{
probe.pre_handler = pre_probe;
probe.post_handler = post_probe;

probe.addr = (kprobe_opcode_t *) kallsyms_lookup_name("probe_function");
if (probe.addr == NULL) {
printk("Cannot find out 'dd_xor_encode_sse' in system\n");
return 1;
}

register_kprobe(&probe);
printk("register probe jffies driver.\n");
return 0;
}

static void __exit kprobe_jiffies_exit(void)
{
unregister_kprobe(&probe);
printk("unregister probe jffies driver.\n");
return;
}

module_init(kprobe_jiffies_init);
module_exit(kprobe_jiffies_exit);

MODULE_AUTHOR("xxx");
MODULE_DESCRIPTION("kernel probe driver");
MODULE_LICENSE("GPL");

我想Kprobe是個非常不錯的東西,如果在Kprobe的基礎上包裝一下,使得用戶更加容易的使用,那麼對內核程序的調試將是會發生革命性的變化。我想有時間我應該在Kprobe的基礎上做一個內核調試工具了。

Copyright © Linux教程網 All Rights Reserved