'strsep' 导致 Linux 内核冻结

'strsep' causing Linux kernel freeze

我在用户空间中有一个程序写入内核模块中的 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;
}

仔细看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 函数的状态。并检查它的 return 值。