</>EmbeddedInterview

What happens in hardware when an exception is taken on Cortex-M?

MediumMicrocontrollers & ARM Cortex-M

Short answer: The core automatically pushes an 8-word stack frame (R0–R3, R12, LR, PC, xPSR) onto the current stack, fetches the handler's address from the vector table at the same time, loads LR with a special EXC_RETURN value, switches to Handler mode using MSP, and starts the handler. When the handler returns (branching to the EXC_RETURN value), the hardware unstacks the registers and resumes the interrupted code. This is why ISRs can be ordinary C functions.

Step by step

  1. Stacking: push xPSR, PC (return address), LR, R12, R3, R2, R1, R0 onto the active stack (MSP or PSP), 8-byte aligned (an extra padding word is added if needed, recorded in xPSR bit 9). If the FPU is active, S0–S15 and FPSCR are also stacked (18 more words), unless lazy stacking reserves the space and saves them only if the handler uses the FPU.
  2. Vector fetch: read the handler address from VTOR + 4 × exception_number, in parallel with stacking (Harvard buses).
  3. Update registers: PC = handler address, LR = EXC_RETURN, IPSR = exception number, switch to Handler mode (always privileged) on MSP.
  4. Handler runs. Higher-priority exceptions can pre-empt it (nesting).
  5. Return: BX LR (or POP {..., PC}) with an EXC_RETURN value tells the core to perform an exception return: unstack, restore mode and stack pointer, continue the interrupted code.

Timing: 12 cycles from the interrupt to the first handler instruction on Cortex-M3/M4 (zero wait states), similar on exit, and only 6 cycles between back-to-back handlers with tail-chaining.

The stacked frame layout (lowest address first)

Offset Register
0x00 R0
0x04 R1
0x08 R2
0x0C R3
0x10 R12
0x14 LR (of the interrupted code)
0x18 PC (return address)
0x1C xPSR

Fault handlers read frame[6] to find the instruction that faulted.

What the hardware does not save: R4–R11 (and S16–S31). The compiler saves them in the handler if it uses them (AAPCS callee-saved), and an RTOS saves them in software during a context switch.