The Complete Guide to ARM Cortex-M Assembly (Thumb-2)
Learn Cortex-M assembly end to end: registers, Thumb-2 encodings, branches, calling convention, startup, interrupts, RTOS switching, atomics, DSP and FPU.

Most Cortex-M firmware is written in C, and most of it never needs a line of assembly. Then one day it does. A HardFault lands in a handler and the only useful information is a stacked program counter. A vendor's startup file does something you cannot explain. A context switch has to save registers the compiler cannot reach. A loop has to hit the same cycle count every time. At that moment the engineer who can read and write Thumb-2 is the one who finishes the day, and the engineer who cannot is reduced to guessing. This guide is the route from zero to that ability. It covers the processor's programmer's model, the instruction encodings and the toolchain, then the instructions you use every day, the calling convention that lets assembly and C share a program, and the system-level pieces that only assembly can do: the vector table, exception entry, interrupt control, SVC and PendSV, exclusive access, and the DSP and floating-point extensions. Facts come from the Armv6-M, Armv7-M and Armv8-M Architecture Reference Manuals, the technical reference manuals of the cores, and the Arm Procedure Call Standard. Toolchain examples use Arm GNU Toolchain 14 (GCC 14, binutils 2.42), and every code sample is written to be assembled with arm-none-eabi-gcc.
"A Cortex-M runs one instruction set, Thumb, in two sizes. Once you can tell a 16-bit encoding from a 32-bit one and know which core owns which instruction, every listing you open stops being foreign."
Two rules govern how to use the guide. First, read the sections in order the first time: each one assumes the registers and conventions of the sections before it. Second, treat every cycle count and size as something to verify on your own part, since two chips sold with the same core name differ in memory wait states, bus width and optional features.
Why write Cortex-M assembly at all
Compilers are good. For a loop that adds numbers, a modern GCC produces code that you will not beat by hand, and the maintenance cost of assembly is high. So the reasons to write it are narrow, and knowing them tells you where to spend effort.
The first is code that the language cannot express. The reset handler that runs before .data is initialized cannot be written in C that uses globals. A context switch has to save and restore r4 to r11 and swap stack pointers, which C has no syntax for. System registers need mrs and msr, and barriers need dsb and isb. The second is code whose timing is the specification: a bit-banged waveform where the pulse is a count of cycles. The third is code that uses an instruction the compiler will not choose, such as a DSP multiply-accumulate in a hand-tuned filter. The fourth is reading: you debug compiled code by reading its disassembly, and every fault investigation ends in a listing.
The fifth reason is learning how the machine works, which changes how you write C. After you have seen what a volatile access, a function call and a switch statement turn into, you stop writing code that fights the hardware.
What assembly is not for is general speed. If a profile says a function is slow, look first at the algorithm, the data layout and the compiler flags. Hand-written assembly beats the compiler rarely, and almost never twice: the next compiler release closes the gap while your routine stays frozen.
The Cortex-M family and its instruction sets
"Cortex-M" is a family of cores with a common programmer's model and different instruction sets. Three architecture profiles matter.
| Architecture | Cores | What it adds |
|---|---|---|
| Armv6-M | M0, M0+, M1 | Small Thumb set: about 56 instructions, almost all 16-bit |
| Armv7-M | M3 | Full Thumb-2, hardware divide, bitfield and exclusive instructions, it blocks |
| Armv7E-M | M4, M7 | DSP instructions, optional FPU |
| Armv8-M Baseline and Mainline | M23, M33 and later | TrustZone, stack limit registers, more instructions |
The key fact for portability is that the sets nest. Everything in Armv6-M is in Armv7-M, and everything in Armv7-M is in Armv7E-M. A binary built for the Cortex-M0 runs on an M4, and the reverse is not true. If you must ship one object for several cores, write to the lowest one you support. The longer comparison of what each core has is in the post on the instruction set differences between the M0, M3, M4 and M7, and the practical consequences are these:
On Armv6-M there are no
itblocks, nocbzandcbnz, nomovwandmovt, no hardware divide, and no exclusive access. Most data-processing instructions work onr0tor7only and always set flags.On Armv7-M all of those exist, along with
bfi,ubfx,rbit,clzandBASEPRI.On Armv7E-M you also have
smlad,qadd,ssatand a single-precision FPU on the F parts.
The choice of core is made at the compiler with -mcpu. Everything the assembler accepts follows from it, which makes the build flags the first thing to get right.
Registers: the programmer's model
The processor exposes sixteen 32-bit registers to ordinary code. r0 to r12 are general purpose, r13 is the stack pointer sp, r14 is the link register lr, and r15 is the program counter pc. The low registers r0 to r7 can be used by every 16-bit instruction, while r8 to r12 are reachable only by a few. A status register, xPSR, combines three views: APSR holds the flags N, Z, C and V, IPSR holds the number of the exception being handled, and EPSR holds the Thumb state bit and the IT block state.
The stack pointer is two registers in disguise. MSP, the main stack pointer, is used after reset and in every exception handler. PSP, the process stack pointer, lets an operating system give each task its own stack. Bit 1 of the CONTROL register selects which one thread mode uses. A bare-metal program never touches PSP.
Three special registers are read and written with mrs and msr and are not part of the numbered set. PRIMASK masks all configurable exceptions when its bit is set, BASEPRI masks only exceptions below a priority value, and CONTROL selects the stack and privilege. These matter later, when interrupts arrive.
You can look at the registers from assembly:
.syntax unified
.cpu cortex-m4
.thumb
.text
.global read_ipsr
.type read_ipsr, %function
.thumb_func
// uint32_t read_ipsr(void): returns the current exception number, 0 in thread mode
read_ipsr:
mrs r0, ipsr
bx lr
.size read_ipsr, .-read_ipsrCalled from main it returns 0, and from the SysTick_Handler it returns 15. The detailed table of registers and what each is for is in the post on registers, and this single function shows the pattern: a special register, the mrs instruction, and a result left in r0.
Thumb, Thumb-2 and how instructions are encoded
A Cortex-M executes only Thumb code. The instruction set began as a 16-bit encoding called Thumb and was extended with 32-bit instructions into Thumb-2, named T32 in the Armv8 documents. The two sizes mix freely in one stream: if the first halfword of an instruction begins with the bits 0b11101, 0b11110 or 0b11111, it is a 32-bit instruction and continues in the next halfword, and anything else is complete in 16 bits. Instructions are only halfword aligned.
You can see this in a disassembly. movs r0, #1 is the single halfword 0x2001. movw r0, #0x1234 is the two halfwords 0xF241 0x2034. bx lr is 0x4770. Reading the encoding column of arm-none-eabi-objdump -d tells you immediately which of your instructions took two bytes and which four, and so what your code size is.
The processor has no ARM state, which is why every address that you branch to must have bit 0 set. The core reads that bit as the new Thumb state bit, and a clear bit means ARM state, which a Cortex-M cannot enter. The result is a fault called INVSTATE, one of the most common mistakes in handwritten code. The linker sets the bit for you on symbols that the assembler knows are Thumb functions. Your job is to mark each assembly entry point with .thumb_func.
Two consequences shape the way assembly looks on a Cortex-M0. First, the 16-bit data-processing instructions set flags always, so you write adds and movs. Second, many operations take the destination as one of the sources, so ands r0, r1 replaces and r0, r1, r2. On Armv7-M and later the 32-bit forms give back three-operand forms and flag-preserving variants.
Unified syntax, directives and the toolchain
Cortex-M assembly in GNU as starts with a header that you will paste into every file:
.syntax unified // UAL: one syntax for ARM and Thumb
.cpu cortex-m4 // which instructions are legal
.fpu fpv4-sp-d16 // which FPU instructions are legal (M4F)
.thumb // encode in Thumb.syntax unified selects the Unified Assembler Language, which is the syntax every Arm manual uses. Without it GNU as assembles in the older divided syntax and the same mnemonics mean different things, mainly around the s suffix on flag-setting instructions. .cpu limits the assembler to what the core can run, so sdiv on a cortex-m0 file stops the build with a clear message, which is what you want.
Each function needs a few more lines:
.text
.global my_func
.type my_func, %function
.thumb_func
my_func:
// ...
bx lr
.size my_func, .-my_func.global exports the symbol, .type and .size give debuggers and nm the information they need, and .thumb_func makes the assembler record the symbol as Thumb code so that its address gets bit 0 set.
The flags that tie a build together are -mcpu, -mthumb, -mfloat-abi and -mfpu. -mcpu=cortex-m4 picks the instruction set and the scheduling model. -mfloat-abi=hard with -mfpu=fpv4-sp-d16 uses the FPU and passes floats in FPU registers, and -mfloat-abi=soft does everything in software. Object files built with different float ABIs cannot be linked together, and the linker says so with a message about VFP register arguments. Name the same flags in every compile, assemble and link command. If you give a .S file the C preprocessor, #include and #define work in assembly.
Build and inspect with three commands:
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -c max.S -o max.o
arm-none-eabi-objdump -d max.o
arm-none-eabi-nm -S max.oMoving data: load, store and addressing
The Cortex-M is a load-store machine. Arithmetic works on registers, and a small set of instructions moves values to and from memory. ldr loads a 32-bit word, str stores one, and the b, h, sb and sh suffixes select bytes and halfwords with zero or sign extension. A byte of 0xFF loads as 255 with ldrb and as -1 with ldrsb.
The memory operand sits in square brackets. [r1] is the address in r1. [r1, #4] adds a constant. [r1, r2] adds a register, and [r1, r2, lsl #2] scales it for a word array. On Armv7-M you also get writeback: [r1, #4]! updates r1 before the access and [r1], #4 after, which is how a loop walks a buffer in one instruction. The 16-bit encodings limit offsets: a word load from a low register reaches offsets 0 to 124 in steps of four.
ldm and stm move several registers at once, lowest register at the lowest address, with ! to write the base register back. push {r4, lr} and pop {r4, pc} are the stack versions. This function copies four words and is valid on the smallest core:
.syntax unified
.cpu cortex-m0
.thumb
.text
.global copy4
.type copy4, %function
.thumb_func
// void copy4(uint32_t *dst, const uint32_t *src)
copy4:
ldmia r1!, {r2, r3}
stmia r0!, {r2, r3}
ldmia r1!, {r2, r3}
stmia r0!, {r2, r3}
bx lr
.size copy4, .-copy4Called with src = {1, 2, 3, 4}, it leaves dst equal to {1, 2, 3, 4}.
dst = 1 2 3 4Alignment rules differ between cores. A Cortex-M0 faults on any unaligned word or halfword access. A Cortex-M3 and later allow unaligned single loads and stores unless the configuration says otherwise, but never for ldm, stm, push and pop. When a protocol hands you packed fields, read bytes and assemble the value in registers.
Arithmetic, logic, flags and the barrel shifter
Data-processing instructions take registers or small immediates and put the result in a register. The core set is add, sub, rsb (reverse subtract), adc and sbc (with carry), and, orr, eor, bic (bit clear), mvn (move not), mul and, on Armv7-M, sdiv and udiv. The flags N, Z, C and V are set only by instructions with an s suffix and by the compare instructions cmp, cmn and tst. So adds r0, r0, #1 increments and sets flags, add r0, r0, #1 increments without, and on a Cortex-M0 only the first exists for low registers.
Reading flags means knowing what each means. After a subtraction or compare, C is set when no borrow was needed, so for unsigned values r0 >= r1 leaves C set and bcs (also written bhs) branches. For signed values the overflow flag matters, and ge tests N == V. Using a signed condition on unsigned data is a classic bug: 0xFFFFFFFF is below 1 under lt and above it under hi.
On Armv7-M the last operand of most data-processing instructions can be shifted for free. add r0, r1, r2, lsl #2 computes r1 + (r2 << 2), the address of a word-array element, in one instruction. The shift operations are lsl, lsr, asr, ror and rrx. They are also the basis of multiplication by constants without a multiplier: add r0, r0, r0, lsl #2 multiplies by 5, and rsb r0, r0, r0, lsl #3 by 7. On the Cortex-M0 there is no shifted-operand form, so the shift is a separate lsls.
Armv7-M adds the bit-field instructions that register-map code uses constantly. ubfx r0, r1, #8, #4 extracts four bits starting at bit 8, bfi r0, r1, #8, #4 inserts the low four bits of r1 there without touching the others, and bfc clears a field. clz counts leading zeros, rbit reverses the bit order, and rev swaps bytes for endianness. On a Cortex-M0, rev, rev16, revsh, sxtb, sxth, uxtb and uxth exist, but the field instructions do not, so the same job takes shifts and masks.
Loading constants
A 32-bit instruction cannot hold a 32-bit constant, and Cortex-M has four ways around that. movs r0, #n loads 0 to 255 in 16 bits. On Armv7-M, mov.w takes a modified immediate: an 8-bit value rotated, or one of the replication patterns 0x00XY00XY, 0xXY00XY00 and 0xXYXYXYXY. For anything else, movw loads the low 16 bits and clears the high half, and movt writes the high half and leaves the low one. The pair builds any constant in 8 bytes with no memory access, and exists on Armv7-M and later but not on the Cortex-M0.
The portable option is the pseudo-instruction ldr r0, =value. The assembler stores the constant in a literal pool and emits a PC-relative load, or substitutes a mov when the value fits one. The pool defaults to the end of the section. A 16-bit PC-relative load reaches only 0 to 1020 bytes forward, so in a long function you must place a pool yourself with .ltorg after an unconditional branch or return. A pool in the middle of straight-line code would be executed as instructions.
movs r0, #200 // 0..255
mov.w r1, #0xFF000000 // modified immediate (Armv7-M)
movw r2, #0x5678 // r2 = 0x00005678
movt r2, #0x1234 // r2 = 0x12345678
ldr r3, =0x12345678 // portable: literal poolAll of r2 and r3 hold 0x12345678 at the end. The dedicated posts on constants and on .ltorg go through the encodings and the placement rules.
Branches, conditions and IT blocks
b label jumps, bl label jumps and stores the return address in lr, bx rm jumps to a register, and blx rm calls through one. Conditional forms add a condition suffix: beq, bne, bcs, bcc, bmi, bpl, bhi, bls, bge, blt, bgt and ble. The 16-bit conditional branch reaches about 256 bytes either way, the 16-bit unconditional one about 2 KB, and the 32-bit forms up to 16 MB. When a target is out of range on a Cortex-M0, the assembler stops, and the fix is to invert the condition and jump over an unconditional branch.
Armv7-M adds two tools for short tests. cbz r0, label and cbnz r0, label branch forward up to 126 bytes if a low register is zero or not, without touching flags. And it blocks make the next one to four instructions conditional: after it lt, an rsblt r0, r0, #0 negates r0 only if the last compare said less than. The letters t and e after it choose then or else for each instruction, and the block may not contain a branch except as its last instruction.
.syntax unified
.cpu cortex-m4
.thumb
.text
.global abs32
.type abs32, %function
.thumb_func
// int32_t abs32(int32_t x)
abs32:
cmp r0, #0
it lt
rsblt r0, r0, #0
bx lr
.size abs32, .-abs32abs32(-5) is 5 and abs32(5) is 5. Inside an IT block the 16-bit data-processing instructions do not update flags, the reverse of the usual rule, and the assembler enforces that the condition on each instruction matches the block.
The calling convention: where assembly meets C
An assembly function that C code calls must follow the Procedure Call Standard for the Arm Architecture, AAPCS. The rules that matter:
The first four 32-bit arguments arrive in
r0tor3, and further ones are on the stack at[sp]on entry.A 64-bit argument starts in an even register, so
f(int, long long)usesr0,r2andr3and leavesr1empty.The result returns in
r0, orr0andr1for 64 bits. Composite values over four bytes return through a hidden pointer inr0.A function may destroy
r0tor3andr12. It must preserver4tor11, andspmust come back as it went in.lrmust be saved by any function that calls another, becausebloverwrites it.The stack must be 8-byte aligned at every public interface.
With -mfloat-abi=hard, floats travel in s0 to s15 and s16 to s31 become callee-saved, and objects of the two ABIs do not link together. The function below adds a 32-bit and a 64-bit argument and shows the register-pair rule: a in r0, b in r2 and r3, and the result in r0 and r1.
.syntax unified
.cpu cortex-m3
.thumb
.text
.global addmix
.type addmix, %function
.thumb_func
// uint64_t addmix(uint32_t a, uint64_t b)
addmix:
adds r0, r2, r0
adc r1, r3, #0
bx lr
.size addmix, .-addmixaddmix(1, 0xFFFFFFFF) returns 0x100000000. The post on the 32-bit calling convention covers structs, variadic functions and the veneer register r12 in detail.
Stack, frames and function prologues
The stack grows downward and sp points at the last item pushed. push {r4, r5, lr} stores the three registers with the lowest-numbered one at the lowest address, and pop {r4, r5, pc} restores them and returns, since writing pc from a pop is a branch. A function that calls others uses this pair as its frame:
.syntax unified
.thumb
.text
.global caller
.type caller, %function
.thumb_func
// uint32_t caller(uint32_t x): returns helper(x) + x
caller:
push {r4, lr} // r4 keeps x across the call, lr is the return address
mov r4, r0
bl helper
adds r0, r0, r4
pop {r4, pc}
.size caller, .-callerPushing two registers keeps sp 8-byte aligned if it was aligned on entry. If you push an odd number, add a filler register so the next call still sees an aligned stack. Locals live below the saved registers: sub sp, sp, #16 allocates 16 bytes, you address them as [sp, #0] to [sp, #12], and add sp, sp, #16 frees them before the pop. The frame must be released in the reverse order of allocation, and a mismatch is the first place to look when a function returns to a wrong address.
The vector table and the startup code
When the core leaves reset it reads two words from the start of the vector table: the initial MSP and the reset handler address. Every exception and interrupt after that has a word in the same table, in the order the architecture fixes for the first sixteen entries (reset, NMI, HardFault, MemManage, BusFault, UsageFault, four reserved, SVCall, DebugMonitor, one reserved, PendSV, SysTick) and the chip vendor fixes for the rest. Each handler address needs its Thumb bit set, which .word handler provides for a .thumb_func symbol.
A startup file defines the table in its own section, gives every handler a weak default that spins forever, and supplies a reset handler that copies initialized data from flash to RAM, zeroes the uninitialized data, calls a clock-setup function and calls main. The linker script supplies _estack, _sidata, _sdata, _edata, _sbss and _ebss, and marks the table with KEEP so that section garbage collection does not remove it. A reset handler that touches the FPU must enable it first, by setting the CP10 and CP11 fields of CPACR at 0xE000ED88 to full access and following the write with dsb and isb, or the first floating-point instruction faults. The dedicated posts on the vector table and on enabling the FPU show both in full; here is the table's essence:
.syntax unified
.thumb
.section .isr_vector, "a", %progbits
g_vectors:
.word _estack // 0: initial MSP
.word Reset_Handler // 1: reset
.word NMI_Handler // 2
.word HardFault_Handler // 3
// ... remaining entries ...Contents of section .isr_vector:
8000000 00000220 41010008 ...The first word is the end of a 128 KB RAM at 0x20000000, and the second is 0x08000141: the reset handler at 0x08000140 with the Thumb bit set.
Exceptions and interrupts: what the hardware does for you
When an exception is taken, the core pushes eight registers onto the active stack: r0 to r3, r12, lr, the return address and xPSR, in ascending address order, 32 bytes in all. It loads the handler address from the table, sets IPSR, and loads lr with a special value called EXC_RETURN, such as 0xFFFFFFF9 for "return to thread mode on the main stack". A handler returns by branching to that value with bx lr, and the core unstacks the frame and resumes. The set it stacks is exactly the one a C function may destroy, so an interrupt handler can be an ordinary C function with no attributes.
If the stack was only 4-byte aligned, the core pads to 8 when STKALIGN in CCR is set and records it in bit 9 of the stacked xPSR. If the FPU was in use, an extended frame with s0 to s15 and FPSCR follows the basic one, and with lazy stacking, the default, that space is reserved but filled only if the handler touches the FPU.
An assembly handler can read the frame to find where it was called from. The next one finds the program counter of the interrupted code, which is at offset 24:
.syntax unified
.thumb
.global SysTick_Handler
.type SysTick_Handler, %function
.thumb_func
SysTick_Handler:
tst lr, #4 // which stack did the interrupted code use?
ite eq
mrseq r0, msp
mrsne r0, psp
ldr r1, [r0, #24] // stacked pc
ldr r2, =last_pc
str r1, [r2]
bx lrA profiler built this way stores the interrupted address on every tick and has a statistical picture of where time goes.
Controlling interrupts, sleeping and ordering memory
cpsid i sets PRIMASK and masks every configurable exception, and cpsie i clears it. Used in pairs they make a critical section, but the pair must restore the previous state rather than force interrupts on, or nested sections break:
mrs r3, primask // remember whether interrupts were already off
cpsid i
// ... touch shared data, a few instructions only ...
msr primask, r3 // restore, do not force enableOn Armv7-M, BASEPRI masks only exceptions at or below a priority, which an RTOS uses to leave its most urgent interrupts alive. NMI and HardFault ignore PRIMASK.
wfi stops the core's clock until an enabled interrupt becomes pending, and wfe waits for the event register. A flag test followed by wfi has a race: if the interrupt arrives between the test and the sleep, the wake-up is lost. The fix is to test with interrupts masked, because a pending enabled interrupt still wakes wfi while PRIMASK is set, then unmask after waking. SCR.SLEEPDEEP asks for deep sleep, and SCR.SLEEPONEXIT makes the core go back to sleep after each handler.
Three barrier instructions control ordering. dmb orders memory accesses, dsb waits until they complete, and isb flushes the pipeline so later instructions see the new state. After writing VTOR, the MPU registers or a sleep control register, use dsb then isb. After writing CONTROL, use isb. Before starting DMA from a buffer you just filled, put a dmb between the buffer writes and the register write that starts the transfer. A simple Cortex-M3 may work without them, and a Cortex-M7 with a store buffer and caches will not, so write them whenever the architecture manual requires them.
System calls and task switching: SVC and PendSV
Two exceptions exist for software. svc #n raises SVCall synchronously, and its handler runs privileged, which is the Cortex-M system call. The handler picks the stack the caller used, reads the immediate from the byte before the stacked pc, takes arguments from the stacked r0 to r3, and returns results by writing the stacked r0. PendSV is the opposite kind: it runs only when no other handler is active, because it is set to the lowest priority, and is the place where an RTOS switches tasks.
A context switch saves what the hardware did not, then swaps stacks:
PendSV_Handler:
mrs r0, psp
ldr r3, =current_tcb
ldr r2, [r3]
stmdb r0!, {r4-r11} // save the software context
str r0, [r2] // current_tcb->sp = r0
push {r3, lr}
bl scheduler_next // picks the next task
pop {r3, lr}
ldr r2, [r3]
ldr r0, [r2]
ldmia r0!, {r4-r11} // restore the next task's context
msr psp, r0
bx lr // EXC_RETURN unstacks the restTwo tasks that yield alternate, task A then task B. The posts on SVC system calls and on writing the full PendSV handler build the data structures and the first-task start around this skeleton.
Atomics without masking: LDREX and STREX
Disabling interrupts for a one-word update is heavy. Armv7-M offers ldrex, which loads a word and marks the address in the local exclusive monitor, and strex, which stores only if the mark is still there and reports 0 for success and 1 for failure. An exception entry or return clears the mark, so an interrupt in the middle of the sequence just forces a retry:
.syntax unified
.cpu cortex-m4
.thumb
.text
.global atomic_inc
.type atomic_inc, %function
.thumb_func
// uint32_t atomic_inc(volatile uint32_t *p): returns the old value
atomic_inc:
1: ldrex r1, [r0]
adds r2, r1, #1
strex r3, r2, [r0]
cmp r3, #0
bne 1b
mov r0, r1
bx lr
.size atomic_inc, .-atomic_incFor a counter holding 41, the function returns 41 and leaves 42. The Cortex-M0 has no exclusive instructions, so there the section is masked. The monitor does not see DMA or other cores, so the pair protects against interrupts only unless the system provides a global monitor.
DSP and floating point
The M4 and M7 add the DSP extension. smlad Rd, Rn, Rm, Ra does two signed 16-bit multiplies and adds both products to Ra, so a loop that reads two samples per ldr does two multiply-accumulates per iteration. qadd adds with saturation, and ssat Rd, #n, Rm clamps to an n-bit signed range. A sticky Q flag in APSR bit 27 records any saturation, and you read it with mrs and clear it with msr apsr_nzcvq.
On a core with the FPU, there are thirty-two single-precision registers s0 to s31, loaded with vldr, operated on with vadd.f32, vmul.f32 and vfma.f32, and compared with vcmp.f32 followed by vmrs APSR_nzcv, fpscr to copy the flags into the integer flags. The FPU is off at reset. A program that uses it must set CPACR bits 23:20 first, and a missing enable shows up as a UsageFault with NOCP set. The posts on the DSP instructions, on using the FPU and on enabling it carry the details.
Finding faults: the stacked frame and the Thumb bit
A fault handler gets the interrupted state from the frame. Write the entry in assembly to pick the stack, pass the frame pointer to C, and read the program counter at offset 24, the link register at 20 and xPSR at 28. The CFSR register at 0xE000ED28 classifies the fault, with the usage fault bits in its top half and the bus and memory fault bits below.
The error you will meet first is INVSTATE, bit 17 of CFSR, with HFSR.FORCED set. It means the core tried to execute with the Thumb bit clear, so something branched to an even address. The causes are a hard-coded function address without the bit, address arithmetic that dropped it, or an assembly label that the assembler did not know was Thumb code. The stacked program counter is the bad target and the stacked lr points back to the caller. The fix is a | 1 on a raw address, a vector-table read in place of a constant, or a .thumb_func before the label. Enable USGFAULTENA in SHCSR so the same condition arrives as a usage fault whose name says what happened.
Other bits point elsewhere. NOCP (bit 19) is a coprocessor instruction with the FPU disabled. UNALIGNED (bit 24) is an unaligned multi-word access with trapping enabled, and DIVBYZERO (bit 25) is a divide by zero when CCR.DIV_0_TRP is set. IBUSERR and IACCVIOL say that the fetch itself failed, which needs an address-map check and not a Thumb bit.
A complete small program
The pieces fit into a program that counts SysTick interrupts and sleeps between them, with no C runtime: a vector table, a reset handler, a tick counter in RAM and a main loop.
.syntax unified
.cpu cortex-m3
.thumb
.section .isr_vector, "a", %progbits
.word _estack
.word Reset_Handler
.rept 13 // NMI .. PendSV placeholders point at Default_Handler
.word Default_Handler
.endr
.word SysTick_Handler // exception 15
.bss
.align 2
tick_count:
.space 4
.text
.thumb_func
Default_Handler:
b Default_Handler
.global Reset_Handler
.thumb_func
Reset_Handler:
ldr r0, =0xE000E014 // SYST_RVR: reload value
ldr r1, =0x000FFFFF
str r1, [r0]
ldr r0, =0xE000E010 // SYST_CSR
movs r1, #7 // ENABLE, TICKINT, CLKSOURCE
str r1, [r0]
1: wfi // sleep until the next tick
b 1b
.global SysTick_Handler
.thumb_func
SysTick_Handler:
ldr r0, =tick_count
ldr r1, [r0]
adds r1, r1, #1
str r1, [r0]
bx lr
.ltorgAfter the timer has fired three times, tick_count holds 3. The program uses no stack beyond what the exception frame needs, because the handler touches only r0 and r1, which the hardware saved. The tick_count variable lives in .bss, and RAM contents at power-up are not guaranteed, so a real program zeroes .bss in the reset handler before the first tick. The reload value, the position of Default_Handler in the table and the bit assignments in SYST_CSR (bit 0 ENABLE, bit 1 TICKINT, bit 2 CLKSOURCE) are from the Armv7-M Architecture Reference Manual's description of the SysTick registers.
A debugging workflow that uses all of this
Fault hunting on a Cortex-M follows the same route every time, and each step uses a section of this guide. Start with the evidence the core gives you: stop in the fault handler, and read CFSR, HFSR and, for bus and memory faults, BFAR or MMFAR. Then get the frame, which means the stacked pc, lr and xPSR from the stack the interrupted code was using. Pick the stack from bit 2 of EXC_RETURN in lr, because looking at the wrong one gives a plausible frame full of nonsense.
Next, locate the stacked pc in your build. arm-none-eabi-addr2line -f -e firmware.elf 0x08001234 prints the function and, with -g debug information, the line. If the stacked pc is even, you have the Thumb-bit problem and the target is the cause. If it points at a vldr or a vadd.f32, the FPU is off. If it points just after a ldm or stm, check alignment. If it is in a function that looks fine, read the registers named by the instruction and see which one holds a bad pointer; the stacked r0 to r3 and r12 are in the frame, and r4 to r11 are still in the registers because the handler has not touched them yet.
Finally, work backward from the bad value. The stacked lr names the caller, and the map file names the function around it. A function pointer in a table tells you to read the table's initial contents from the ELF with objdump -s -j .data, to see whether the value was wrong in the image or overwritten at run time. Both outcomes point to a different fix, and this three-step habit of evidence, frame and origin finds them without guessing. When timing is the suspect, switch tools: read DWT_CYCCNT before and after the code, and compare the count with the instruction timings in the core's technical reference manual.
The same workflow applies when there is no fault at all but the output is wrong. Put a breakpoint at the first instruction of the routine, check that the argument registers hold what the caller meant to pass, and step through the instructions watching the destination register of each. Because every Thumb instruction does one visible thing to one or two registers, the step where the register first holds a wrong value is the bug, or one instruction before it. With a listing open next to the debugger, the whole check takes minutes.
Where this guide does not fit
The guide assumes you are writing for a bare-metal or RTOS target in Thumb-2. A few readers need something else.
Cortex-A and Cortex-R in AArch32. Those cores run ARM state as well, where every instruction is conditional and pc is a general register. The register names and much of the mnemonics carry over, and the condition-suffix style, the ldm addressing modes and exception model do not. The Armv7-A manual is the reference.
AArch64 developers. The 64-bit instruction set is a different encoding with different registers: x0 to x30, no push and pop, a fixed 4-byte instruction size. The companion guide to AArch64 assembly covers it.
Teams that only read disassembly. If your goal is to understand a fault in compiled code, skip to the register, encoding and fault sections, and the post on reading Cortex-M disassembly with objdump. You do not need the exclusive-access or SVC material.
Security-critical code on Armv8-M. TrustZone adds the sg instruction, secure gateway veneers, bxns and register-clearing rules that this guide only mentions. Treat the Armv8-M manual and the Arm C Language Extensions for Armv8-M as the source for that work.
What to read next
Take the topics in this order if you are building up. Write the startup file for your own part from the vector-table section and compare it with the vendor's. Take one C function from your project, compile it with -O1, and read its disassembly line by line against the source. Write an RTOS context switch for two tasks and watch PSP alternate in the debugger. Then pick a routine that matters for timing and measure it with the cycle counter in the debug unit, DWT_CYCCNT at 0xE0001004, instead of guessing. Each of those exercises uses a section of this guide, and by the fourth you will have written more Cortex-M assembly than most of the people who need it.


