Skip to content

Conversation

@Bwooce
Copy link

@Bwooce Bwooce commented Sep 1, 2025

Summary

This PR fixes buffer alignment issues that cause MAVLink message corruption on ESP32 (Xtensa) and ARM platforms.

Problem

ESP32 and ARM processors require proper memory alignment when accessing multi-byte values (float, int32, etc.) through char buffers. Without proper alignment, these platforms can experience:

  • Data corruption when reading/writing values
  • Stack corruption leading to incorrect message lengths
  • ATTITUDE messages reporting 385 bytes instead of 28 bytes

Solution

  • Added MAVLINK_ALIGNED_BUF macro that uses alignas(4) for ESP32/ARM platforms
  • Updated code generator to use MAVLINK_ALIGNED_BUF instead of plain char[] arrays
  • Included stdalign.h when alignment is needed

Changes

  1. generator/C/include_v2.0/protocol.h: Added MAVLINK_ALIGNED_BUF macro definition
  2. generator/mavgen_c.py: Updated all buffer declarations to use the new macro

Testing

  • Tested on ESP32-S3 hardware where the issue was originally observed
  • Verified MAVLink messages are now correctly sized and uncorrupted
  • No impact on other platforms (macro defaults to plain char[] on non-ARM/ESP32)

Related Issues

This resolves MAVLink corruption issues observed in ArduPilot on ESP32 platforms.

Add MAVLINK_ALIGNED_BUF macro to ensure proper memory alignment for
buffer accesses on platforms that require it. ESP32 (Xtensa) and ARM
processors can experience data corruption when accessing unaligned
float/int values through char buffers.

The fix:
- Adds MAVLINK_ALIGNED_BUF macro that uses alignas(4) for ESP32/ARM
- Updates code generator to use MAVLINK_ALIGNED_BUF instead of plain char[]
- Includes stdalign.h when alignment is needed

This resolves MAVLink message corruption issues observed on ESP32 where
messages like ATTITUDE would have incorrect lengths (385 bytes instead
of 28) due to unaligned memory access causing stack corruption.
@tridge
Copy link
Contributor

tridge commented Sep 1, 2025

@Bwooce thanks for raising this - what is surprising is arm (specifically STM32) is the most widely used platform that MAVLink is used on. So why are we not seeing issues in current usage?
I think that for MAVLINK_NEED_BYTE_SWAP or !MAVLINK_ALIGNED_FIELDS it should be mapping the _mav_put_XXX() functions onto byte_copy_YY() which maps to a function that copies byte by byte.
We could use what you've done and then potentially make things a bit more efficient by avoiding the byte by byte copies

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants