'strsep'导致Linux内核冻结

问题描述 投票:1回答:1

我在用户空间中有一个程序,它写入我的内核模块中的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;
}
python c linux-kernel kernel-module
1个回答
4
投票

仔细看看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);

localBuff调用之后更新strsep变量。所以对kfree的调用不是同一个指针。这允许非常奇怪的行为。使用临时指针保存strsep函数的状态。并检查它的返回值。

© www.soinside.com 2019 - 2024. All rights reserved.