mincore - determine whether pages are resident in memory

Code snippet copied from https://github.com/llvm-mirror/compiler-rt/blob/21a2aeb64cb27fae0f6e95f7d05a82ba67d70cd3/test/asan/TestCases/Linux/mincore.cc

First, we ask for 20 pages; since, by default, lazy mapping is used, none of them are mapped into physical memory. A page will be backed by physical memory on the first write into that page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// RUN: %clangxx_asan -std=c++11 -O0 %s -o %t && %run %t

#include <assert.h>
#include <unistd.h>
#include <sys/mman.h>

int main(void) {
unsigned char vec[20];
int res;
size_t PS = sysconf(_SC_PAGESIZE);
void *addr = mmap(nullptr, 20 * PS, PROT_READ | PROT_WRITE,
MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);

res = mincore(addr, 10 * PS, vec);
assert(res == 0);
for (int i = 0; i < 10; ++i)
assert((vec[i] & 1) == 0);

for (int i = 0; i < 5; ++i)
((char *)addr)[i * PS] = 1;
res = mincore(addr, 10 * PS, vec);
assert(res == 0);
for (int i = 0; i < 10; ++i)
assert((vec[i] & 1) == (i < 5));

for (int i = 5; i < 10; ++i)
((char *)addr)[i * PS] = 1;
res = mincore(addr, 10 * PS, vec);
assert(res == 0);
for (int i = 0; i < 10; ++i)
assert((vec[i] & 1) == 1);

return 0;
}