简体   繁体   中英

Most portable way to use mprotect() on allocated memory

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, eg using the POSIX function mprotect() . I can think of the following approaches:

  1. Allocate memory using mmap() , ie 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)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM