# CM3 MPU port potential stack-overflow and fix

**URL:** <https://forums.freertos.org/t/cm3-mpu-port-potential-stack-overflow-and-fix/819>\
**Category:** Kernel\
**Created:** [August 11, 2012, 5:49am UTC](https://forums.freertos.org/t/cm3-mpu-port-potential-stack-overflow-and-fix/819 "2012-08-11T05:49:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [August 11, 2012, 5:49am UTC](https://forums.freertos.org/t/cm3-mpu-port-potential-stack-overflow-and-fix/819/1 "2012-08-11T05:49:05Z")

</div>

**[rwt33](https://sourceforge.net/u/rwt33/)** wrote on [Saturday, August 11, 2012](https://sourceforge.net/p/freertos/discussion/382005/thread/25ea6909/#365e):

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

---

<div class="post-metadata">

**Author:** ![rtel](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/rtel/32/31_2.png) [@rtel](https://forums.freertos.org/u/rtel)\
**Post date:** [August 11, 2012, 1:03pm UTC](https://forums.freertos.org/t/cm3-mpu-port-potential-stack-overflow-and-fix/819/2 "2012-08-11T13:03:07Z")

</div>

**[rtel](https://sourceforge.net/u/rtel/)** wrote on [Saturday, August 11, 2012](https://sourceforge.net/p/freertos/discussion/382005/thread/25ea6909/#4908):

Yes please do post the code in the FreeRTOS Interactive site ([http://interactive.freertos.org).](http://interactive.freertos.org%29.)

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.

Regards.
