Linux内核:copy_from_user-带有指针的结构 [英] Linux Kernel: copy_from_user - struct with pointers

查看:494
本文介绍了Linux内核:copy_from_user-带有指针的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了某种字符设备,并且需要copy_ from_user函数的帮助.

I've implemented some kind of character device and I need help with copy_ from_user function.

我有一个结构:

struct  my_struct{

int a;

int *b;
};

我在用户空间初始化它,并使用'write'函数将指向my_struct的指针传递给我的char设备.在内核的空间字符设备的写入"功能中,我将其从* char强制转换为这种结构.我使用kmalloc为结构分配了一些内存,并对它执行了copy_from_user.

I initialize it in user space and pass pointer to my_struct to my char device using 'write' function. In Kernel's Space character device 'write' function I cast it from a *char to this kind of structure. I alloc some memory for a struct using kmalloc and do copy_from_user into it.

对于简单的'int a'很好,但是它仅复制b值的指针(地址),而不复制b指向的值,因此我现在在内核空间中,并且正在使用指向a的指针用户空间内存.这是不正确的吗?我不应该直接访问用户空间指针,而必须在结构中使用copy_from_user每个指针,然后使用copy_to_user函数复制回"read"函数中的每个指针?

It's fine for simple 'int a', but it copies only pointer (address) of b value, not value pointed by b, so I'm now in Kernel Space and I'm working with a pointer that points to a user space memory. Is this incorrect and I shouldn't access to user space pointer directly and I have to copy_from_user every single pointer in my struct and then copy back every pointer in "read" function using copy_to_user function?

推荐答案

无论如何获取指针,都必须始终使用copy_from_user和类似的命令从内核空间访问用户空间内存.由于b是指向用户空间内存的指针,因此必须使用copy_from_user进行访问.

You must always use copy_from_user and similar to access user space memory from kernel space, regardless of how you got the pointer. Since b is a pointer to user space memory, you must use copy_from_user to access it.

这些功能执行两项重要的附加任务:

These functions do two important additional tasks:

  1. 它们确保指针指向用户空间而不是内核空间.如果没有此检查,则用户空间程序可能能够绕过正常的安全性读取或写入内核内存.
  2. 它们可以正确处理页面错误.通常,内核模式下的页面错误会导致OOPS或恐慌-copy_*_user函数系列具有特殊的覆盖,可以告诉PF处理程序一切正常,并且应该正常处理该错误;并且如果IO无法解决故障(即通常会导致SIGSEGVSIGBUS的原因),请返回错误代码,以便其调用者可以执行任何必要的清除操作,然后再使用-EFAULT返回用户空间
  1. They make sure the pointer points into user space and not kernel space. Without this check, user space programs might be able to read or write to kernel memory, bypassing normal security.
  2. They handle page faults correctly. Normally a page fault in kernel mode will result in an OOPS or panic - the copy_*_user family of functions have a special override that tells the PF handler that all is well, and the fault should be handled normally; and in the event that the fault cannot be satisfied by IO (ie, what would normally cause a SIGSEGV or SIGBUS), return an error code instead so their caller can do any necessary cleanup before returning to userspace with -EFAULT.

这篇关于Linux内核:copy_from_user-带有指针的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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