Cortex-M Unaligned Access Faults: Why a Cast Packed-Struct Parser Crashes on LDRD, and How to Fix It
A parser reads a 32-bit field out of a receive buffer with *(uint32_t *)&buf[3]. On your Cortex-M4 it works for months. Then a compiler update, a new optimisation level, a uint64_t field or a move to a Cortex-M0+ turns it into a UsageFault or HardFault with UNALIGNED set, at an address you "know" is fine. This article explains which instructions the core accepts at odd addresses and which it never does, why the same C code can be both, how to confirm the cause in the fault registers, and how to read wire data in a way that does not depend on any of it.
The symptom
- A fault (UsageFault if enabled, otherwise a HardFault with
HFSR.FORCEDset) that appears or disappears when you change optimisation level, toolchain version or an unrelated struct layout. - The faulting instruction is a load or store of a 64-bit value or of several registers:
ldrd,strd,ldm,stm, and on parts with an FPU alsovldr/vstr/vldm/vstm. A plainldrfrom the same address would have worked. - The same source works on a Cortex-M4 and faults on a Cortex-M0/M0+ (where every unaligned access faults), or works with MPU disabled and faults after you enable the MPU.
- The failing address is odd or
2 mod 4, typically a pointer into the middle of a byte buffer: a frame payload after a 1-, 2- or 3-byte header, a field inside a flash-stored record, or a member of a__attribute__((packed))struct that was passed around as a plain pointer.
Root cause: "unaligned access is supported" is a per-instruction statement
On ARMv7-M cores (Cortex-M3, M4, M7) and ARMv8-M Mainline (M33), the architecture allows a short list of single-register loads and stores to use any address: LDR, LDRH, LDRSH, STR, STRH and the unprivileged variants. The hardware splits such an access into several aligned bus transfers, so it takes more cycles and is not atomic. Everything else that moves more than one register, or needs exclusive access, requires natural alignment: LDM, STM, LDRD, STRD, LDREX/STREX, and the FPU's VLDR, VSTR, VLDM, VSTM. The Arm Community thread quoting the Cortex-M3 TRM puts it plainly: "Unaligned LDM/STM/LDRD/STRD instructions always fault irrespective of the setting of UNALIGN_TRP." The exact list for your core is in the ARMv7-M Architecture Reference Manual (DDI0403, section A3.2 "Alignment support") and in the Cortex-M4 Devices Generic User Guide (DUI0553, "Unaligned accesses").
Two more rules complete the picture:
CCR.UNALIGN_TRP(bit 3 of the Configuration and Control Register,SCB->CCR, 0xE000ED14) turns every unaligned access, including the otherwise-legalLDR/STR, into a UsageFault. It is off at reset. It affects only the accesses that would otherwise succeed; the multi-register instructions fault regardless.- Memory type matters. The ARMv7-M architecture also faults unaligned accesses to Device and Strongly-ordered memory, whatever the instruction. The default memory map treats the peripheral region as Device, and an MPU region you configure as Device or Strongly-ordered has the same effect. That is why "it worked until I turned on the MPU" is a real failure mode: the ST Community has a thread titled "HardFault on unaligned access after enabling MPU". Check the attributes you programmed in the MPU (see my MPU article for the attribute encodings).
- Cortex-M0, M0+ (ARMv6-M) and M23: all unaligned accesses fault, and since these cores have no UsageFault, you get a HardFault.
So whether your code faults depends on which instruction the compiler picks. That is where the C language comes in.
Why the compiler picks LDRD for a cast pointer
Casting a uint8_t * to uint64_t * and dereferencing it is undefined behaviour if the address is not suitably aligned. The compiler is therefore allowed to assume the address is aligned, and on a target with LDRD it may use it. For a uint32_t cast it normally emits ldr, which tolerates misalignment, so the bug stays hidden. But it can also merge two adjacent 32-bit loads into one ldrd or ldm, or inline a struct copy as ldm/stm. Which one you get depends on the GCC version, the optimisation level and the surrounding code, so nothing in the source changes when it starts failing.
The GCC documentation for -munaligned-access states the other half: unaligned access is enabled by default for all architectures except pre-ARMv6, ARMv6-M and ARMv8-M Baseline, and "if unaligned access is not enabled then words in packed data structures are accessed a byte at a time." So with the default flags on a Cortex-M4, direct member access to a packed struct compiles to plain ldr/str (legal for odd addresses), and the same code built for a Cortex-M0+ compiles to byte accesses. Neither faults. The trouble starts when the compiler loses the "packed" information: you take a pointer to a packed member, pass it as uint32_t *, and the callee assumes alignment. GCC 9 and later warn about this with -Waddress-of-packed-member, which is on by default.
Reproduce and confirm
A minimal reproduction for a Cortex-M4 target (-mcpu=cortex-m4 -mthumb -O2):
#include <stdint.h>
/* Undefined behaviour if p is not 8-byte aligned. */
uint64_t read_u64_cast(const uint8_t *p)
{
return *(const uint64_t *)p;
}
Disassemble it (arm-none-eabi-objdump -d). Because the compiler may assume 8-byte alignment, it is allowed to emit a single ldrd (or ldm) here, which faults when p is odd. Whether it does depends on your GCC version and flags, so check the output on your toolchain. Calling it with &buf[1] from a 4-byte-aligned buf triggers the fault.
To confirm from a captured fault, read the Configurable Fault Status Register. The UsageFault Status Register is its top halfword; UFSR.UNALIGNED is bit 8 of the UFSR, i.e. bit 24 of SCB->CFSR. The stacked PC points at the faulting instruction (UsageFaults of this kind are precise), so arm-none-eabi-addr2line plus a disassembly gives you the line, and the register that holds the odd address is visible in the stacked frame or in the debugger.
#include "stm32f4xx.h" /* any CMSIS device header; core_cm4.h provides SCB */
#include <stdint.h>
#define CFSR_UNALIGNED (1UL << 24) /* UFSR.UNALIGNED = CFSR bit 24 */
void fault_report(const uint32_t *frame) /* frame = stacked r0-r3,r12,lr,pc,xpsr */
{
uint32_t cfsr = SCB->CFSR;
uint32_t pc = frame[6];
if (cfsr & CFSR_UNALIGNED) {
/* store pc and cfsr to a no-init RAM block or log, then reset */
}
(void)pc;
}
Call it from the HardFault/UsageFault entry stub that selects MSP or PSP; I describe a complete decoder in the Cortex-M fault decoder article and the register walk-through in STM32 HardFault debugging. Remember that UsageFaults are disabled until you set SCB_SHCSR_USGFAULTENA_Msk in SCB->SHCSR; otherwise the fault escalates to HardFault and HFSR.FORCED (bit 30) is set. The CFSR still holds the UsageFault bit.
The fix
1. Read wire data as bytes or with memcpy
The portable, standards-compliant way is to copy into an aligned object. With a constant size, GCC turns memcpy into the best sequence the target allows given that the source has alignment 1:
#include <stdint.h>
#include <string.h>
static inline uint32_t load_u32(const void *p)
{
uint32_t v;
memcpy(&v, p, sizeof v); /* host byte order */
return v;
}
If the protocol has a fixed endianness (most do), write the accessor by bytes. It is independent of core, compiler and memory type, and it fixes endianness at the same time:
static inline uint32_t load_le32(const uint8_t *p)
{
return (uint32_t)p[0]
| ((uint32_t)p[1] << 8)
| ((uint32_t)p[2] << 16)
| ((uint32_t)p[3] << 24);
}
GCC recognises this pattern and, where unaligned access is enabled, folds it to a single ldr; where it is not, it stays as byte loads. Check the disassembly once if code size or speed matters. For 64-bit variants, check on your toolchain that no ldrd/ldm comes out; this is compiler behaviour, not an architectural guarantee.
2. Access packed structs only through the struct
If you map a __attribute__((packed)) struct onto the buffer, access members directly (hdr->length), never through a pointer to the member. Treat -Waddress-of-packed-member as an error (-Werror=address-of-packed-member). Whole-struct copies are better done with memcpy into an aligned local.
3. Make the layout aligned in the first place
Declare receive buffers with __attribute__((aligned(4))) (or 8 for 64-bit data), and where you control the format, pad headers so payload fields land on their natural boundary. This also helps DMA and cache-line handling. It does not help when a frame carries a variable-length header, which is why the accessors above are the general answer.
4. Compiler flags: safety net, not a fix
-Wcast-align=strictwarns about casts that increase alignment even on targets where GCC would otherwise stay quiet because unaligned access is "allowed". It is noisy but finds the exact lines.-mno-unaligned-accessforces byte-wise access to packed members on a Cortex-M4/M7. It makes packed-struct code behave as it would on a Cortex-M0+, at a cost in size and speed. It does not rescue a cast pointer, because the compiler still assumes that pointer is aligned.
On a Cortex-M4/M7 the only switch is UNALIGN_TRP, and it makes things stricter, not looser. There is no bit that makes LDRD or LDM accept an unaligned address. If a build "works" after an unrelated change, the compiler has merely stopped emitting the multi-register instruction at that spot.
Verify and guard against regression
- Turn on
UNALIGN_TRPin debug and test builds:SCB->CCR |= SCB_CCR_UNALIGN_TRP_Msk;together withSCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk;. Every unaligned access, including the ones that would silently work and silently cost cycles, becomes a UsageFault you can locate. Expect some hits in third-party code; each one is a latent bug on a different core or compiler. - Run the parser on the host with UBSan: build the protocol code with
-fsanitize=alignment(GCC and Clang) and feed it captured frames at every offset 0–7 within the buffer. Misaligned dereferences are reported with file and line. This is the cheapest regression test I know, and it needs no hardware. - Test offsets, not just content: a unit test that places each message at
buf + 1,+2,+3catches what a test with an aligned array never will. - Keep the fault capture: log CFSR and stacked PC to a no-init RAM block so a field fault arrives with
UNALIGNEDalready identified.
Practical checklist
- Fault at an odd or
2 mod 4address? Check CFSR bit 24 and the instruction at the stacked PC. - Is it
ldrd/strd/ldm/stm/vldr? These never accept unaligned addresses on any Cortex-M. - Is the memory Device/Strongly-ordered (peripherals, MPU region)? Then even
LDRfaults. - Is the core ARMv6-M (M0/M0+/M23)? Every unaligned access faults and you get a HardFault.
- Replace pointer casts on buffers with
memcpyor explicit byte accessors; fix endianness at the same point. - Never take the address of a packed member; enable
-Werror=address-of-packed-member. - Add
-Wcast-align=strictin a CI job,-fsanitize=alignmentin host tests, andUNALIGN_TRPin debug firmware.
How I would approach this on a client project
I would not start by hunting the one failing line. I would put every access to externally-formatted data (UART frames, CAN payloads, flash records, OTA headers) behind a small set of accessors like the ones above, and make that the only place that touches raw bytes. Then I would enable UNALIGN_TRP in the development build for a week of normal testing, because it shows every unaligned access the code makes today, not only the one that crashed. If the product may move to a Cortex-M0+ part later, or to a newer GCC, the accessors make that move a non-event. Finally, I would add the host-side offset test to CI so the bug cannot come back with the next protocol field.
Sources
- Arm, ARMv7-M Architecture Reference Manual (DDI0403), A3.2 "Alignment support" and the System Control Block register descriptions (CCR, CFSR/UFSR, HFSR).
- Arm, Cortex-M4 Devices Generic User Guide (DUI0553), "Memory model → Unaligned accesses" and "Configuration and Control Register". developer.arm.com/documentation/dui0553
- Arm Community, Debugging a UsageFault for an unaligned memory access (quotes the Cortex-M3 TRM on LDM/STM/LDRD/STRD).
- GCC manual, ARM Options: -munaligned-access / -mno-unaligned-access.
- ST Community, HardFault on unaligned access after enabling MPU.
Reply to this article by email — I read and respond to every message.