I tried to create MAP_GROWSDOWN
mapping with the expectation it would grow automatically. As specified in the manual page:
MAP_GROWSDOWN
This flag is used for stacks. It indicates to the kernel virtual memory system that the mapping should extend downward in memory. The return address is one page lower than the memory area that is actually created in the process's virtual address space. Touching an address in the "guard" page below the mapping will cause the mapping to grow by a page. This growth can be repeated until the mapping grows to within a page of the high end of the next lower mapping, at which point touching the "guard" page will result in a
SIGSEGV
signal.
So I wrote the following example to test the mapping growing:
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdio.h>
int main(void){
char *mapped_ptr = mmap(NULL, 4096,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_STACK | MAP_GROWSDOWN,
-1, 0);
if(mapped_ptr == MAP_FAILED){
int error_code = errno;
fprintf(stderr, "Cannot do MAP_FIXED mapping."
"Error code = %d, details = %s\n", error_code, strerror(error_code));
exit(EXIT_FAILURE);
}
volatile char *c_ptr_1 = mapped_ptr; //address returned by mmap
*c_ptr_1 = 'a'; //fine
volatile char *c_ptr_2 = mapped_ptr - 4095; //1 page below the guard
*c_ptr_2 = 'b'; //crashes with SEGV
}
So I got SEGV
instead of growing the mapping. What does it mean by growing here?
mapped_ptr
is already in the guard page. Touch it first before touching a page below it. – Makomapped_ptr
. It was fined. But if I touchmapped_ptr - 4095
after this it segfaults anyway (I expected it to grow further). – Abstain4.18.0-24-generic
Ubuntu 18.04. – Abstainmmap
call (I suspect the guard page mapping is done viammap
with flagsMAP_FIXED
andPROT_NONE
protection). If so then it is clear what the patch author was talking about. – Abstain