2014-09-26 78 views
3

在对内核泄漏进行静态分析时,我遇到了一个有趣的场景,我无法找到变量的de分配。 分配在以下功能发生(使用kmalloc的调用),如下:linux内核中潜在的内存泄漏?

static int mounts_open_common(struct inode *inode, struct file *file, 
       int (*show)(struct seq_file *, struct vfsmount *)){ 
    struct proc_mounts *p; 

    //some code// 
    *p = kmalloc(sizeof(struct proc_mounts), GFP_KERNEL);** 
    file->private_data = &p->m;//the allocated variable is escaped to file structure 
    //some code 

} 

我希望这个分配的内存固定在:

static int mounts_release(struct inode *inode, struct file *file) 
{ 
    struct proc_mounts *p = proc_mounts(file->private_data); 
    path_put(&p->root); 
    put_mnt_ns(p->ns); 
    return seq_release(inode, file); 
} 

但似乎这个功能访问分配变量来释放一些内部成员,但不是变量'p'本身。 那么这个变量的内存在哪里被释放?如果它应该在mounts_release函数中释放,那么它可能会发生内存泄漏。

+0

什么是seq_release(inode,file);电话呢? – 2014-09-26 19:01:25

+0

据我所知,mounts_release()函数应该释放与挂载设备相关的内存! – dsingh 2014-09-26 19:04:41

回答

6

如果你看看seq_release:

int seq_release(struct inode *inode, struct file *file) 
{ 
     struct seq_file *m = file->private_data; 
     kvfree(m->buf); 
     kfree(m); 
     return 0; 
} 

它用途不同呢kfree(file->private_data)

现在,file->private_data成立于mounts_open_common作为

file->private_data = &p->m; 

这就是p这是kmalloc'd在你的问题。 m成员不是一个指针,所以不应该被允许被释放。然而,它的struct proc_mounts

struct proc_mounts { 
     struct seq_file m; 
     struct mnt_namespace *ns; 
     struct path root; 
     int (*show)(struct seq_file *, struct vfsmount *); 
     void *cached_mount; 
     u64 cached_event; 
     loff_t cached_index; 
}; 

所以seq_release()执行kfree()在m成员的地址的1件,这是因为与p = kmalloc(sizeof(struct proc_mounts), GFP_KERNEL);

得到我想这是不是很友好的同一地址一个静态分析器。但没有内存泄漏。

+0

在seq_release()函数中明确指出m是seq_file类型的指针,所以kfree(m)将释放由该指针分配的内存(我认为它将在seq_open()函数中分配,正如我们原来的mounts_open_common ()函数)而不是变量p指向的父结构proc_point。 – dsingh 2014-10-02 02:01:21

+0

另外,linux使用container_of宏从其子成员中提取父指针。你可以在generic_create_cred()/ generic_free_cred函数中检查............. – dsingh 2014-10-02 02:03:06

+0

不能使用类型与第一个结构体成员类型相同的变量,它指向第一个成员的地址的结构来释放整个父结构。 – dsingh 2014-10-02 02:05:42