Search code examples
cortex-minterrupt-handlingarm-mpu

Are exceptions stacked by the Cortex-M hardware in thread-mode or handler mode?


On Cortex-M processors with MPUs (let's use Cortex-M4 to be specific, but I bet the answer is the same for e.g. M3), what privilege mode is does the hardware exception entry stacking run in w.r.t the MPU?

Suppose I'm running in unprivileged thread mode using the process stack (PSP), with the MPU set to only accept writes within a particular region (e.g. a user-mode process is running). When an exception occurs, before the handler executes (in handler mode), the hardware stacks registers r0-r3,lr,pc etc onto the PSP. Does this also occur in unprivileged thread mode?

Specifically, suppose the process sets it's SP to some arbitrary point in memory it should not be allowed to write to, will the exception stacking result in a memory fault?


Solution

  • Coming back to this a year later after having dealt with this, the answer is that stacking occurs with whatever privilege was previously running.

    So, if in unprivileged mode an interrupt occurs, the hardware will stack registers on the PSP using the existing MPU settings as though unprivileged code is performing the stacking. If stacking would violate MPU rules, a MemManage Fault occurs, and the MemManage Fault Status Register's MSTKERR field will be set (page 4-25 of the Cortex-M4 user guide)