如何查找内存位置是否可用于 mmaping?

How can I find if a memory location is free for mmaping?

我真的想使用 mmapMAP_FIXED 选项保留一组特定的内存位置。但是,默认情况下 mmapmunmap 那些地址中已有的任何内容,这将是灾难性的。

如何告诉 mmap 到 "reserve the memory at this address, but fail if it is already in use"?

您可以尝试使用 mincore(2)

不幸的是,这将是非线程安全的。另一个线程可能会在您检查区域状态之后但在您执行 mmap.

之前分配该区域

如果需要预留内存区域,只需用PROT_NONE创建匿名私有映射即可。稍后您可以使用 MAP_FIXED.

在其上放置不同的映射

编辑:看起来 mincore 行为将 change in Linux 5.0 due to the fact that it can cause information leak (CVE-2019-5489):

So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use).

漏洞描述可见here.

只需省略 MAP_FIXED 然后 Linux 将在空闲时使用请求的地址。如果请求的地址不可用,则使用其他地址,在这种情况下,您可以使用 munmap.