diff --git a/cpu/msp430_common/msp430-main.c b/cpu/msp430_common/msp430-main.c index aa171b68db..7b5b25e61d 100644 --- a/cpu/msp430_common/msp430-main.c +++ b/cpu/msp430_common/msp430-main.c @@ -126,6 +126,8 @@ void msp430_cpu_init(void) #define STACK_EXTRA 32 +extern char __stack; /* provided by linker script */ +char *__heap_end = NULL; /* top of heap */ /* * Allocate memory from the heap. Check that we don't collide with the @@ -135,12 +137,15 @@ void msp430_cpu_init(void) */ void *sbrk(int incr) { - char *stack_pointer; + char *__heap_top = __heap_end; - asmv("mov r1, %0" : "=r"(stack_pointer)); - stack_pointer -= STACK_EXTRA; + if (!__heap_top) { + /* set __heap_top to stack pointer if we are not in thread mode */ + asmv("mov r1, %0" : "=r"(__heap_top)); + __heap_top -= STACK_EXTRA; + } - if (incr > (stack_pointer - cur_break)) { + if (incr > (__heap_top - cur_break)) { return (void *) - 1; /* ENOMEM */ } diff --git a/cpu/msp430_common/startup.c b/cpu/msp430_common/startup.c index 5a6365ac0e..8baeafbeb3 100644 --- a/cpu/msp430_common/startup.c +++ b/cpu/msp430_common/startup.c @@ -26,6 +26,13 @@ extern void board_init(void); +/** + * Leave some extra space in the stack to allows us to finish the kernel + * initialization procedure. __heap_end is set the current stack, minus + * STACK_EXTRA since there is still code to execute. + */ +#define STACK_EXTRA 32 + __attribute__((constructor)) static void startup(void) { /* use putchar so the linker links it in: */ @@ -35,5 +42,10 @@ __attribute__((constructor)) static void startup(void) LOG_INFO("RIOT MSP430 hardware initialization complete.\n"); + /* save current stack pointer as top of heap before enter the thread mode */ + extern char *__heap_end; + __asm__ __volatile__("mov r1, %0" : "=r"(__heap_end)); + __heap_end -= STACK_EXTRA; + kernel_init(); }