c - 迭代时内核哈希表崩溃

标签 c linux hashtable

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

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

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

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

#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;
}

谢谢你的帮助!

最佳答案

Kamil 的解决方案奏效了。

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

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

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

关于c - 迭代时内核哈希表崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093617/

相关文章:

c++ - c、共享库中的c++内存

c - 了解 SPARC 汇编中函数调用的基本示例

c - 缓冲区溢出;避免溢出攻击

optimization - 多少个哈希桶

java - 为什么我的 HashMap 识别出不应该是键的散列键?

java - 为什么键在 Java 中是不可变的?

c++ - 尝试使用 tcc 针对 gcc 生成的 .o 文件编译源代码时出现奇怪的行为

linux - 如何以特定方式重命名目录。巴什

Linux套接字操作

c++ - 将字符串数组转换为 int 数组