2.2.8 Stack Underflow and Overflow Resets
Inside a PIC microcontroller, there is a hardware stack that holds the return addresses needed when invoking a function. One way to visualize this concept is to imagine a paper basket with pieces of paper inside that have a task written on them. After waking up and getting ready, the basket is empty, and the user performs an ordinary task. If there’s a phone call in the middle of the task, a sheet of paper is added on top to take the call. When the call is complete, that sheet of paper is removed.
A stack underflow is a condition where the user attempts to remove a sheet of paper when there is none in the basket. In the microcontroller, undefined behavior may occur in the CPU, as the address to jump to is not valid.
A stack overflow is an opposite condition - for instance if the user has so many tasks in progress that the stack of paper falls over. The CPU in the microcontroller may also exhibit undefined behavior in this case.
In contrast to PIC microcontrollers, AVR microcontrollers use a software-based stack that exists in SRAM. This makes the stack flexible in length, which makes it difficult to trigger a stack overflow event. However, if the stack pointer is shifted, then the CPU will execute software at invalid or uninitialized locations. Usually, the CPU will end up back in the main by reaching the initialization vector.
/* If the reset register is zero, * then there is a stack overflow or an unhandled interrupt * (something is calling main()) */ if (RSTCTRL.RSTFR == 0) { // If in debug mode; break the CPU asm volatile ("break"); // Production code: Blink a LED for a few moments before resetting uint16_t timeout = 0xffff; while (--timeout) { LED0_tgl(); _delay_ms(100); } reset_system(); // Development code: keep the system in an infinite loop // To allow for the debugger to examine SRAM and other registers. while (1) { LED0_tgl(); } } RSTCTRL.RSTFR = 0xff;Stack Overflow (or Unhandled Interrupt) Detector for AVR microcontrollers
One of the most common sources of stack overflow faults on AVR is recursive functions calls, where function A calls function B, which calls function A, etc. If this chain of function calls is long enough, the program will overflow the stack.