我正在编写两个基本的系统调用。一个将包含用户空间字符串的节点添加到哈希表,另一个转储表的内容。
添加一些项目并调用转储函数后,它打印一个项目然后崩溃并显示BUG: unable to handle kernel paging request at
我试图删除与用户空间字符串相关的所有代码,以确保错误不是来自于此。我添加了一个只有 next
和 key
的 table_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/