【问题标题】:Kernel hashtable crash while iterating迭代时内核哈希表崩溃
【发布时间】:2019-09-29 07:24:15
【问题描述】:

我正在编写两个基本的系统调用。一个将包含用户空间字符串的节点添加到哈希表中,另一个转储表的内容。

添加几个项目并调用转储函数后,它打印一个项目然后崩溃BUG: unable to handle kernel paging request at

我尝试删除与用户空间字符串相关的所有代码,以确保错误不是来自该字符串。我添加了一个只有nextkeytable_node,但我遇到了同样的错误。

我有一种感觉,我忽略了一些非常简单的事情。我添加或走动表格的方式有什么特别之处吗?

#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/slab.h>
#include <linux/hashtable.h>
#include <linux/uaccess.h>
#include <asm/uaccess.h>

DEFINE_HASHTABLE(table, 10);

struct table_node {

    unsigned long key;
    struct hlist_node next;
    char * name;
};

SYSCALL_DEFINE1(add_to_table, const char *, name) {

    struct table_node newNode;
    long strLen;
    long copied;
    int maxLen = 100;

    // Get length of userspace string
    strLen = strnlen_user(name, maxLen); 
    if (strLen <=0 || strLen > maxLen){
       return -EINVAL;
    }

    char s[strLen];
    newNode.name = s;

   // Copy string to kernel space
   copied = strncpy_from_user(newNode.name, name, strLen); 
   if (copied <= 0 || copied > maxLen){
       return -EINVAL;
   }

    newNode.key = (hash(name) % HASH_SIZE(table));

    hash_add(table, &newNode.next, newNode.key);

    return 0;
}

SYSCALL_DEFINE0(dump_table) {

    int bkt = 0;
    table_node * ptr = NULL;

    // Print each entry in the hash table
    hash_for_each_(table, bkt, ptr, next){
        printk("\tkey=%lu,bucket %d\n", ptr->key bkt);
    }

    return 0;
}

感谢您的帮助!

【问题讨论】:

  • struct table_node newNode;char s[strLen]; newNode.name = s;都是局部变量,函数返回后就不存在了。您不需要动态分配它们吗?另外,您没有错误吗 - 当strnlen_user(name 返回maxLen 时,newNode.name 不会以空值终止(strncpy_from_user 是否总是以空值终止字符串?)?

标签: c linux hashtable


【解决方案1】:

Kamil 的解决方案奏效了。

我忘了动态分配内存。添加这两行解决了我的问题。

table_node *newNode = kmalloc(sizeof(table_node), GFP_KERNEL);

newNode-fname = kmalloc(strLen * sizeof(char)+1, GFP_KERNEL);

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 1970-01-01
    • 2019-06-23
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多