具有结构的copy_to_user和copy_from_user [英] copy_to_user and copy_from_user with structs

查看:146
本文介绍了具有结构的copy_to_user和copy_from_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题:例如,当我必须将结构的内容从用户空间复制到内核空间时,例如使用ioctl调用(或反之亦然)(为简单起见,代码没有错误检查):

I have a simple question: when i have to copy a structure's content from userspace to kernel space for example with an ioctl call (or viceversa) (for simplicity code hasn't error check):

typedef struct my_struct{
 int a;
 char b;
} my_struct;

用户空间:

my_struct s;
s.a = 11;
s.b = 'X';

ioctl(fd, MY_CMD, &s);

内核空间:

int my_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
             unsigned long arg)
{
...
    my_struct ks;
    copy_from_user(&ks, (void __user *)arg, sizeof(ks));
...
}

我认为用户空间(变量s)和内核空间(变量ks)中结构的大小可能不相同(未指定__attribute__((packed))).那么用sizeof宏指定copy_from_user中的字节数是否正确?我看到内核源代码中有一些未声明为压缩的结构,因此如何确保用户空间和内核空间的大小相同?

i think that size of structure in userspace (variable s) and kernel space (variable ks) could be not the same (without specify the __attribute__((packed))). So is a right thing specifing the number of byte in copy_from_user with sizeof macro? I see that in kernel sources there are some structures that are not declared as packed so, how is ensured the fact that the size will be the same in userspace and kernelspace?

谢谢大家!

推荐答案

用户空间结构应该来自内核头文件,因此用户和内核空间中的结构定义应该相同.你有什么真实的例子吗?

The userspace structure should come from kernel header, so struct definition should be the same in user and kernel space. Do you have any real example ?

当然,如果您在ABI的两侧使用不同的包装选项,则无论遇到什么情况,您都将遇到麻烦.这里的问题不是sizeof.

Of course, if you play with different packing options on two side of an ABI, whatever it is, you are in trouble. The problem here is not sizeof.

如果您的问题是:打包选项是否会影响二进制接口,答案是肯定的. 如果您的问题是,我该如何解决包装不匹配的问题,请提供更多信息

If your question is : does packing options affect binary interface, the answer is yes. If your question is, how can I solve a packing mismatch, please provide more information

这篇关于具有结构的copy_to_user和copy_from_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆