update makefile
[musl-tools.git] / vmfill.c
bloba7f0a15290ab0474a5227025652c80da8e7e95cc
1 #include <stdlib.h>
2 #include <stdint.h>
3 #include <stdio.h>
4 #include <sys/mman.h>
5 #include <fcntl.h>
6 #include <unistd.h>
8 #ifndef PAGE_SIZE
9 #define PAGE_SIZE sysconf(_SC_PAGE_SIZE)
10 #endif
12 static void printvm() {
13 int fd = open("/proc/self/smaps", O_RDONLY);
14 char buf[4096];
15 int n;
17 printf("/proc/self/smaps:\n");
18 fflush(stdout);
19 while ((n = read(fd, buf, sizeof buf)) > 0)
20 write(1, buf, n);
21 close(fd);
24 static size_t mmapmax(int fd, void **p) {
25 size_t i,j,n=0;
27 for (i=j=SIZE_MAX/2+1; i>=PAGE_SIZE; i/=2) {
28 if ((*p=mmap(NULL, j, PROT_NONE, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
29 j -= i/2;
30 else {
31 n = j;
32 munmap(*p, n);
33 j += i/2;
36 if (n && (*p=mmap(NULL, n, PROT_NONE, MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
37 fprintf(stderr, "failed to mmap the same amount again.\n");
38 exit(1);
40 return n;
43 int main(int argc, char *argv[]) {
44 const int fd = open("/dev/zero", O_RDWR);
45 void *p[100];
46 size_t n[100];
47 size_t sum = 0;
48 int i;
49 int vmmaps = 0;
51 if (argc == 2 && argv[1][0]=='-' && argv[1][1]=='v')
52 vmmaps = 1;
54 for (i=0; i<sizeof p/sizeof *p; i++) {
55 n[i] = mmapmax(fd, p+i);
56 if (!n[i])
57 break;
58 sum += n[i];
59 printf("%d %16zu B %012zx-%012zx\n", i, n[i], (size_t)p[i], (size_t)p[i]+n[i]);
61 printf("mmaped %zu B in %d blocks.\n", sum, i);
63 printf("try malloc:");
64 for(i=0; i < 1000 && malloc(PAGE_SIZE) != NULL; i++)
65 printf(".");
66 printf(" %zu B\n", i*(size_t)PAGE_SIZE);
68 if (vmmaps)
69 printvm();
70 return 0;