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

729 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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)

0
On

About MPU rule violation & MSTKERR / MUNSKERR, when exception occurs in unprivileged software, and MPU is enabled:

  • On the exception entry, if the base address of allocated stack memory for the unprivileged software is NOT aligned to its stack size, then Cortex-M4 generates MemManage fault and MSTKERR field is set.

  • On the exception return, similarly if the base address of allocated stack memory is NOT aligned to its stack size, then Cortex-M4 generates MemManage fault and MUNSKERR field is set.

For example MPU_RASR.SIZE = 0x7 means the MPU region for the stack has size 2^(7+1) = 256 bytes , then MPU_RBAR.ADDR must be like 0x00000100 , 0x00000200 ... etc., otherwise Cortex-M4 generates corresponding MemManage fault immediately on exception entry/return.

For more information please read section 4.5.4 MPU Region Base Address Register in DUI0553 - Cortex ™ -M4 Devices Generic User Guide .