Kernel 您是否在内核链接_path_walk()中考虑过这段代码

Kernel 您是否在内核链接_path_walk()中考虑过这段代码,kernel,Kernel,我想打印文件的路径,所以我在link\u path\u walk(…)函数namei.c 这导致了内核恐慌 这个代码有效吗 char* path_str = NULL;*/ char* ret;*/ int flag_fsm = 0;*/ ret = strstr(name,"_FSM");*/ // add this code - start*/ if(ret != NULL){*/ path_str = (char*)kmalloc(sizeof(name),GFP_KERN

我想打印文件的路径,所以我在
link\u path\u walk(…)
函数
namei.c

这导致了内核恐慌

这个代码有效吗

char* path_str = NULL;*/
char* ret;*/
int flag_fsm = 0;*/
ret = strstr(name,"_FSM");*/


// add this code - start*/


if(ret != NULL){*/
    path_str = (char*)kmalloc(sizeof(name),GFP_KERNEL);*/
    strcpy(path_str,name);  */
    printk(KERN_INFO "%s, link_path_walk() in vfs\n",path_str);*/
    flag_fsm = 1;*/
}*/


// add this code - finish*/


while (*name=='/')*/
    name++;*/
if (!*name){*/


// add this code - start*/


if(ret != NULL){*/
    printk(KERN_INFO "%s, return from link_path_walk() in vfs\n",path_str);*/
    kfree(path_str);*/
}*/

// add this code - finish*/
    return 0;*/
} */

考虑到
name++
在那里的某个地方,可以肯定的是
name
是一个指针,而不是一个数组

因此,该代码段:

path_str = (char*)kmalloc(sizeof(name),GFP_KERNEL);
strcpy(path_str,name);
是相当危险的,因为
sizeof(name)
是指针的大小,而不是字符串的长度

例如:

char *name = "way more bytes than in a pointer,"
             " and more than the minimum kmalloc size";
这将给你带来无尽的痛苦,因为你将为路径分配四到八个字节,然后尝试将长字符串复制到其中

分配可能应该更符合以下原则:

path_str = kmalloc (strlen (name) + 1, GFP_KERNEL);
您还应该检查
kmalloc
中的返回值,如果找不到合适的内存,它可以返回NULL。这适用于userland代码,但在内核中更为重要,因为违反内存保护比在userland中更糟糕