1 #define _GNU_SOURCE
2 #include "tests/sys_mman.h"
3 #include <stdio.h>
4 #include <stdlib.h>
5 
mkmap(unsigned sz)6 static char *mkmap(unsigned sz)
7 {
8 	static char *map;
9 	static unsigned mapsz;
10 	char *p;
11 
12 	if (map != NULL)
13 		munmap(map, mapsz);
14 
15 	p = (char *)mmap(0, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
16 
17 	if (p == (char *)-1) {
18 		perror("mmap");
19 		exit(1);
20 	}
21 
22 	map = p;
23 	mapsz = sz;
24 
25 	return p;
26 }
27 
28 
main()29 int main()
30 {
31 	char *np;
32 	char *p;
33 
34 	p = mkmap(1024*1024);
35 	np = mremap(p, 1024*1024, 256*1024, 0);	/* shrink, fixed */
36 	if (np == (char *)-1)
37 		perror("mremap(shrink, fixed)");
38 	if (np != p)
39 		fprintf(stderr, "shrink, nomove: p=%p np=%p: shrink moved?!\n",
40 			p, np);
41 	if (np != (char *)-1)
42 		munmap(np, 256*1024);
43 
44 	p = mkmap(1024*1024);
45 	np = mremap(p, 1024*1024, 256*1024, MREMAP_MAYMOVE);	/* shrink, maymove */
46 	if (np == (char *)-1)
47 		perror("mremap(shrink, maymove)");
48 	if (np != p)
49 		fprintf(stderr, "shrink, maymove: p=%p np=%p: shrink moved?!\n",
50 			p, np);
51 	if (np != (char *)-1)
52 		munmap(np, 256*1024);
53 
54 	p = mkmap(1024*1024);
55 	np = mremap(p, 1024*1024, 2048*1024, 0); /* grow, fixed */
56 	if (np == (char *)-1)
57 		perror("mremap(grow, fixed)");
58 	if (np != p)
59 		fprintf(stderr, "grow, nomove: p=%p np=%p: shrink moved?!\n",
60 			p, np);
61 	if (np != (char *)-1)
62 		munmap(np, 2048*1024);
63 
64 	p = mkmap(1024*1024);
65 	np = mremap(p, 1024*1024, 2048*1024, MREMAP_MAYMOVE); /* grow, maymove */
66 	if (np == (char *)-1)
67 		perror("mremap(grow, maymove)");
68 	if (np != p)
69 		fprintf(stderr, "grow, maymove: p=%p np=%p: shrink moved?!\n",
70 			p, np);
71 	if (np != (char *)-1)
72 		munmap(np, 2048*1024);
73 
74 	p = mkmap(1024*1024);
75 	munmap(p+512*1024, 4096);
76 	np = mremap(p, 512*1024, 1024*1024, 0); /* grow, nomove, constrained */
77 	if (np == (char *)-1)
78 		perror("mremap(grow, nomove, constrained)");
79 	else if (np == p)
80 		fprintf(stderr, "grow, maymove, constrained: p=%p np=%p (managed to grow without moving?!)\n",
81 			p, np);
82 	if (np != (char *)-1)
83 		munmap(np, 1024*1024);
84 
85 	p = mkmap(1024*1024);
86 	munmap(p+512*1024, 4096);
87 
88 	np = mremap(p, 512*1024, 1024*1024, MREMAP_MAYMOVE); /* grow, maymove, constrained */
89 	if (np == (char *)-1)
90 		perror("mremap(grow, maymove, constrained)");
91 	if (np == p)
92 		fprintf(stderr, "grow, maymove, constrained: p=%p np=%p (managed to grow without moving?!)\n",
93 			p, np);
94 	if (np != (char *)-1)
95 		munmap(np, 1024*1024);
96 
97 	return 0;
98 }
99