Search code examples
cgcccpu-registerscortex-mbare-metal

GCC ARM: get actual value from SP register


How to get actual value from SP register?

I Want to fill up whole SRAM with some initial values, but I didn't want to overwrite actual content of stack.

My startup code (which also overwrite actual content of stack):

void RESET_handler() {
    unsigned *src, *dst;
    // initialize memory
    // .....

    // fill SRAM
    dst = &_bss_end;
    while (dst < &_stacktop) {
        *dst++ = 0x55555555;
    }
}

_bss_end is end of used memory for static variables and _stacktop is pointing to end of SRAM memory or also top of stack.

Although this function is reset handler gcc make it safe and on begin push some registers into stack (more info). Yes at this point actual content of stack is irrelevant and overwriting it is safe but for clearance I would like to stop filling before stack by replacing &_stacktop with actual value of SP.

Any other ideas are also welcome except suggestion to rewrite startup code into assembler.


Solution

  • It can be done reliably only by the startup file modiffication.

    I will only focus on single stack (for thread * privileged) example for openSTM32 type startup:

    /* Call the clock system intitialization function.*/
        bl  SystemInit
    /* Call static constructors */
    
        bl  fillStack  // <------------ add this
    
        bl __libc_init_array
    /* Call the application's entry point.*/
        bl  main
    

    Then in any of your C files implement the fillStack function. use CMSIS intrinsic instructions like __get_MSP()