Reputation: 61
is that allowed to allocate user space memory from kernel space? I know that process in Linux uses virtual memory and virtual addresses. And there is a protection which can`t allow using of memory of different process (it raises segmentation fault). So, there is no way to allocate a buffer and return a valid pointer to it to user space process?
Upvotes: 0
Views: 2118
Reputation: 41
Direct allocation of user space memory from kernel space is not allowed. This is because kernel space and user space are two isolated spaces, each with its own virtual address space. If kernel space could allocate user space memory directly, it could bypass the kernel's security protections and lead to a security vulnerability.
However, it is possible to use the mmap() system call in kernel space to create a shared memory region that can be used by both kernel space processes and user space processes. mmap() system call will return a pointer to the shared memory region, which can be used by the user space process. Like this:
#include <sys/mman.h
int main() {
// Create a shared memory area, 1 MB in size.
void *ptr = mmap(NULL, 1024 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
// Check if the shared memory region was created successfully.
if (ptr == MAP_FAILED) {
return -1;
}
// Return the pointer to the shared memory region to user space.
return (int)ptr; }
}
Upvotes: 0
Reputation: 12668
is that allowed to allocate user space memory from kernel space? I know that process in Linux uses virtual memory and virtual addresses. And there is a protection which can`t allow using of memory of different process (it raises segmentation fault). So, there is no way to allocate a buffer and return a valid pointer to it to user space process?
Memory allocation routines have normally a return value, which is the pointer (in virtual memory coordinates) that the kernel has allocated the value. If the user is not asking for new memory, it's not normall to allocate memory for him in user space without telling where it has been allocated....
But you can do it. I think the best way to know how to do it is to study how the mmap(2)
system call works (as it maps allocated memory to user space, and returns a user space pointer for the user to know where it has been allocated), and use the internal kernel function used to allocate user memory. The kernel malloc group of routines need to know how to map (even for the kernel virtual space, as the kernel also runs in a virtual address memory space) memory pages into virtual memory addresses. Not doing that leads to unaccessable memory.
Upvotes: 1