Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc results in segmentation fault after mprotect

I'm getting a segmentation fault the first time I call malloc() after I protect a memory region with mprotect(). This is a code sniplet that does the memory allocation the the protection:

#define PAGESIZE 4096
void* paalloc(int size){   // Allocates and aligns memory
        int type_size =  sizeof(double);
        void* p;
        p = malloc(type_size*size+PAGESIZE-1);
        p = (void*)(((long) p + PAGESIZE-1) & ~(PAGESIZE-1));
        return p;
}
void aprotect(int size, void* array){  // Protects memory after values are set
        int type_size = sizeof(double);
        if (mprotect(array, type_size*size, PROT_READ)) {
                perror("Couldn't mprotect");
        }
}

I want to use mprotect to avoid anything writing into my arrays (which are pre-calculated sine/cosine values). Is this a stupid idea?

like image 403
hanno Avatar asked Dec 02 '25 09:12

hanno


2 Answers

mprotect can only work in units of pages, as you probably already know. In this case, you're correctly aligning the start of your block to a page boundary, but what you're not doing is ensuring that your allocation extends to the end of the last page you're going to use in it.

This means that your mprotect is protecting data past the end of your allocation (right to the end of that page), which is space that the next malloc call assumes it can write to.

The easiest fix is to change the PAGE_SIZE - 1 in the malloc call to PAGE_SIZE * 2.

like image 89
caf Avatar answered Dec 04 '25 01:12

caf


I would recommend you just use mmap directly to create an anonymous mapping, and then call mprotect on that after you finishing writing to the array. Because you are always allocating entire pages, it doesn't make sense to use the heap at all. It's primary purpose is to deal with allocation and deallocation of small(ish) objects. When dealing with page blocks it just adds unnecessary overhead.

like image 36
Scott Wisniewski Avatar answered Dec 04 '25 00:12

Scott Wisniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!