https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124748

--- Comment #11 from Adam Panchártek <adam.panchartek at gmail dot com> ---
We have tested the behavior of GCC 13.3.0 (arm-none-eabi) on ARM Cortex-M4 with
respect to unaligned memory access in packed structures.
We can confirm that the compiler is working as described.

Direct member access in packed structures:
When accessing members of a __attribute__((packed)) structure directly, GCC
always generates byte-by-byte access regardless of the member type and
regardless of whether -munaligned-access or -mno-unaligned-access is specified:

double → 8× STRB/LDRB
uint32_t → 4× STRB/LDRB
uint16_t → 2× STRB/LDRB
uint8_t → 1× STRB/LDRB

This is technically correct — no hard fault occurs even on cores that do not
support unaligned access (e.g. Cortex-M0). However, it is not optimal in terms
of code size and performance, since cores like Cortex-M3 and M4 are capable of
handling unaligned 16- and 32-bit accesses natively.

Member access via memcpy:
When members are accessed through memcpy wrapped in inline helper functions,
GCC generates significantly more efficient code:

double → 2× STR (unaligned)
uint32_t → 1× STR (unaligned)
uint16_t → 1× STRH (unaligned)
uint8_t → 1× STRB

Example implementation:
typedef struct {
    uint8_t  my_u8;
    uint16_t my_u16;
    uint32_t my_u32;
    double   my_double;
} __attribute__((packed)) MyPackedStru;

static inline void record_set_u16(MyPackedStru *r, uint16_t val)
{
    memcpy(&r->my_u16, &val, sizeof(val));
}

static inline void record_set_u32(MyPackedStru *r, uint32_t val)
{
    memcpy(&r->my_u32, &val, sizeof(val));
}

static inline void record_set_double(MyPackedStru *r, double val)
{
    memcpy(&r->my_double, &val, sizeof(val));
}

  /* Packed - direct */
  packed.my_u8 = 0x12;
  packed.my_u16 = 0x1234;
  packed.my_u32 = 0x12345678;
  packed.my_double = 1.0;

  /* Packed + memcpy */
  record_set_u16(&packed, 0x1234);
  record_set_u32(&packed, 0x12345678);
  record_set_double(&packed, 1.0);

Conclusion
The memcpy-based access pattern is the correct and portable solution for
working with packed structures on ARM Cortex-M. It eliminates the risk of hard
faults while producing near-optimal code, without requiring any non-standard
compiler extensions such as the proposed -munaligned-double-access.

We would like to thank everyone involved in this discussion for their time and
valuable guidance.

Reply via email to