我正在为内核模块编写ioctls处理程序,我想从用户空间复制数据。当我使用禁用的优化(-O0 -g
标志(编译代码时,编译器返回以下错误:CCD_ 2。我的代码:
struct my_struct {
int x;
int y;
}
...
long ioctl_handler(struct file *filp, unsigned int cmd, unsigned long arg) {
switch(cmd) {
case MY_IOCTL_ID:
struct my_struct *cmd_info = vmalloc(sizeof(struct my_struct));
if (!cmd_info)
//error handling
if (copy_from_user(cmd_info, (void __user*)arg, sizeof(struct my_struct)))
//error handling
//perform some action
vfree(cmd_info);
return 0;
}
}
当我在堆栈上声明变量(struct my_struct cmd_info;
(而不是使用vmalloc时,问题消失了,模块编译时没有任何错误,但我希望避免这种解决方案。此外,当使用-O2
标志编译成功时。
在快速查看了内核内部之后,我找到了返回错误的位置,但我认为在我的情况下不应该发生错误,因为__compiletime_object_size(addr)
等于sizeof(struct my_struct)
int sz = __compiletime_object_size(addr);
if (unlikely(sz >= 0 && sz < bytes)) {
if (!__builtin_constant_p(bytes))
copy_overflow(sz, bytes);
else if (is_source)
__bad_copy_from();
else
__bad_copy_to();
return false;
}
当我使用禁用的优化(
-O0 -g
标志(编译代码时
不支持无优化编译(-O0
(。但是,也不要尝试自己设置-Og
等其他支持的标志,而是必须使用CONFIG_CC_OPTIMIZE_FOR_DEBUGGING
等配置选项。
原因是存在根据配置选项的值而更改的代码。因此,即使标志是相同的,您最终还是会得到损坏的构建。