简体   繁体   English

在分配的 memory 上使用 mprotect() 的最便携方式

[英]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() .我想知道是否有一种可移植的方式来动态分配 memory,然后限制对该 memory 的一部分的读/写访问,例如使用 POSIX 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() .使用mmap()分配 memory ,即mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) :这里,memory 保护标志可以在稍后在初始分配调用中给出,并且可以选择修改使用mprotect()
    Problem: MAP_ANONYMOUS is not specified by POSIX , although it's supposedly supported by “almost all” or “most” systems .问题: POSIX 没有指定MAP_ANONYMOUS ,尽管它应该被“几乎所有”“大多数”系统支持。
  2. Apparently, using mmap() on /dev/zero is an alternative to MAP_ANONYMOUS .显然, /dev/zero上使用mmap()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).这将使mmap()调用自身完全与 POSIX 兼容,但似乎这种行为不一定比MAP_ANONYMOUS更便携(显然不适用于 Mac OS X/macOS)。
  3. Allocate memory using aligned_alloc() (or posix_memalign() ) and use mprotect() .使用aligned_alloc() (或posix_memalign() )分配 memory 并使用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)” .问题: 根据 POSIX, mprotect()的行为仅针对通过mmap()获得的 memory 指定,尽管至少“在 Linux 上,始终允许在进程地址空间中的任何地址上调用mprotect() (除了kernel vsyscall 区域)”

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() .所以从标准的角度来看,问题在于mprotect()仅与mmap()结合指定,但没有标准实际指定动态 memory 分配与mmap() It seems that option (1.) is the most portable.似乎选项(1.)是最便携的。 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共享 memory object 怎么样? shm_open returns a file descriptor which can be mapped by mmap and therefore mprotect (ed). shm_open返回一个文件描述符,它可以被mmap映射,因此可以被mprotect (ed) 映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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