I'm curious, because I got a kernel panic after trying to access memory directly (then I found these functions).
The copy_to_user function copies a block of data from the kernel into user space. This function accepts a pointer to a user space buffer, a pointer to a kernel buffer, and a length defined in bytes. The function returns zero on success or non-zero to indicate the number of bytes that weren't transferred.
Whilst a user-space program is not allowed to access kernel memory, it is possible for the kernel to access user memory. However, the kernel must never execute user-space memory and it must also never access user-space memory without explicit expectation to do so.
You can use the copy_from_user() and copy_to_user() functions to move data between kernel space and user space.
Kernel space is strictly reserved for running a privileged operating system kernel, kernel extensions, and most device drivers. In contrast, user space is the memory area where application software and some drivers execute.
These functions do a few things:
access_ok()
) - this prevents userspace applications from asking the kernel to read/write kernel addresses;EFAULT
) instead of crashing the kernel (this is implemented by special co-operation with the page fault handler, which specifically can detect when a fault occurs in one of the user memory access functions);Those functions check whether the memory is accessible. If the kernel attempts to directly access a non-accessible address, it will panic. But in addition, the kernel and user address spaces may be different ... a valid address in the user address space may not be accessible in the kernel, and if it is it may point to kernel stuff rather than user stuff.
For more details, see https://developer.ibm.com/articles/l-kernel-memory-access
On a historical note: once upon a time there were operating systems in which the kernel was designed to be part of the user address space, and in those systems the kernel could always access user space directly. There may still be such systems, but modern linux isn't one. The user process's memory being part of the kernel address space is always an option for the implementation, of course, and that can make copy_to_user and copy_from_user a lot faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With