17.2 Writing an Interrupt Service Routine

An interrupt service routine takes no arguments and returns no results, that is, its argument list is void, as is its return type. This pattern is not enforced but executing an ISR that does not follow it will result in unpredictable behavior.

On Cortex-M cores, the hardware takes care of preserving and restoring context. When an ISR is executed, in addition to other things, the hardware saves registers r0, r1, r2, r3, r12, and r14 on the stack and restores them when the function exits. Consequently, any function with no return value and no arguments that conforms to the procedure call standard of the platform can be used as a handler function. Regardless, a function should still be marked as an interrupt handler function using the interrupt attribute so that the compiler knows that it is used. When seeing the interrupt attribute, the compiler generates code to guarantee the stack is 8-byte (double-word) aligned when the function is entered and restores the stack pointer to its original value when the function exits. Such an action is a safeguard, but the extra instructions are not necessary if the device is configured to guarantee an 8-byte aligned stack upon exception entry.

When targeting Cortex-A devices, the compiler must generate application code to save and restore the device context. The function acting as the interrupt handler, therefore, must use the interrupt attribute so that the compiler can ensure the correct context switch is generated.

See the appropriate architecture reference manual for full details on that device's exception entry and exit behavior.