CM3 MPU port potential stack-overflow and fix
Posted by Robert Turner
on 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.
RE: CM3 MPU port potential stack-overflow and fix
Posted by Richard
on August 11, 2012
Yes please do post the code in the FreeRTOS Interactive site (http://interactive.freertos.org).
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.
Copyright (C) 2004-2010 Richard Barry. Copyright (C) 2010-2016 Real Time Engineers Ltd.
Any and all data, files, source code, html content and documentation included in the FreeRTOSTM distribution or available on this site are the exclusive property of Real Time Engineers Ltd..
See the files license.txt (included in the distribution) and this copyright notice for more information. FreeRTOSTM and FreeRTOS.orgTM are trade marks of Real Time Engineers Ltd.