2 years ago
#47281

hanie
copy_from_user and strcmp causing kernel crashes
I have recently started working with kernel modules and I'm writing a simple character device driver. My device supports operations such as read and write and my read function is working as expected. But the kernel always crashes when I enter my write function. I'm really new to these concepts, so I don't have any idea about the cause of this problem.
In my write function, first I have to analyze user's string, then I should do some simple math operations on my long long int arr_accounts[100]
based on that string.
My first my_write()
function was this:
static ssize_t my_write(struct file *filep, const char *buffer, size_t len, loff_t *offset)
{
printk(KERN_INFO "Inside %s function\n", __FUNCTION__);
char databuf[1000000];
int error = 0;
error = copy_from_user(databuf, buffer, 1000000);
printk(KERN_INFO "Data from the user: %s\n", databuf);
if(error != 0) return -EFAULT;
if(strcmp (databuf, "r") == 0)//rest all of accounts to 2000000
{
int i = 0;
while(i < 100)
{
arr_accounts[i] = 2000000;
i++;
}
return 0;
}
}
but this didn't work at all and it caused the kernel to crash, whenever I used write method in my user-space test application.
So I changed first part of my code like this:
static ssize_t my_write(struct file *filep, const char *buffer, size_t len, loff_t *offset)
{
printk(KERN_INFO "Inside %s function\n", __FUNCTION__);
//changed part
size_t maxdatalen = 1000000, ncopied;
uint8_t databuf[maxdatalen];
if (len < maxdatalen) {
maxdatalen = len;
}
ncopied = copy_from_user(databuf, buffer, maxdatalen);
if (ncopied == 0) {
printk("Copied %zd bytes from the user\n", maxdatalen);
}
else {
printk("Could't copy %zd bytes from the user\n", ncopied);
}
databuf[maxdatalen] = 0;
//end of changed part
//second part
if(strcmp(databuf, "r") == 0) // reset all accounts to 2000000
{
int i = 0;
while(i < 100)
{
arr_accounts[i] = 2000000;
i++;
}
return 0;
}
//end of second part
}
I got the changed part of my code from a sample code I found, but I don't understand why is this working?
So my first question is what is the problem in my own code that is causing the kernel to crash?
now with this new code if second part of my code is commented everything is fine, but if I use strcmp
or strncmp
, again my kernel would crash.
So I tried different approaches like this simple one
if(databuf[0] == 'r' && databuf[1] == '\0')
and again system crash.
then I tried just this line printk(KERN_INFO "Data from the user: %d\n", databuf[0]);
and I got the same result.
My second question is why whenever I use something like databuf[0]
or even strncmp()
function, my kernel crashes?
c
linux-kernel
linux-device-driver
kernel-module
0 Answers
Your Answer