How to use copy_from_user?
ssize_t probchar_write(struct file *filp,
const char __user *data, size_t s, loff_t *off) {
printk(KERN_DEBUG "Data> |%s|\n", data); // only for debug
char chars[MAX_LENGHT];
if(s > MAX_LENGHT)
s = MAX_LENGHT;
if (copy_from_user(chars, data, s)) {
return -EFAULT;
}
printk(KERN_DEBUG "Chars> |%s|\n", chars);
return s;
}
This is dmesg o开发者_StackOverflow社区utput
[66777.956582] Data> |45
[66777.956596] |
[66777.956634] Chars> |45
[66777.956636] � Ҩ�H�� H�� |
Why the copied chain has more characters in the end?
This seems to be a write function from a device driver.
First
printk(KERN_DEBUG "Data> |%s|\n", data);
Do not do this! Do not ever directly access user data ever!
Second
char chars[s];
I doubt this is legal C. You need to either specify a size at compile time, or use kmalloc.
The copy_from_user usage is good. You should check for error and return -EFAULT. This is ok.
So just try and allocating the chars and it should work. You might also want to look at the offset, though for academic purposes that can be initially skipped.
Suppose the following: there is no \0
at the end of the provided string. You don't add one or enforce one to be present. Then you print the string after copying the "valid" data on a stack-allocated buffer that contains random garbage. That makes extra characters being printed.
Suggested check: allocate MAX_LENGTH+1 characters and after you copied the data, do chars[s]=0
.
You might want to strip that \n
character that kills the formatting of your log, too.
精彩评论