【问题标题】:Do you think about this code in kernel link_path_walk()您是否考虑过内核中的这段代码 link_path_walk()
【发布时间】:2014-01-03 15:51:45
【问题描述】:

我想打印文件的路径,所以我在link_path_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;*/
} */

【问题讨论】:

    标签: kernel


    【解决方案1】:

    鉴于您在某处有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 分配四个或八个字节,然后尝试将那个长字符串复制到其中。

    分配应该更接近于:

    path_str = kmalloc (strlen (name) + 1, GFP_KERNEL);
    

    你还应该检查kmalloc的返回值,如果找不到合适的内存,它可以返回NULL。这适用于用户空间代码,但在内核中更重要,因为违反内存保护的情况比用户空间更糟糕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 2016-10-26
      相关资源
      最近更新 更多