【发布时间】:2019-09-29 07:24:15
【问题描述】:
我正在编写两个基本的系统调用。一个将包含用户空间字符串的节点添加到哈希表中,另一个转储表的内容。
添加几个项目并调用转储函数后,它打印一个项目然后崩溃BUG: unable to handle kernel paging request at
我尝试删除与用户空间字符串相关的所有代码,以确保错误不是来自该字符串。我添加了一个只有next 和key 的table_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是否总是以空值终止字符串?)?