CM3 MPU port potential stack-overflow and fix

rwt33 wrote on Saturday, August 11, 2012:

The Cortex M3 MPU port does a brilliant job of protecting various memory regions, however, it is still possible for a non-privileged task to overflow its stack. This can happen if the stack is already close to being full and then the task is context-switched out, specifically the stacking of the CONTROL and r4 to r11 registers in the xPortPendSVHandler context switcher. When a handler is called, if there isn’t enough room to store the standard Cortex-M context (r0-4, r12, lr, pc, xPSR) the TRM specifies that an MPU fault will occur (stack error), however, the PendSVHandler executes in handler (priv) mode and can easily overflow the user stack (psp).
I have implemented a way of storing these 9 registers in a separate tcb-space (I put them in the xMPU_SETTINGS) so that all stack overflows for non-priv tasks are caught by the MPU. It does, however, require quite a few port modifications, including setting up of the the task stack, unstacking the first task, and context switching.
I could post code if people are interested. There is one point that had to be implemented as a hack which is related to if a task starts executing as privileged or not.

Robert Turner

rtel wrote on Saturday, August 11, 2012:

Yes please do post the code in the FreeRTOS Interactive site (

I think setting configCHECK_FOR_STACK_OVERFLOW to 1 should catch the situation you refer to, albeit in software rather than by generating a memory fault.