xref: /haiku/src/tests/system/kernel/reserved_areas_test.cpp (revision 4124f4801ba281731fe2aa841835d31c9d886e52)
1 /*
2  * Copyright 2009, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 //!	Test application that reproduces bug #4778.
8 
9 
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 
14 #include <OS.h>
15 
16 #include <syscalls.h>
17 
18 
19 status_t
memory_eater(void *)20 memory_eater(void*)
21 {
22 	size_t total = 0;
23 
24 	while (true) {
25 		size_t size = rand() % 16384 + 8;
26 		if (malloc(size) == NULL) {
27 			printf("out of memory after having allocated %ld bytes\n", total);
28 			break;
29 		} else
30 			total += size;
31 
32 		putchar('.');
33 	}
34 
35 	return B_OK;
36 }
37 
38 
39 status_t
area_creator(void *)40 area_creator(void*)
41 {
42 	while (true) {
43 		status_t status = B_ERROR;
44 		uint32 addressSpec = B_ANY_ADDRESS;
45 		void* base;
46 		bool readOnly = false;//(rand() % 256) > 127;
47 		if (!readOnly) {
48 			// reserve 128 MB of space for the area
49 			base = (void*)0x60000000;
50 			status = _kern_reserve_address_range((addr_t*)&base, B_BASE_ADDRESS,
51 				128 * 1024 * 1024);
52 			addressSpec = status == B_OK ? B_EXACT_ADDRESS : B_BASE_ADDRESS;
53 			printf("\naddress spec = %lx, base %p (status %s)\n", addressSpec,
54 				base, strerror(status));
55 		}
56 
57 		area_id area = create_area(readOnly ? "read-only memory" : "r/w memory",
58 			&base, addressSpec, B_PAGE_SIZE * 4, B_NO_LOCK,
59 			B_READ_AREA | (readOnly ? 0 : B_WRITE_AREA));
60 		if (area >= 0) {
61 			printf("new %s area %ld at %p\n", readOnly ? "read-only" : "r/w",
62 				area, base);
63 		} else
64 			break;
65 
66 		snooze(10000);
67 	}
68 
69 	return B_OK;
70 }
71 
72 
73 int
main(int argc,char ** argv)74 main(int argc, char** argv)
75 {
76 	thread_id eater = spawn_thread(&memory_eater, "memory eater",
77 		B_NORMAL_PRIORITY, NULL);
78 	resume_thread(eater);
79 
80 	thread_id creator = spawn_thread(&area_creator, "area creator",
81 		B_NORMAL_PRIORITY, NULL);
82 	resume_thread(creator);
83 
84 	object_wait_info waitInfos[2] = {
85 		{ eater, B_OBJECT_TYPE_THREAD, 0 },
86 		{ creator, B_OBJECT_TYPE_THREAD, 0 }
87 	};
88 	ssize_t which = wait_for_objects(waitInfos, 2);
89 	printf("wait for objects: %ld\n", which);
90 
91 	debugger("Welcome to the land of tomorrow");
92 	return 0;
93 }
94