我在用户空间中有一个程序,它在我的内核模块中写入sysfs文件。我已经隔离出,崩溃的来源很可能是这个特定的函数,因为当我在到达这一点之前运行用户代码时,它不会崩溃,但当我添加编写代码时,它崩溃的概率很高。我怀疑我解析字符串的方式会导致内存错误,但我不明白为什么。
我正在开发内核版本3.2和python 2.7
我所说的崩溃是指整个系统冻结,我必须重新启动它或将VM恢复到以前的快照。
用户编写代码(Python):
portFile = open(realDstPath, "w")
portFile.write(str(ipToint(srcIP)) + "|" + str(srcPort) + "|")
portFile.close()内核代码:
ssize_t requestDstAddr( struct device *dev,
struct device_attribute *attr,
const char *buff,
size_t count)
{
char *token;
char *localBuff = kmalloc(sizeof(char) * count, GFP_ATOMIC);
long int temp;
if(localBuff == NULL)
{
printk(KERN_ERR "ERROR: kmalloc failed\n");
return -1;
}
memcpy(localBuff, buff, count);
spin_lock(&conntabLock);
//parse values passed from proxy
token = strsep(&localBuff, "|");
kstrtol(token, 10, &temp);
requestedSrcIP = htonl(temp);
token = strsep(&localBuff, "|");
kstrtol(token, 10, &temp);
requestedSrcPort = htons(temp);
spin_unlock(&conntabLock);
kfree(localBuff);
return count;
}发布于 2019-02-19 17:56:27
仔细看看strsep。来自man strsep
char *strsep(char **stringp, const char *delim);
... and *stringp is updated to point past the token. ...在您的代码中,您需要:
char *localBuff = kmalloc(sizeof(char) * count, GFP_ATOMIC)
...
token = strsep(&localBuff, "|");
...
kfree(localBuff);在strsep调用之后更新localBuff变量。因此,对kfree的调用不是使用相同的指针。这允许非常奇怪的行为。使用临时指针保存strsep函数的状态。并检查其返回值。
https://stackoverflow.com/questions/54763043
复制相似问题