Most portable way to use mprotect() on allocated memory

670 views Asked by At

I was wondering if there is a portable way to dynamically allocate memory and then restrict read/write access to a portion of this memory, e. g. using the POSIX function mprotect(). I can think of the following approaches:

  1. Allocate memory using mmap(), i. e. mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0): Here, the memory protection flags can already be given in the initial allocation call, and can optionally be modified later using mprotect().
    Problem: MAP_ANONYMOUS is not specified by POSIX, although it’s supposedly supported by “almost all” or “most” systems.
  2. Apparently, using mmap() on /dev/zero is an alternative to MAP_ANONYMOUS. This would make the mmap() call itself fully POSIX-compatible, but it seems that this behavior is not necessarily more portable than MAP_ANONYMOUS (apparently does not work on Mac OS X/macOS).
  3. Allocate memory using aligned_alloc() (or posix_memalign()) and use mprotect().
    Problem: The behavior of mprotect() according to POSIX is only specified for memory obtained via mmap(), although at least “on Linux, it is always permissible to call mprotect() on any address in a process’s address space (except for the kernel vsyscall area)”.

So from the standards point of view, the problem is that mprotect() is only specified in combination with mmap(), but there is no standard that actually specifies dynamic memory allocation with mmap(). It seems that option (1.) is the most portable. Is there another approach that works on more systems (or, even better, is actually specified by a standard)?

1

There are 1 answers

6
Erdal Küçük On

How about shared memory object via shm_open? shm_open returns a file descriptor which can be mapped by mmap and therefore mprotect(ed).