Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Example 08 — Source Code Deep-Dive
MSP vs PSP — Dual Stack Pointers
Why ARM Cortex-M4 has two stack pointers, how change_sp_to_psp() works in assembly, what a naked function is, and why every RTOS uses PSP for tasks and MSP for the kernel.
1. Overview — What This Example Does
The 008_stack project demonstrates the ARM Cortex-M4 dual stack pointer architecture:
- On reset: Thread Mode uses MSP (CONTROL.SPSEL=0)
- Calls
change_sp_to_psp()— initialises PSP and switches Thread Mode to use PSP - All subsequent function calls (including
fun_add()) use the PSP for stack operations - Generates an SVC exception → CPU uses MSP in Handler Mode regardless of PSP
- SVC_Handler runs, prints result, returns to Thread Mode using PSP
2. Source Code — Full Annotated Walkthrough
#include <stdio.h>
#define SRAM_START 0x20000000U
#define SRAM_SIZE (128 * 1024) /* 128KB SRAM */
#define SRAM_END (SRAM_START + SRAM_SIZE) /* 0x20020000 */
#define STACK_START SRAM_END
#define STACK_MSP_START STACK_START /* 0x20020000 — MSP initially here */
#define STACK_MSP_END (STACK_MSP_START - 512) /* 0x2001FE00 — MSP limit */
#define STACK_PSP_START STACK_MSP_END /* 0x2001FE00 — PSP starts here */
/* A simple function to demonstrate stack usage with PSP */
int fun_add(int a, int b, int c, int d)
{
return a + b + c + d; /* After sp switch, this uses PSP for local vars */
}
/* ----------------------------------------------------------------
* change_sp_to_psp() — NAKED FUNCTION
*
* "naked" means: NO compiler-generated prologue/epilogue.
* The function body must be entirely inline assembly.
* The compiler will not insert PUSH/POP, so we control the
* stack frame entirely.
*
* Purpose: Initialize PSP to PSP_START and set CONTROL.SPSEL=1
* ---------------------------------------------------------------- */
__attribute__((naked)) void change_sp_to_psp(void)
{
/* Step 1: Define PSP_START as an assembly-visible symbol */
__asm volatile(".equ SRAM_END, (0x20000000 + (128 * 1024))");
__asm volatile(".equ PSP_START, (SRAM_END - 512)");
/* Step 2: Load PSP_START value into R0 */
__asm volatile("LDR R0, =PSP_START"); /* R0 = 0x2001FE00 */
/* Step 3: Write R0 into PSP register */
__asm volatile("MSR PSP, R0"); /* PSP = 0x2001FE00 */
/* Step 4: Set CONTROL.SPSEL = 1 → Thread Mode now uses PSP */
__asm volatile("MOV R0, #0x02"); /* 0b10: bit1=SPSEL=1 */
__asm volatile("MSR CONTROL, R0"); /* CONTROL = 0x02 */
/* Step 5: Return — BX LR is MANDATORY in naked functions */
__asm volatile("BX LR");
/* From this point, Thread Mode uses PSP instead of MSP */
}
void generate_exception(void)
{
/* SVC (Supervisor Call): triggers SVC exception immediately
* The immediate value #0x2 is embedded in the opcode
* and can be read by the SVC handler */
__asm volatile("SVC #0x2");
}
int main(void)
{
change_sp_to_psp(); /* Switch to PSP */
int ret;
ret = fun_add(1, 4, 5, 6); /* Uses PSP — stack grows from 0x2001FE00 */
printf("result = %d\n", ret); /* PSP used for printf's internal buffers */
generate_exception(); /* SVC triggers → Handler Mode uses MSP */
for(;;);
}
void SVC_Handler(void)
{
/* Handler Mode: always uses MSP, always privileged */
printf("in SVC_Handler\n");
}
3. MSP and PSP — Complete Explanation
What Are They?
ARM Cortex-M4 has two physically separate stack pointer registers:
| Feature | MSP (Main Stack Pointer) | PSP (Process Stack Pointer) |
|---|---|---|
| Register name | MSP (also accessible as R13 in certain contexts) | PSP |
| Access | MRS/MSR MSP (privileged) | MRS/MSR PSP (privileged) |
| Default after reset | Loaded from vector table[0] | Unknown (unpredictable) |
| Thread Mode use | CONTROL.SPSEL=0 (default) | CONTROL.SPSEL=1 |
| Handler Mode use | Always | Never |
| Exception stacking | Used if CONTROL.SPSEL=0 in Thread Mode | Used if CONTROL.SPSEL=1 in Thread Mode |
| RTOS purpose | Kernel/scheduler stack | Each task has its own PSP region |
SRAM Stack Layout in This Example
Diagram: SRAM Stack Layout in This Example
0x20020000
← MSP initial value (SRAM_END) MSP starts here
0x2001FFFC
MSP stack grows downward from here
0x2001FF00
… MSP stack area (512 bytes reserved) …
0x2001FE00
← PSP_START (STACK_MSP_END) PSP starts here
0x2001FDF0
PSP stack grows downward from here
…
PSP stack area
0x20000000
SRAM start (.data, .bss sections)
4. Naked Functions — Deep Dive
What the Compiler Normally Does
/* Normal function — compiler generates prologue and epilogue */
void normal_func(void)
{
/* Compiler inserts: PUSH {R4, LR} ← PROLOGUE */
int local = 5;
/* ... body ... */
/* Compiler inserts: POP {R4, PC} ← EPILOGUE */
}
/* What the compiler actually generates in assembly: */
normal_func:
PUSH {R4, LR} /* Save callee-saved registers + return addr */
SUB SP, SP, #4 /* Allocate space for local variable */
MOV R4, #5
STR R4, [SP, #0] /* local = 5 on the stack */
ADD SP, SP, #4 /* Deallocate */
POP {R4, PC} /* Restore and return */
Naked Function — No Prologue/Epilogue
/* Naked function — compiler generates ONLY what you write */
__attribute__((naked)) void naked_func(void)
{
/* What the compiler generates — exactly this, nothing more: */
__asm volatile("MOV R0, #0x02");
__asm volatile("MSR CONTROL, R0");
__asm volatile("BX LR"); /* BX LR is REQUIRED — must return! */
/* NO PUSH/POP generated by compiler */
/* NO stack frame created */
}
/* WHY NAKED IS NEEDED HERE:
* change_sp_to_psp() switches the stack from MSP to PSP.
* If the compiler inserted PUSH {LR} at the start (before MSP→PSP),
* and POP {PC} at the end (after MSP→PSP), it would push onto MSP
* but pop from PSP — corrupting both stacks!
* naked prevents this split-stack corruption. */
change_sp_to_psp — Assembly Dissection
/* Instruction-by-instruction walkthrough */
__asm volatile(".equ SRAM_END, (0x20000000 + (128 * 1024))");
/* .equ is an assembler directive: defines a symbol SRAM_END = 0x20020000
* This is evaluated at assemble time, not at runtime.
* Creates a constant, not a variable. */
__asm volatile(".equ PSP_START, (SRAM_END - 512)");
/* PSP_START = 0x20020000 - 512 = 0x2001FE00 */
__asm volatile("LDR R0, =PSP_START");
/* LDR with = is a pseudo-instruction.
* The assembler places the constant 0x2001FE00 in a literal pool
* (a few bytes of Flash near this code) and generates:
* LDR R0, [PC, #offset_to_literal_pool]
* After execution: R0 = 0x2001FE00 */
__asm volatile("MSR PSP, R0");
/* Move R0 into the PSP special register.
* After: PSP = 0x2001FE00
* Thread Mode will use this as stack top when SPSEL=1.
* Note: MSP still points to SRAM_END (set from vector table on reset). */
__asm volatile("MOV R0, #0x02");
/* R0 = 0x02 = 0b00000010
* bit1 = SPSEL = 1 → use PSP in Thread Mode
* bit0 = nPRIV = 0 → remain privileged */
__asm volatile("MSR CONTROL, R0");
/* CONTROL = 0x02 → Thread Mode now uses PSP.
* From this instruction onwards, all stack operations
* (PUSH, POP, function calls) use PSP, not MSP.
* An ISB should follow MSR CONTROL per ARM spec. */
__asm volatile("BX LR");
/* Return from naked function.
* LR holds the return address set by the caller.
* If we didn't have "naked", the compiler would have done
* "POP {PC}" here — popping from MSP (since PUSH was on MSP
* at function entry). But now SP is PSP (not yet populated!).
* Using BX LR bypasses any stack-based return, correctly
* returning to the caller. */
5. SVC — Supervisor Call
When generate_exception() executes SVC #0x2:
- The processor saves the exception frame to the PSP (since Thread Mode was using PSP)
- The SVC_Handler executes using the MSP (Handler Mode always uses MSP)
- LR in SVC_Handler =
0xFFFFFFFD(EXC_RETURN: return to Thread Mode using PSP)
/* Exception frame saved to PSP when SVC fires from PSP-using Thread Mode */
/* PSP points to:
* [PSP + 0x1C] ← xPSR (stacked)
* [PSP + 0x18] ← PC (address after SVC instruction)
* [PSP + 0x14] ← LR
* [PSP + 0x10] ← R12
* [PSP + 0x0C] ← R3
* [PSP + 0x08] ← R2
* [PSP + 0x04] ← R1
* [PSP + 0x00] ← R0 ← PSP points here after stacking
*
* SVC_Handler then runs:
* MSP is used as its stack (not PSP).
* LR = 0xFFFFFFFD = EXC_RETURN: return to Thread Mode using PSP.
*/
6. MSP/PSP in an RTOS Context
/* RTOS-style stack architecture:
*
* SRAM_TOP (0x20020000) ← MSP initial value
* ───────────────────── MSP stack (kernel/scheduler)
* Each interrupt handler, PendSV, SysTick uses MSP.
*
* T1_STACK_TOP ← PSP for Task 1
* ───────────────────── Task 1 PSP stack (1KB)
*
* T2_STACK_TOP ← PSP for Task 2
* ───────────────────── Task 2 PSP stack (1KB)
*
* T3_STACK_TOP ← PSP for Task 3
* ───────────────────── Task 3 PSP stack (1KB)
*
* When scheduler switches to Task 1:
* MSR PSP, R0 (R0 = T1's saved PSP value)
* MOV R0, #0x02
* MSR CONTROL, R0 (SPSEL=1: use PSP)
* BX LR (load EXC_RETURN value, return to Task 1)
*
* Task 1 runs with PSP. If it calls a function:
* PUSH {R4, LR} goes to T1's PSP stack — isolated from other tasks!
*
* When SysTick fires (context switch):
* CPU automatically saves Task 1's SF1 frame to PSP
* SysTick handler runs with MSP (kernel stack)
* PendSV handler manually saves R4-R11 to PSP (STMDB R0!, {R4-R11})
* Then switches PSP to Task 2's PSP
* Returns to Task 2 via EXC_RETURN 0xFFFFFFFD */
7. Interview Questions & Answers
Q1. What is the difference between MSP and PSP in ARM Cortex-M4?
ARM Cortex-M4 has two stack pointer registers:
MSP (Main Stack Pointer): Default stack pointer. Used by the reset handler, all exception handlers (Handler Mode), and Thread Mode when CONTROL.SPSEL=0. Initialized from vector table[0] (first word of Flash) at reset. Also called the “privileged” or “system” stack.
PSP (Process Stack Pointer): Optional second stack pointer. Used in Thread Mode when CONTROL.SPSEL=1. Not used by any exception handler. Must be explicitly initialised by software (MSR PSP, Rx) before enabling. Used by RTOS to give each task its own isolated stack.
Key rule: Handler Mode ALWAYS uses MSP. Thread Mode uses either MSP (SPSEL=0) or PSP (SPSEL=1) depending on CONTROL register bit 1.
MSP (Main Stack Pointer): Default stack pointer. Used by the reset handler, all exception handlers (Handler Mode), and Thread Mode when CONTROL.SPSEL=0. Initialized from vector table[0] (first word of Flash) at reset. Also called the “privileged” or “system” stack.
PSP (Process Stack Pointer): Optional second stack pointer. Used in Thread Mode when CONTROL.SPSEL=1. Not used by any exception handler. Must be explicitly initialised by software (MSR PSP, Rx) before enabling. Used by RTOS to give each task its own isolated stack.
Key rule: Handler Mode ALWAYS uses MSP. Thread Mode uses either MSP (SPSEL=0) or PSP (SPSEL=1) depending on CONTROL register bit 1.
Q2. Why do RTOS implementations use PSP for tasks and MSP for the kernel?
Separation of stacks provides several benefits:
1. Isolation: Each task has its own PSP stack. A stack overflow in one task doesn’t corrupt the kernel stack (MSP) or another task’s stack. The RTOS can add stack sentinel values to detect overflows per-task.
2. Stack depth accounting: The RTOS knows exactly how much PSP stack each task has used (compare PSP with PSP_START). Cannot measure usage on shared MSP.
3. Easy context save: On exception entry (SysTick), hardware saves 8 registers to PSP. PendSV saves the remaining 8 (R4-R11) to PSP. All 16 registers are now on the PSP — easy to save/restore per-task.
4. Security: MSP (kernel) can be in MPU-protected privileged-only memory. PSP (task) in per-task MPU region. This prevents a task from writing to the kernel stack even through a pointer error.
1. Isolation: Each task has its own PSP stack. A stack overflow in one task doesn’t corrupt the kernel stack (MSP) or another task’s stack. The RTOS can add stack sentinel values to detect overflows per-task.
2. Stack depth accounting: The RTOS knows exactly how much PSP stack each task has used (compare PSP with PSP_START). Cannot measure usage on shared MSP.
3. Easy context save: On exception entry (SysTick), hardware saves 8 registers to PSP. PendSV saves the remaining 8 (R4-R11) to PSP. All 16 registers are now on the PSP — easy to save/restore per-task.
4. Security: MSP (kernel) can be in MPU-protected privileged-only memory. PSP (task) in per-task MPU region. This prevents a task from writing to the kernel stack even through a pointer error.
Q3. What is a “naked” function attribute and why is it needed here?
The
In
With naked: no PUSH/POP. The function uses BX LR explicitly for return, which uses the caller-provided LR register directly without any stack involvement.
__attribute__((naked)) attribute prevents GCC from generating any function prologue (PUSH registers at the start) or epilogue (POP registers at the end). The function body contains only the exact inline assembly you write.In
change_sp_to_psp(), this is critical because the function switches the stack pointer from MSP to PSP halfway through. If GCC generated a normal prologue, it would PUSH {LR} to MSP before the switch. The corresponding epilogue would try to POP {PC} from PSP (after the switch) — but PSP hasn’t been loaded yet, so it would read garbage as the return address, causing a crash.With naked: no PUSH/POP. The function uses BX LR explicitly for return, which uses the caller-provided LR register directly without any stack involvement.
Q4. How is the PSP initialised and what value should it be set to?
PSP is initialised using the MSR instruction:
The PSP value should be the top of the stack area allocated for Thread Mode (or for the first task in an RTOS). The ARM stack grows downward, so the initial SP should be the highest address of the stack region + 4 (or simply the top of the allocated block).
In this example: PSP = 0x2001FE00 = SRAM_END − 512. This means the first 512 bytes below 0x2001FE00 are the PSP stack. When a PUSH instruction executes (SP -= 4, then write), data is stored at 0x2001EFFC, 0x2001EFF8, etc. The stack grows toward lower addresses.
__asm volatile("MSR PSP, R0"); where R0 holds the desired PSP value.The PSP value should be the top of the stack area allocated for Thread Mode (or for the first task in an RTOS). The ARM stack grows downward, so the initial SP should be the highest address of the stack region + 4 (or simply the top of the allocated block).
In this example: PSP = 0x2001FE00 = SRAM_END − 512. This means the first 512 bytes below 0x2001FE00 are the PSP stack. When a PUSH instruction executes (SP -= 4, then write), data is stored at 0x2001EFFC, 0x2001EFF8, etc. The stack grows toward lower addresses.
Q5. What is CONTROL.SPSEL and how is it different from CONTROL.nPRIV?
Both are bits in the CONTROL register, but they control independent aspects of Thread Mode behaviour:
CONTROL.bit0 (nPRIV): Privilege level of Thread Mode. 0=privileged, 1=unprivileged. Affects what registers/memory Thread Mode can access.
CONTROL.bit1 (SPSEL): Stack pointer selection for Thread Mode. 0=use MSP, 1=use PSP. Affects which of the two stack pointer registers is the active one when Thread Mode code runs (PUSH, POP, function calls).
An RTOS typically sets both: CONTROL = 0x03 (bit1=1 PSP, bit0=1 unprivileged). CONTROL = 0x02 (bit1=1 PSP, bit0=0 privileged) is used in this example — PSP but still privileged.
CONTROL.bit0 (nPRIV): Privilege level of Thread Mode. 0=privileged, 1=unprivileged. Affects what registers/memory Thread Mode can access.
CONTROL.bit1 (SPSEL): Stack pointer selection for Thread Mode. 0=use MSP, 1=use PSP. Affects which of the two stack pointer registers is the active one when Thread Mode code runs (PUSH, POP, function calls).
An RTOS typically sets both: CONTROL = 0x03 (bit1=1 PSP, bit0=1 unprivileged). CONTROL = 0x02 (bit1=1 PSP, bit0=0 privileged) is used in this example — PSP but still privileged.
Q6. What is EXC_RETURN 0xFFFFFFFD and when does it appear?
0xFFFFFFFD is the EXC_RETURN value that the processor loads into LR when an exception is entered from Thread Mode that was using PSP. When this value is loaded into PC (via BX LR at the end of the ISR), the processor performs an exception exit:
• Returns to Thread Mode (not Handler Mode)
• Uses PSP (not MSP) for unstacking — pops the exception frame from PSP
• Restores R0–R3, R12, LR, PC, xPSR from PSP
The three EXC_RETURN values are:
• 0xFFFFFFF1: Return to Handler Mode (nested interrupt), use MSP
• 0xFFFFFFF9: Return to Thread Mode, use MSP
• 0xFFFFFFFD: Return to Thread Mode, use PSP ← this example
The processor recognises these values (bits 31:5 all 1s = impossible real address) as exception return triggers rather than normal branch targets.
• Returns to Thread Mode (not Handler Mode)
• Uses PSP (not MSP) for unstacking — pops the exception frame from PSP
• Restores R0–R3, R12, LR, PC, xPSR from PSP
The three EXC_RETURN values are:
• 0xFFFFFFF1: Return to Handler Mode (nested interrupt), use MSP
• 0xFFFFFFF9: Return to Thread Mode, use MSP
• 0xFFFFFFFD: Return to Thread Mode, use PSP ← this example
The processor recognises these values (bits 31:5 all 1s = impossible real address) as exception return triggers rather than normal branch targets.
Q7. What is a stack overflow and how can the dual stack pointer architecture help detect it?
A stack overflow occurs when the stack pointer decrements past the bottom of the allocated stack region. In embedded systems (no virtual memory), it silently corrupts the adjacent memory (typically .bss or .data sections), causing unpredictable behaviour.
With MSP/PSP separation in an RTOS:
1. Each task has a known PSP start address and size (e.g., 1KB)
2. The RTOS can check if
3. A stack sentinel (magic value) can be placed at the bottom of each task stack. If it gets overwritten, a stack overflow is detected at the next check.
4. The MPU can be configured to make the last 32 bytes of each task stack read-only (no-access), causing a MemManage fault on overflow — immediate detection.
None of this is possible with a single shared MSP stack where all tasks mix their data.
With MSP/PSP separation in an RTOS:
1. Each task has a known PSP start address and size (e.g., 1KB)
2. The RTOS can check if
current_PSP < task_stack_bottom at each context switch3. A stack sentinel (magic value) can be placed at the bottom of each task stack. If it gets overwritten, a stack overflow is detected at the next check.
4. The MPU can be configured to make the last 32 bytes of each task stack read-only (no-access), causing a MemManage fault on overflow — immediate detection.
None of this is possible with a single shared MSP stack where all tasks mix their data.
Q8. What function does the SVC instruction serve and how does the SVC number work?
SVC (Supervisor Call) generates the SVCall exception (exception number 11, priority configurable). It is the primary mechanism for unprivileged code to request privileged services (the ARM equivalent of a system call in Linux).
The immediate value in
The immediate value in
SVC #N is encoded in the lower byte of the 16-bit Thumb opcode (0xDFNN where NN is the SVC number 0–255). The SVC handler can extract this number by reading the stacked PC value (return address), decrementing by 2 to get the SVC instruction address, and reading the lower byte: uint8_t svc_num = *(uint8_t*)(stacked_pc - 2); This is demonstrated in detail in examples 013 and 014.Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments