Course: Computer Architectures
Source lesson: ARM Exceptions and Interrupts

Modes and privilege

Cortex-M has Thread mode for normal code and Handler mode for exception handlers. Handler mode is always privileged. Thread mode can be privileged or user level.

CONTROL[0] selects privilege (0 privileged, 1 user). CONTROL[1] selects the active Thread-mode stack (0 MSP, 1 PSP). Handler mode uses MSP.

Automatic entry sequence

When an exception occurs, hardware:

  1. Stacks r0, r1, r2, r3, r12, LR, PC, and PSR on the currently active stack.
  2. Looks up the handler in the Interrupt Vector Table.
  3. Switches to MSP and updates IPSR with the exception number.
  4. Loads the handler address into PC and an EXC_RETURN code into LR.
  5. Runs the handler.

The new stack frame is:

Offset from new SPValue
0r0
4r1
8r2
12r3
16r12
20LR
24PC
28PSR

The saved PC is at offset #24 because six words come before it.

Vector table

The vector table maps exception numbers to handler addresses. It begins with the initial stack pointer, Reset, NMI, Hard Fault, memory, bus, and usage faults, followed by SVC, PendSV, SysTick, and external interrupts.

EXC_RETURN

During a handler, LR is not an ordinary subroutine return address. Its encoded value tells the processor how to restore context:

ValueReturn target
0xFFFFFFF1Handler mode
0xFFFFFFF9Thread mode using MSP
0xFFFFFFFDThread mode using PSP

The handler normally executes:

BX LR

The processor recognizes the special value, un-stacks the saved frame, clears the exception’s active state, and resumes the selected context.

Common confusion

Exception entry is not the same as BL: hardware saves a complete context and changes mode. LR contains EXC_RETURN, not simply the address after a call. The saved PC belongs to the interrupted code and is read from the stack frame.

Retrieval questions

  • Which stack is used while a handler runs? MSP.
  • Where is the stacked PC? At [SP,#24] from the new SP.
  • Why does BX LR return from an exception? Because LR contains an EXC_RETURN code.