xref: /haiku/src/tests/system/kernel/mmap_fixed_test.cpp (revision 7be371792f03735519174b773450546e6bf5376e)
1*7be37179STrung Nguyen /*
2*7be37179STrung Nguyen  * Copyright 2023, Trung Nguyen, trungnt282910@gmail.com.
3*7be37179STrung Nguyen  * Distributed under the terms of the MIT License.
4*7be37179STrung Nguyen  */
5*7be37179STrung Nguyen 
6*7be37179STrung Nguyen #include <fcntl.h>
7*7be37179STrung Nguyen #include <stdlib.h>
8*7be37179STrung Nguyen #include <stdio.h>
9*7be37179STrung Nguyen #include <sys/mman.h>
10*7be37179STrung Nguyen #include <unistd.h>
11*7be37179STrung Nguyen 
12*7be37179STrung Nguyen int
main()13*7be37179STrung Nguyen main()
14*7be37179STrung Nguyen {
15*7be37179STrung Nguyen 	char tmpfile[] = "/tmp/mmap_fixed_test_XXXXXX";
16*7be37179STrung Nguyen 	int fd = mkstemp(tmpfile);
17*7be37179STrung Nguyen 
18*7be37179STrung Nguyen 	if (fd < 0) {
19*7be37179STrung Nguyen 		printf("cannot create temporary file.\n");
20*7be37179STrung Nguyen 		return -1;
21*7be37179STrung Nguyen 	}
22*7be37179STrung Nguyen 
23*7be37179STrung Nguyen 	unlink(tmpfile);
24*7be37179STrung Nguyen 	ftruncate(fd, 4096);
25*7be37179STrung Nguyen 
26*7be37179STrung Nguyen 	// Should not crash the kernel (#18422)
27*7be37179STrung Nguyen 	void* addr = mmap(NULL, 4096, PROT_NONE, MAP_SHARED, fd, 0);
28*7be37179STrung Nguyen 	void* addr1 = mmap(addr, 4096, PROT_NONE, MAP_SHARED | MAP_FIXED, fd, 0);
29*7be37179STrung Nguyen 
30*7be37179STrung Nguyen 	if (addr == MAP_FAILED || addr1 == MAP_FAILED) {
31*7be37179STrung Nguyen 		printf("mmap failed.\n");
32*7be37179STrung Nguyen 		return -1;
33*7be37179STrung Nguyen 	}
34*7be37179STrung Nguyen 
35*7be37179STrung Nguyen 	if (addr != addr1) {
36*7be37179STrung Nguyen 		printf("MAP_FIXED did not return same address.\n");
37*7be37179STrung Nguyen 		return -1;
38*7be37179STrung Nguyen 	}
39*7be37179STrung Nguyen 
40*7be37179STrung Nguyen 	return 0;
41*7be37179STrung Nguyen }
42