内存泄漏工具kmemleak 使用方法

1.kmemleak使用方法

https://www.cnblogs.com/arnoldlu/p/8568090.html

2.英文手册

https://www.kernel.org/doc/html/latest/dev-tools/kmemleak.html

3.原理分析

http://blog.chinaunix.net/uid-26859697-id-5758036.html

参考上面3个文章,但是编译内核以后,一直  /sys/kernel/debug/kmemleak 下找不到。后来发现开机log打印:

[    0.000000] kmemleak: Kernel memory leak detector disabled
[    0.000550] kmemleak: Early log buffer exceeded (1147), please increase DEBUG_KMEMLEAK_EARLY_LOG_SIZE

后续发现 .config中DEBUG_KMEMLEAK_EARLY_LOG_SIZE设置默认值为400,更到到10000后运行正常。

实例如下:

1.写出内存泄漏的相关代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

struct task_struct *mem_alloc_kthread;
int memory_kthread_alloc(void *arg)
{
	char *buf = NULL;
	while(!kthread_should_stop()) {
		buf = kmalloc(128, GFP_KERNEL);
		ssleep(5);
	}
	/* Should never get here */
	BUG_ON(1);
	return 0;
}

static int kmemleak_dbg_init(void)
{

	mem_alloc_kthread = kthread_create(memory_kthread_alloc, NULL, "mem_kthread");
	if (!IS_ERR(mem_alloc_kthread)) {
		wake_up_process(mem_alloc_kthread);
	}

	return 0;
}

static void kmemleak_dbg_exit(void)
{

	return 0;
}


module_init(kmemleak_dbg_init);

module_exit(kmemleak_dbg_exit);

MODULE_LICENSE("GPL");

2. 插入驱动后, echo scan > /sys/kernel/debug/kmemleak 

3.然后观察,浏览内存泄漏情况:

   cat /sys/kernel/debug/kmemleak

unreferenced object 0xcbd86580 (size 128): //泄漏128字节
  comm "mem_kthread", pid 1676, jiffies 122870 (age 591.900s)
  hex dump (first 32 bytes):
    00 00 f2 cb 00 10 00 00 00 00 00 00 00 00 00 00  ................
    00 00 00 00 00 00 00 00 02 00 00 64 00 00 00 00  ...........d....
  backtrace://栈回溯,找到泄漏地址
    [] memory_kthread_alloc+0x18/0x3c [kmemleak]
    [] kthread+0xdc/0xf0
    [] ret_from_fork+0x14/0x2c
    [] 0xffffffff

 

你可能感兴趣的:(kernel)