如何使用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;
}
这是 dmesg 输出
[66777.956582] Data> |45
[66777.956596] |
[66777.956634] Chars> |45
[66777.956636] � Ҩ�H�� H�� |
为什么复制的链最后有更多字符?
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 output
[66777.956582] Data> |45
[66777.956596] |
[66777.956634] Chars> |45
[66777.956636] � Ҩ�H�� H�� |
Why the copied chain has more characters in the end?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这似乎是设备驱动程序的写入功能。
首先
不要这样做!永远不要直接访问用户数据!
第二我怀疑这是合法的C。您需要在编译时指定大小,或者使用kmalloc。
copy_from_user 的用法很好。您应该检查错误并返回 -EFAULT。这没关系。
所以只要尝试分配字符就可以了。您可能还想查看偏移量,但出于学术目的,最初可以跳过。
This seems to be a write function from a device driver.
First
Do not do this! Do not ever directly access user data ever!
SecondI 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.
假设以下情况:提供的字符串末尾没有
\0
。您不必添加一项或强制要求一项存在。然后,在将“有效”数据复制到包含随机垃圾的堆栈分配缓冲区上后打印字符串。这会导致打印额外的字符。建议检查:分配 MAX_LENGTH+1 个字符,并在复制数据后执行
chars[s]=0
。您可能还想删除会破坏日志格式的
\n
字符。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.