xref: /haiku/src/tests/system/kernel/mmap_resize_test.cpp (revision 21258e2674226d6aa732321b6f8494841895af5f)
1 /*
2  * Copyright 2010, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/mman.h>
13 #include <unistd.h>
14 
15 
16 int
17 main()
18 {
19 	const char* fileName = "/tmp/mmap-resize-test-file";
20 
21 	// create file
22 	printf("creating file...\n");
23 	int fd = open(fileName, O_CREAT | O_RDWR | O_TRUNC, 0644);
24 	if (fd < 0) {
25 		fprintf(stderr, "Failed to open \"%s\": %s\n", fileName,
26 			strerror(errno));
27 		exit(1);
28 	}
29 
30 	// write half a page
31 	printf("writing data to file...\n");
32 	char buffer[2048];
33 	memset(buffer, 0xdd, sizeof(buffer));
34 	if (write(fd, buffer, sizeof(buffer)) != (ssize_t)sizeof(buffer)) {
35 		fprintf(stderr, "Failed to write to file!\n");
36 		exit(1);
37 	}
38 
39 	// map the page
40 	printf("mapping file...\n");
41 	void* address = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
42 	if (address == MAP_FAILED) {
43 		fprintf(stderr, "Failed to map the file: %s\n", strerror(errno));
44 		exit(1);
45 	}
46 
47 	// truncate the file
48 	printf("truncating file...\n");
49 	if (ftruncate(fd, 0) < 0) {
50 		fprintf(stderr, "Failed to truncate the file: %s\n", strerror(errno));
51 		exit(1);
52 	}
53 
54 	// touch data
55 	printf("touching no longer mapped data (should fail with SIGBUS)...\n");
56 	*(int*)address = 42;
57 
58 	printf("Shouldn't get here!!!\n");
59 
60 	return 0;
61 }
62