我正在为内核模块编写 ioctls 处理程序,我想从用户空间复制数据。当我使用禁用的优化(-O0 -g
标志)编译代码时,编译器返回以下错误:./include/linux/thread_info.h:136:17: error: call to ‘__bad_copy_to’ declared with attribute error: copy destination size is too small
.我的代码:
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
时标志编译成功。快速浏览后kernel internals我找到了返回错误的地方,但我认为在我的情况下它不应该发生,因为
__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;
}
最佳答案
When I'm compiling code with disabled optimizations (
-O0 -g
flags)
不支持不进行优化的编译 (
-O0
)。但是,不要尝试设置其他支持的标志,如 -Og
你自己也一样,你必须使用像 CONFIG_CC_OPTIMIZE_FOR_DEBUGGING
这样的配置选项。 .原因是有些代码会根据配置选项的值而变化。因此,即使标志相同,您最终还是会得到损坏的构建。
关于copy_from_user() 错误 : destination size is to small,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61270898/