Stack painting

An effective way to measure the amount of stack space needed consists of filling the estimated stack space with a well-known pattern. This mechanism, informally referred to as stack painting, reveals the maximum expansion of the execution stack at any time. By running the software with a painted stack, it is in fact possible to measure the amount of stack used by looking for the last recognizable pattern, and assuming that the stack pointer has moved during the execution at most until that point.

We can perform stack painting manually in the reset handler, during memory initialization. To do so, we need to assign an area to paint. In this case it would be the last 8 KB of memory up until _end_stack. Once again, while manipulating the stack in the reset_handler function, local variables should not be used. The reset_handler function will store the value of the current stack pointer into the global variable sp:

static unsigned int sp;

Within the handler, the following section can be added before invoking main():

asm volatile("mrs %0, msp" : "=r"(sp));
dst = ((unsigned int *)(&_end_stack)) - (8192 / sizeof(unsigned int)); ;
while (dst < sp) {
*dst = 0xDEADC0DE;
dst++;
}

The first assembly instruction is used to store the current value of the stack pointer to the variable sp, to ensure that the painting stops after painting the area, but only up until the last unused address in the stack:

Painting the stack area with a recognizable pattern helps estimating the stack memory used in the prototype

The current stack usage can be checked periodically at runtime, for instance in the main loop, to detect the area painted with the recognizable pattern. The areas that are still painted have never been used by the execution stack so far, and indicate the amount of stack still available.

This mechanism may be used to verify the amount of stack space required by the application to run comfortably. According to the design, this information can be used later on to set a safe lower limit on the segment that can be used for the stack.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset