Keeping an eye on stack space

vApplicationStackOverflowHook provides a very simple way of eliminating most of the oddball behavior and halting the application. When enabling configCHECK_FOR_STACK_OVERFLOW #define in FreeRTOSConfig.h, any time a stack overflow is detected by FreeRTOS, vApplicationStackOverflowHook will be called.

There are two potential values for configCHECK_FOR_STACK_OVERFLOW:

  • #define configCHECK_FOR_STACK_OVERFLOW 1: Checks the stack pointer location upon task exit.
  • #define configCHECK_FOR_STACK_OVERFLOW 2: Fills the stack with a known pattern and checks for the pattern upon exit.

The first method checks the task stack pointer as the task exits the running state. If the stack pointer is pointing to an invalid location (where the stack shouldn't be), then an overflow has occurred:

This method is very fast, but it has the potential to miss some stack overflows—for example, if the stack has grown beyond its originally allocated space, but the stack pointer happens to be pointing to a valid spot when checked, then the overflow will be missed. To combat this, a second method is also available.

When setting configCHECK_FOR_STACK_OVERFLOW to 2, method 1 will be used, but a second method will also be employed. Instead of simply checking where the stack pointer is located after the task has exited the running state, the top 16 bytes of the stack can be watermarked and analyzed upon exit. This way, if at any point during the task run the stack has overflowed and the data in the top 16 bytes has been modified, an overflow will be detected:

This method helps to ensure that, even if a stack overflow has occurred (or nearly occurred) at any point during the task execution, it will be detected, as long as the overflow passed through the upper 16 words of the stack.

While these methods are good for catching stack overflows, they are not perfect—for example, if an array is declared on a task stack and extends past the end of the stack with only the end of the array being modified, then a stack overflow won't be detected.

So, to implement a very simple hook that will stop execution when a stack overflow occurs, we'll take the following simple steps:

  1. In FreeRTOSConfig.h, define the configuration flag:
#define configCHECK_FOR_STACK_OVERFLOW 2
  1. In a *.c file, add the stack overflow hook:
void vApplicationStackOverflowHook( void )
{
__disable_irq();
while(1);
}

This very simple method disables all interrupts and executes an infinite loop, leaving no question that something has gone wrong. At this point, a debugger can be used to analyze which stack has overflowed.

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

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