March 24, 2013

Stack usage for ARM Cortex-M

I'll present how I used one of the methods to measure stack usage, not using any plugin, just debugger and memory window.

Methods to use:
1. IDE plugins (usually compiler and linker do the job)
2. Fill pattern (add small assembly routine in startup)
3. Take an address of the stack pointer in the main function, and in the most nested function (for a simple application usable)

IAR stack plugin []
This document is targeted to IAR stack plugin. Although this did not work for the MCU I debugged.

Stack and Heap []
What's stack, heap, methods explained briefly how to calculate stack usage in IAR. Methods applicable for other IDE's as well, not limited to IAR only.

Stack use in C and C++ []
How to obtain stack usage in KEIL using callgraph (option --callgraph).
Here's callgraph output which I found on the internet, not needed to share mine:
Keil callgraph - an example []

Using indirect calls (function pointers) make this method unreliable, same for IAR stack plugin, where it can be added #pragma calls, but what if an application using another library, that's too much changes to do, more simple approach is in a following paragraph presented, a filling memory for a stack with a pattern and show how low it gets.

KEIL stack initialize routine []
Stack initialization routine, which I only accustomed to Thumb-2. Here's the code used on Cortex-M0. Label __user_initial_stackheap is located in assembly file for your board. Just run your application for a while and check the memory window to obtain the lowest address of the last character of your pattern (in our case it's AA (char values)). Calculate the subtraction which gives your application stack usage.

    LDR     R0, =Stack_Mem
    LDR     R1, =Stack_Size           
    LDR     R2, =0xAAAAAAAA
    STR     R2, [R0]
    ADDS    R0,#4
    SUBS    R1,#4                     
    BNE     fill

This also can be added in assembly file which is used in IAR or any other IDE, just replace Stack_Mem symbol (beginning of the stack) and Stack_Size (size of the stack).