【问题标题】:Example of "copy_from_user" in Linux Kernel (just copying a pointer to an int)Linux 内核中的“copy_from_user”示例(仅复制指向 int 的指针)
【发布时间】:2019-01-28 02:10:22
【问题描述】:

我知道有很多关于此的帖子,但大多数都非常复杂,我希望有人可以帮助我完成我的简单示例。

我正在编写一个系统调用,我正在编写的函数具有以下形式:

SYS_CALLDEFINE4(calc, int, param1, int, param2, char, operation, int*, result) 
{
//Do system call stuff here
} 

我知道指向 int 的指针会有问题,因为用户空间应用程序可能已经传递了一个指向重要系统空间的指针(我们不想弄乱它)。所以我需要使用copy_from_user 函数。

有人可以举例说明如何在确保可以正确访问该指针的上下文中正确使用这两个函数吗?

【问题讨论】:

    标签: linux kernel system-calls


    【解决方案1】:

    替换

    *result = <value>;
    

    int local_value = <value>;
    if (copy_to_user(&local_value, result, sizeof(*result)))
    {
        // 'result' points to inaccessible memory.
    }
    // assigning 'result' has been successful.
    

    另外,由于result 的大小很小(在您的情况下为int),您可以使用put_user,它更简单有效:

    if (put_user(<value>, result) < 0)
    {
        // 'result' points to inaccessible memory.
    }
    // assigning 'result' has been successful.
    

    【讨论】:

    • 假设我更新了指针“结果”指向的值。在这种情况下,我需要copy_to_user 电话吗?我的直觉是否定的,因为我没有将我在内核空间中声明的指针返回给用户。我的理解是copy_to_user只用在那个场景中。
    猜你喜欢
    • 1970-01-01
    • 2017-06-19
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多