3

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;
}
mmichal10
  • 322
  • 2
  • 13

1 Answers1

4

When I'm compiling code with disabled optimizations (-O0 -g flags)

Compiling without optimizations (-O0) is not supported. However, do not try to set other supported flags like -Og yourself either, instead you have to use configuration options like CONFIG_CC_OPTIMIZE_FOR_DEBUGGING.

The reason is that there is code which changes depending on the value of the configuration options. So even if the flags are the same, you will end up with broken builds nevertheless.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • So I need to recompile kernel with `CONFIG_CC_OPTIMIZE_FOR_DEBUGGING` enabled and then all modules (even my own custom out of tree module) builded on such system will be compiled with debug symbols by default? – mmichal10 Apr 17 '20 at 12:30
  • 2
    @mmichal10 That's right! Always build your kernel (and its modules) with the kernel build system, do not call `gcc` or use flags on your own unless you *really* know what you are doing. Modules are really part of the kernel, and they should be compiled exactly the same way as the kernel. – Acorn Apr 17 '20 at 12:44