简体   繁体   中英

'strsep' causing Linux kernel freeze

I have a program in userspace that writes to a sysfs file in my kernel module. I have isolated that with high probability the source of the crash is this specific function, as when I run the user code before reaching this point it doesn't crash, but when I add the write code it crashes with high probability. I suspect the way I parse the string causes a memory error but I don't understand why.

I am working on kernel version 3.2 and python 2.7

By crash I mean the whole system freezes up and I have to either restart it or restore the VM to a previous snapshot.

user write code(python):

portFile = open(realDstPath, "w")
portFile.write(str(ipToint(srcIP)) + "|" + str(srcPort) + "|")
portFile.close()

kernel code:

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;
}

Look closely at strsep . From man strsep :

char *strsep(char **stringp, const char *delim);

... and *stringp is updated to point past the token. ...

In your code you do:

char *localBuff = kmalloc(sizeof(char) * count, GFP_ATOMIC)
...
token = strsep(&localBuff, "|");
...
kfree(localBuff);

The localBuff variable is updated after the strsep call. So the call to kfree is not with the same pointer. That allows for very strange behaviors. Use a temporary pointer to save the state of strsep function. And check it's return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM