Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`mprotect` fails after many invocations

I invoke mprotect frequently in my program, and I find the program fails after a while. I guess it is due to too many mprotect calls, So I wrote a test to verify:

#define pagesize 4096
int main(){
  while(1){
     buffer = memalign(pagesize, 4 * pagesize);// allocate some buffer
     mprotect(buffer, pagesize, PROT_NONE)// make the first page inaccessible
  }
}

After around 30 thousand iterations, mprotect returns -1, regardless of the size of the buffer.

Can anybody explain why and how to resolve it? My guess is mprogtect consumes kernel resources and there is some constraint for each process, but not sure.

like image 434
Infinite Avatar asked Apr 23 '14 01:04

Infinite


1 Answers

Apparently, there's a kernel parameter controlling the number of distinct mappings a process can have, available at /proc/sys/vm/max_map_count. The typical default number of mappings on most distros is 64k - consistent with mprotect failing at around 30k iterations (one mapping per memalign, another per mprotect + some normal system mappings). Increasing that limit will allow you to allocate and protect more memory areas.

like image 52
oakad Avatar answered Nov 07 '22 05:11

oakad