【发布时间】:2020-04-17 11:47:23
【问题描述】:
我正在为内核模块编写 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;
}
【问题讨论】: