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 <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/kthread.h>
#include <linux/slab.h>
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://棧回溯,找到泄漏地址
[<bf000018>] memory_kthread_alloc+0x18/0x3c [kmemleak]
[<c00368cc>] kthread+0xdc/0xf0
[<c000eb48>] ret_from_fork+0x14/0x2c
[<ffffffff>] 0xffffffff