Cortex-M Unaligned Access Faults: Why a Cast Packed-Struct Parser Crashes on LDRD, and How to Fix It

2026-12-04 · Davide Carrese
Cortex-M · Firmware Debugging · HardFault · STM32 · Cortex-M4 · Cortex-M7

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

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:

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

⚠ Do not "fix" it by clearing a trap or by luck

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

Practical checklist

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

💬 Comments by email

Reply to this article by email — I read and respond to every message.