copy_to_user(struct * file,const char __user * buf,size_t len,loff_t * off_t)时如何摆脱警告

时间:2013-01-30 18:03:10

标签: c linux-kernel linux-device-driver

这是null驱动程序的myread和mywrite函数。

#define SIZE 6
    static char c[SIZE];

    static ssize_t myread(struct file *file,char __user *buf,size_t len, loff_t  *fops)
{
    printk(KERN_INFO"My read with length %zd \n",len);

    memset(buf,0,SIZE);
    //return is status i.e., 0.
    if(copy_to_user(buf,c,SIZE) != 0)
        return -EFAULT;
    else if (*fops > 0)
        return 0;
        else
            *fops += SIZE;
            return SIZE;
}


static ssize_t mywrite(struct file *file, const char __user *buf, size_t len, loff_t *fops)
    {
        printk(KERN_INFO "My write \n");
        memset(c,0,SIZE);
            if (len <= SIZE)`
            {`
        if(copy_from_user(c,buf,len) != 0)
            return -EFAULT;
        else
            //number of bytes written to the kernel space is returned
            return len;`
            }
            else 
                    return -EFAULT;`
    }

当我构建模块时,它会抛出这样的警告:

  

/usr/src/linux-headers-3.2.0-36-generic-pae/arch/x86/include/asm/uaccess_32.h:在函数'mywrite'中:   /usr/src/linux-headers-3.2.0-36-generic-pae/arch/x86/include/asm/uaccess_32.h:211:26:警告:调用带有属性警告声明的'copy_from_user_overflow':copy_from_user()缓冲区大小无法证明是正确的[默认情况下启用]

请指导我如何摆脱这个警告。就像我在哪里做错了..

1 个答案:

答案 0 :(得分:2)

您的问题是传入lenmyread功能的mywrite可能大于SIZE;如果是这种情况,copy_from_user / copy_to_user将溢出您的数组并读取/写入其他附近的内存。您的代码需要将副本的长度限制为不超过其访问的内核内存的长度。