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