Skip to content
systemcoding.dev
Assembly

Read the main stack pointer with mrs r0, msp

Read the main stack pointer into r0 with mrs r0, msp on Cortex-M, privileged code only, for fault handlers that need to inspect the stacked frame.

1 min read
Summarize in AI

Inside a handler you often need the main stack pointer as a value, for example to find the registers the core stacked when an exception arrived. mrs r0, msp copies it into a general register. Cortex-M has two stack pointers, MSP and PSP, and sp (r13) is whichever one is current, so reading sp directly is not the same thing when thread code runs on the process stack.

msp.Sasm
    .syntax unified
    .thumb
    .global get_msp
    .thumb_func
get_msp:
    mrs   r0, msp
    bx    lr
Text
get_msp() -> 0x20001FE8     (example; depends on the stack the caller is using)

The AAPCS returns a 32-bit value in r0, so the C prototype is uint32_t get_msp(void);. The function is written for GNU as 2.4x in unified syntax, and MRS with a special register name exists on every Cortex-M. The ARMv7-M Architecture Reference Manual lists which special registers are available at which privilege level: stack pointer registers are meant for privileged code, so do not rely on this from an unprivileged thread.

Arm's CMSIS wraps it as __get_MSP(); use that in C and keep the assembly for startup and handler stubs.

Also inEmbedded
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.