32b6cce23ba526e32d6f5e08427dc0854af96b27
[libc-test] / src / common / vmfill.c
1 #include <stdint.h>
2 #include <sys/mman.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <limits.h>
6 #include "test.h"
7 #ifndef PAGE_SIZE
8         #define PAGE_SIZE sysconf(_SC_PAGE_SIZE)
9 #endif
10
11 /* max mmap size, *start is the largest power-of-2 size considered */
12 static size_t mmax(int fd, size_t *start)
13 {
14         size_t i, n;
15         void *p;
16
17         for (i=n=*start; i>=PAGE_SIZE; i/=2) {
18                 if ((p=mmap(0, n, PROT_NONE, MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
19                         n -= i/2;
20                 } else {
21                         munmap(p, n);
22                         if (n == i)
23                                 *start = n;
24                         n += i/2;
25                 }
26         }
27         return n & -PAGE_SIZE;
28 }
29
30 /*
31 fills the virtual memory with anonymous PROT_NONE mmaps,
32 returns the mappings in *p and *n in decreasing size order,
33 the return value is the number of mappings or -1 on failure.
34 */
35 int t_vmfill(void **p, size_t *n, int len)
36 {
37         int fd = open("/dev/zero", O_RDWR);
38         size_t start = SIZE_MAX/2 + 1;
39         size_t m;
40         void *q;
41         int i;
42
43         for (i=0;;i++) {
44                 m = mmax(fd, &start);
45                 if (!m)
46                         break;
47                 q = mmap(0, m, PROT_NONE, MAP_PRIVATE, fd, 0);
48                 if (q == MAP_FAILED)
49                         return -1;
50                 if (i < len) {
51                         p[i] = q;
52                         n[i] = m;
53                 }
54         }
55         return i;
56 }