copy_to_user 与 memcpy [英] copy_to_user vs memcpy

查看:29
本文介绍了copy_to_user 与 memcpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直被告知(在书籍和教程中)在将数据从内核空间复制到用户空间时,我们应该使用 copy_to_user() 而使用 memcpy() 会导致系统出现问题.最近我错误地使用了 memcpy() 并且它工作得很好,没有任何问题.为什么我们应该使用 copy_to_user 而不是 memcpy()

I have always been told(In books and tutorials) that while copying data from kernel space to user space, we should use copy_to_user() and using memcpy() would cause problems to the system. Recently by mistake i have used memcpy() and it worked perfectly fine with out any problems. Why is that we should use copy_to_user instead of memcpy()

我的测试代码(内核模块)是这样的:

My test code(Kernel module) is something like this:

static ssize_t test_read(struct file *file, char __user * buf,
             size_t len, loff_t * offset)
{
    char ani[100];

    if (!*offset) {
        memset(ani, 'A', 100);
        if (memcpy(buf, ani, 100))
            return -EFAULT;
        *offset = 100;
        return *offset;
    }

    return 0;
}

struct file_operations test_fops = {
    .owner = THIS_MODULE,
    .read = test_read,
};

static int __init my_module_init(void)
{
    struct proc_dir_entry *entry;

    printk("We are testing now!!
");
    entry = create_proc_entry("test", S_IFREG | S_IRUGO, NULL);
    if (!entry)
        printk("Failed to creats proc entry test
");

    entry->proc_fops = &test_fops;
    return 0;
}
module_init(my_module_init);

从用户空间应用程序,我正在阅读我的 /proc 条目,一切正常.

From user-space app, i am reading my /proc entry and everything works fine.

查看 copy_to_user() 的源代码说它也是简单的 memcpy(),我们只是尝试使用 access_ok 检查指针是否有效并执行 memcpy.

A look at source code of copy_to_user() says that it is also simple memcpy() where we are just trying to check if the pointer is valid or not with access_ok and doing memcpy.

所以我的理解目前是,如果我们确定我们传递的指针,memcpy()总是可以用来代替copy_to_user.

如果我的理解不正确,请纠正我,并且任何 copy_to_user 工作和 memcpy() 失败的示例都非常有用.谢谢.

Please correct me if my understanding is incorrect and also, any example where copy_to_user works and memcpy() fails would be very useful. Thanks.

推荐答案

有几个原因.

首先,安全.因为内核可以写入它想要的任何地址,如果你只是使用你得到的用户空间地址并使用 memcpy,攻击者可以写入另一个进程的页面,这是一个巨大的安全问题.copy_to_user 检查目标页面是否可被当前进程写入.

First, security. Because the kernel can write to any address it wants, if you just use a user-space address you got and use memcpy, an attacker could write to another process's pages, which is a huge security problem. copy_to_user checks that the target page is writable by the current process.

还有一些架构方面的考虑.例如,在 x86 上,目标页面必须固定在内存中.在某些体系结构上,您可能需要特殊说明.等等.Linux 内核非常可移植的目标需要这种抽象.

There are also some architecture considerations. On x86, for example, the target pages must be pinned in memory. On some architectures, you might need special instructions. And so on. The Linux kernels goal of being very portable requires this kind of abstraction.

这篇关于copy_to_user 与 memcpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆