]> git.gir.st - tmk_keyboard.git/blob - tool/mbed/mbed-sdk/libraries/tests/mbed/heap_and_stack/main.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[tmk_keyboard.git] / tool / mbed / mbed-sdk / libraries / tests / mbed / heap_and_stack / main.cpp
1 #include "test_env.h"
2
3 static char *initial_stack_p;
4 static char *initial_heap_p;
5
6 static char line[256];
7 static unsigned int iterations = 0;
8
9 void report_iterations(void) {
10 unsigned int tot = (0x100 * iterations)*2;
11 printf("\nAllocated (%d)Kb in (%u) iterations\n", tot/1024, iterations);
12 #if !defined(TOOLCHAIN_GCC_CR)
13 // EA: This causes a crash when compiling with GCC_CR???
14 printf("%.2f\n", ((float)(tot)/(float)(initial_stack_p - initial_heap_p))*100.);
15 #endif
16 #ifdef TOOLCHAIN_ARM
17 #ifndef __MICROLIB
18 __heapvalid((__heapprt) fprintf, stdout, 1);
19 #endif
20 #endif
21 }
22
23 void stack_test(char *latest_heap_pointer) {
24 char stack_line[256];
25 iterations++;
26
27 sprintf(stack_line, "\nstack pointer: %p", &stack_line[255]);
28 puts(stack_line);
29
30 char *heap_pointer = (char*)malloc(0x100);
31
32 if (heap_pointer == NULL) {
33 int diff = (&stack_line[255] - latest_heap_pointer);
34 if (diff > 0x200) {
35 sprintf(stack_line, "\n[WARNING] Malloc failed to allocate memory too soon. There are (0x%x) free bytes", diff);
36 report_iterations();
37 puts(stack_line);
38 } else {
39 puts("\n[SUCCESS] Stack/Heap collision detected");
40 report_iterations();
41 }
42 return;
43 } else {
44 heap_pointer += 0x100;
45 sprintf(line, "heap pointer: %p", heap_pointer);
46 puts(line);
47 }
48
49 if ((&stack_line[255]) > heap_pointer) {
50 stack_test(heap_pointer);
51 } else {
52 puts("\n[WARNING] The Stack/Heap collision was not detected");
53 report_iterations();
54 }
55 }
56
57
58 int main (void) {
59 char c;
60 initial_stack_p = &c;
61
62 initial_heap_p = (char*)malloc(1);
63 if (initial_heap_p == NULL) {
64 printf("Unable to malloc a single byte\n");
65 notify_completion(false);
66 }
67
68 printf("Initial stack/heap geometry:\n");
69 printf(" stack pointer:V %p\n", initial_stack_p);
70 printf(" heap pointer :^ %p\n", initial_heap_p);
71
72 initial_heap_p++;
73 stack_test(initial_heap_p);
74
75 notify_completion(true);
76 }
Imprint / Impressum