I'm writing ioctls handler for kernel module and I want to copy data from user space. When I'm compiling code with disabled optimizations (-O0 -g
flags) compiler returns following error:
./include/linux/thread_info.h:136:17: error: call to β__bad_copy_toβ declared with attribute error: copy destination size is too small
. My code:
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;
}
}
When I declare variable on stack (struct my_struct cmd_info;
) instead of using vmalloc problem disappears and module is compiled without any errors, but I would like avoid this solution. Also when using -O2
flag compilation is successful.
After taking a quick look at kernel internals I found place from which error is returned but I believe it should not occur in my case because __compiletime_object_size(addr)
is equal 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;
}