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