summaryrefslogtreecommitdiff
path: root/tool/mbed/mbed-sdk/libraries/tests/mbed/heap_and_stack/main.cpp
blob: a127efedb44136b9a1f5421e6d3e341a6f8d354f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "test_env.h"

static char *initial_stack_p;
static char *initial_heap_p;

static char line[256];
static unsigned int iterations = 0;

void report_iterations(void) {
    unsigned int tot = (0x100 * iterations)*2;
    printf("\nAllocated (%d)Kb in (%u) iterations\n", tot/1024, iterations);
#if !defined(TOOLCHAIN_GCC_CR)
    // EA: This causes a crash when compiling with GCC_CR???
    printf("%.2f\n", ((float)(tot)/(float)(initial_stack_p - initial_heap_p))*100.);
#endif
#ifdef TOOLCHAIN_ARM
#ifndef __MICROLIB
    __heapvalid((__heapprt) fprintf, stdout, 1);
#endif
#endif
}

void stack_test(char *latest_heap_pointer) {
    char stack_line[256];
    iterations++;

    sprintf(stack_line, "\nstack pointer: %p", &stack_line[255]);
    puts(stack_line);

    char *heap_pointer = (char*)malloc(0x100);

    if (heap_pointer == NULL) {
        int diff = (&stack_line[255] - latest_heap_pointer);
        if (diff > 0x200) {
            sprintf(stack_line, "\n[WARNING] Malloc failed to allocate memory too soon. There are (0x%x) free bytes", diff);
            report_iterations();
            puts(stack_line);
        } else {
            puts("\n[SUCCESS] Stack/Heap collision detected");
            report_iterations();
        }
        return;
    } else {
        heap_pointer += 0x100;
        sprintf(line, "heap pointer: %p", heap_pointer);
        puts(line);
    }

    if ((&stack_line[255]) > heap_pointer) {
        stack_test(heap_pointer);
    } else {
        puts("\n[WARNING] The Stack/Heap collision was not detected");
        report_iterations();
    }
}


int main (void) {
    char c;
    initial_stack_p = &c;

    initial_heap_p = (char*)malloc(1);
    if (initial_heap_p == NULL) {
        printf("Unable to malloc a single byte\n");
        notify_completion(false);
    }

    printf("Initial stack/heap geometry:\n");
    printf("   stack pointer:V %p\n", initial_stack_p);
    printf("   heap pointer :^ %p\n", initial_heap_p);

    initial_heap_p++;
    stack_test(initial_heap_p);

    notify_completion(true);
}