how can I protect a heap memory in linux?
c++, linux, memory-management
Solution
Yes, mmap and mprotect are the right functions. I do not understand what's the problem with your current approch, i.e., what you mean by "For that I have tried with memalign() with mprotect().But from the memalignment what can I get , memalign allocates memory away from the process heap."
Below is an example how to create 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;
}
Problem
I want to make a chunck of heap memory read-only. For that I have tried with `memalign()` with `mprotect()`.But from the memalignment what can I get , memalign allocates memory away from the process heap. I want to make some portion of the heap read-only. Any help on that ? `malloc()->mmap()->mprotect()` a hypothetical thought , but not sure if that can help ... Any sample code to implement above ? I need to protect the memory address within the heap. with malloc() i get address around 0x10012008 whereas with mmap() it is 0xf7ec9000.My intention is to make a part of heap-meory to be read only to catch any trampler that might try to run through that heap.