Skip to content

pack the socket header structs so AVR and 32-bit agree on the wire - #9

Merged
aphelps-claude-bot merged 2 commits into
mainfrom
pack-socket-headers
Jul 30, 2026
Merged

aphelps-claude-bot merged 2 commits into
mainfrom
pack-socket-headers

Conversation

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator

The bug

rs485_socket_hdr_t was declared without __attribute__((__packed__)). It mixes byte with 16-bit socket_addr_t, so sizeof() came out 7 bytes on AVR (alignment 1, nothing padded) and 8 on any 2-byte-aligned ABI, where the 7-byte layout rounds up to a trailing pad.

That size is what positions the payload at both ends of the link:

  • sendMsgTo() writes the header at (data - sizeof(hdr)) and puts sizeof(hdr) + datalength on the wire (RS485Utils.cpp:203-205)
  • getMsg() returns &msg->data[0], i.e. the byte after sizeof(hdr)

So an ESP32 emitted [7 header][1 pad][payload] while an ATMega328 module read the payload from offset 7 — the pad byte — as the HMTL start code and discarded the frame. In the other direction the ESP32 read from offset 8, skipping the real start code. Every frame between a 32-bit node and the deployed AVR fleet was misparsed by one byte, in both directions.

This is why the WLED rs485_bridge usermod — the first 32-bit participant on an HMTL bus — could not exchange a single frame with a real module. Its automated suite was green throughout, because every check ran on one ABI at a time: host tests are 64-bit, the firmware build is Xtensa, and the AVR side has no automated build. A size that is self-consistent on each target and wrong between them is invisible to that arrangement.

The fix

Pack, which makes the 32-bit layout match the AVR one. The deployed fleet defines the wire, so the ESP32 is what has to move — adding an explicit pad byte instead would mean reflashing every module.

Packing is layout-neutral on AVR (nothing there was padded to begin with), and the new static_asserts pin the size plus every field offset so that stays true. Field offsets already agreed across ABIs; only the trailing pad differed.

Packing also makes the three sites that cast a raw buffer straight to the struct (sendMsgTo, getMsg, headerFromData) unconditionally safe: at alignment 1 the compiler emits byte-wise accesses, where before the 16-bit source/address loads were correctly aligned only by accident of where the buffer landed.

Sibling transports

Same declaration pattern, so both get the same treatment — but they are not equivalent:

struct AVR unpacked 32-bit status
xbee_socket_hdr_t 5 6 prophylactic. Nothing builds XBeeSocket: HMTLTypes.cpp gates it on USE_XBEE and HMTL's module env hardcodes -DDISABLE_XBEE. The vendored XBee.h predates Arduino 1.0 (it includes WProgram.h) so it cannot compile against a current core at all.
rfm69_socket_hdr_t 6 8 not prophylactic, and worse. The padding is interior: source sits at offset 1 on AVR but 2 on 32-bit, so the addresses themselves move, not just the payload. And it ships — compiled into [env:moteino] and [env:nano_rfm69], both -DUSE_RFM69. The sizeof == 6 / source@1 assertions are the safety argument for that change, not a nicety: if packing had moved anything on AVR, two modules in the field would change on the wire.

The vendored RS485_non_blocking is deliberately untouched, so it stays byte-identical to Nick Gammon's upstream.

Verification

Real toolchains, not inference, on all three headers — 12 positive checks:

toolchain what it proves
avr-g++ 9.5 -mmcu=atmega328p packing is layout-neutral on AVR: 7 / 5 / 6, unchanged. If any size had moved, deployed modules would stop interoperating with each other — a worse failure than the one being fixed.
xtensa-esp32-elf-g++ the 32-bit side now matches. This is the fix.
host c++, native ABI cross-check
host c++ -fpack-struct=1 the AVR-like ABI on the host; the form that shows the two agreeing

Each is paired with a negative control that bumps the asserted size by one and confirms all three toolchains refuse to build. Without that control the non-AVR checks would pass vacuously: RS485UTILS_SUPPORTED (RS485Utils.h:46-57) preprocesses the entire struct — and therefore the assertions — away unless RS485_HARDWARE_SERIAL is defined, so a bare -fsyntax-only on this header compiles nothing and exits 0. A check that cannot fail is not a check.

Downstream, in the paired WLED PR: the bridge's host suite passes on both ABIs, pio run -e ampworks fails on its static_assert with the old constant and succeeds with the new one, and pio run -e usermods still builds.

Follow-ups this does not address

Two further defects in this library are tracked separately and deliberately out of scope here, to keep this diff a pure layout change: the receive path's stale-packet re-delivery / missing timeout / debug-gated length checks, and the ESP32 bridge's poll-path handling.

🤖 Generated with Claude Code

https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

rs485_socket_hdr_t was declared without __attribute__((__packed__)), which made
sizeof() 7 bytes on AVR (alignment 1) but 8 on any 2-byte-aligned ABI, where the
7-byte layout rounds up to a trailing pad. That size is what positions the payload
at both ends of the link: sendMsgTo() writes the header at (data - sizeof(hdr)) and
puts sizeof(hdr) + datalength on the wire, and getMsg() reads the payload from
msg->data.

So an ESP32 emitted [7 header][1 pad][payload] while an ATMega328 module read the
payload from offset 7 -- the pad byte -- and vice versa. Every frame between a
32-bit node and the deployed AVR fleet was misparsed by one byte, in both
directions. This is why the WLED rs485_bridge usermod, which is the first 32-bit
participant on an HMTL bus, could not exchange a single frame with a real module.

Fixed by packing, which makes the 32-bit layout match the AVR one -- the deployed
fleet defines the wire, so the ESP32 is what has to move. Packing is layout-neutral
on AVR (nothing there was padded to begin with) and the new static_asserts pin the
size plus every field offset so that stays true.

Field offsets already agreed across ABIs; only the trailing pad differed. Packing
also makes the three sites that cast a raw buffer straight to the struct
(sendMsgTo, getMsg, headerFromData) unconditionally safe: at alignment 1 the
compiler emits byte-wise accesses, where before the 16-bit source/address loads
were correctly aligned only by accident of where the buffer landed.

Same treatment for the two sibling transports, which share the declaration pattern:

  xbee_socket_hdr_t   5 B on AVR, 6 unpacked on 32-bit -- trailing pad only.
                      Prophylactic: nothing builds XBeeSocket today (HMTLTypes.cpp
                      gates it on USE_XBEE and HMTL's module env hardcodes
                      -DDISABLE_XBEE), and the vendored XBee.h predates Arduino 1.0
                      so it cannot compile against a current core at all.

  rfm69_socket_hdr_t  6 B on AVR, 8 unpacked on 32-bit, and the padding is INTERIOR:
                      source sits at offset 1 on AVR but 2 on 32-bit, so the
                      addresses themselves move, not just the payload. Not
                      prophylactic in the AVR direction -- this struct is compiled
                      into [env:moteino] and [env:nano_rfm69], both -DUSE_RFM69 --
                      which makes the sizeof == 6 / source@1 assertions the safety
                      argument for the change rather than a nicety.

The vendored RS485_non_blocking is deliberately untouched, so it stays
byte-identical to Nick Gammon's upstream.

Verified with the real toolchains rather than by inference, on all three headers:
avr-g++ 9.5 -mmcu=atmega328p, xtensa-esp32-elf-g++, and host c++ both natively and
under -fpack-struct=1 (the AVR-like ABI). Each of the twelve positive checks is
paired with a negative control that bumps the asserted size by one and confirms all
three toolchains refuse to build -- without that control the non-AVR checks would
pass vacuously, because RS485UTILS_SUPPORTED preprocesses the struct away unless
RS485_HARDWARE_SERIAL is defined.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
Self-review caught the previous wording claiming the packed-and-asserted guarantee
for "all three header structs" in a way that reads repo-wide, while a fourth wire
header used by the same HMTL module sits outside it. tcp_socket_hdr_t is packed
already but carries no assertions, and tcp_socket_msg_t is unpacked. No cross-ABI
hazard today -- TCPSocket is #if defined(ESP32)-only so it never meets an AVR peer,
and a packed header gives the outer struct alignment 1 regardless -- but the README
should not imply coverage it does not have.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
@aphelps-claude-bot
aphelps-claude-bot merged commit d047ce2 into main Jul 30, 2026
@aphelps-claude-bot
aphelps-claude-bot deleted the pack-socket-headers branch July 30, 2026 02:09
aphelps-claude-bot added a commit to aphelps/WLED_dev that referenced this pull request Jul 30, 2026
…rget) (#24)

* bump ArduinoLibs + WLED: pack the RS485 socket header (7B on every target)

Both pointers move in ONE commit deliberately. rs485_socket_hdr_t goes from an
unpacked struct (7 bytes on AVR, 8 on ESP32) to a packed 7 everywhere, and
RS485B_SOCKET_HDR_LEN follows it from 8 to 7. Any intermediate state with one side
advanced fails `pio run -e ampworks` at the static_assert in
usermod_rs485_bridge.cpp:19 -- which is the build the hardware bring-up depends on.

What this unblocks: until now the rs485_bridge usermod could not exchange a single
frame with a real HMTL module. sizeof(rs485_socket_hdr_t) positions the payload at
both ends, so the ESP32 emitted [7 header][1 pad][payload] while an ATMega328 read
the payload from offset 7, and vice versa -- every frame misparsed by one byte, in
both directions. The bench session for the bridge was blocked on this and nothing
else.

  aphelps/ArduinoLibs#9 -- pack rs485/xbee/rfm69 socket headers + static_assert sweep
  aphelps/WLED#14       -- RS485B_SOCKET_HDR_LEN 8 -> 7, host-test coverage, readme

Submodule PRs merge first; this pointer pair is re-pointed at the merged shas before
this PR lands.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* bump submodules: self-review fixes on the socket-header stack

ArduinoLibs f4afaab -- README scopes the packing guarantee and names TCPSocket as
not covered.
WLED 40d4ecdf -- the new host-test assert was tautological (7 == 7, green even with
the packing attribute removed); replaced with a packed replica plus offsetof checks
that actually fail, and the three comments that overclaimed cross-ABI coverage now
say what the check can and cannot see. Also documents a pre-existing sizing bug the
review surfaced: a full 64-byte TX slot goes on the wire as 71 bytes and overflows a
default 64-byte receive buffer, so the real payload ceiling is 57. Filed separately
rather than fixed here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* re-point submodules at the merged socket-header packing commits

ArduinoLibs d047ce2 (#9) -- pack rs485/xbee/rfm69 socket headers + assertion sweep
WLED 3c11ec16 (#14)     -- RS485B_SOCKET_HDR_LEN 8 -> 7, host-test coverage, readme

Both squash-merged, so this replaces the branch-tip pointers this PR opened with.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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.

1 participant