How can I protect a bunch of memory in Linux?

I want to make a piece of read-only heap memory. For this, I tried with memalign() with mprotect() . But from memalignment, what can I get, memalign allocates memory from the process heap.

I want to make part of the heap read-only. Any help on this?

malloc()->mmap()->mprotect() hypothetical thought, but not sure if this can help ... Any example code to implement above?

I need to protect the memory address inside the heap. with malloc () I get the address about 0x10012008, while with mmap () it is 0xf7ec9000. My intention is to make part of the heap to read only to catch any trampler that might try to go through that heap.

+7
source share
2 answers

Yes, mmap and mprotect are the correct functions. I don’t understand what the problem is with your current convention, that is, what you mean by "For this I tried with memalign () with mprotect (). But from memalignment, what can I get, memalign allocates memory from the process heap."

The following is an example of creating a write-protected memory area:

 #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> static int alloc_size; static char* memory; void segv_handler (int signal_number) { printf ("memory accessed!\n"); mprotect (memory, alloc_size, PROT_READ | PROT_WRITE); } int main () { int fd; struct sigaction sa; /* Install segv_handler as the handler for SIGSEGV. */ memset (&sa, 0, sizeof (sa)); sa.sa_handler = &segv_handler; sigaction (SIGSEGV, &sa, NULL); /* Allocate one page of memory by mapping /dev/zero. Map the memory as write-only, initially. */ alloc_size = getpagesize (); fd = open ("/dev/zero", O_RDONLY); memory = mmap (NULL, alloc_size, PROT_WRITE, MAP_PRIVATE, fd, 0); close (fd); /* Write to the page to obtain a private copy. */ memory[0] = 0; /* Make the memory unwritable. */ mprotect (memory, alloc_size, PROT_NONE); /* Write to the allocated memory region. */ memory[0] = 1; /* All done; unmap the memory. */ printf ("all done\n"); munmap (memory, alloc_size); return 0; } 
+4
source

You should use mmap() directly and completely discard malloc() . And, depending on your needs, you may not need mprotect() :

 ptr = mmap(NULL, length, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); 

In the latest versions of kernels and libc, it will allocate the requested amount of memory with the specified protection mode - in this case, the allocated memory area can be read, but not written. If you only need a zero page, this will do. Otherwise, the resulting area will be correctly aligned, and you can use mprotect() to unprotect for short periods of time in a controlled way ...

+2
source

All Articles