Skip to content

Commit

Permalink
SerialCommHub: fix reading beyond end of buffer
Browse files Browse the repository at this point in the history
When converting a reply with an odd number of bytes of data ("read coils" or
"read discrete inputs"), the byte-to-word conversion was reading beyond the
end of the response message buffer.

This is fixed by checking for the number of remaining bytes, and copying
only what is left.

Signed-off-by: Moritz Barsnick <[email protected]>
  • Loading branch information
barsnick committed Jul 5, 2024
1 parent 0056f6b commit f831bc1
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions modules/SerialCommHub/tiny_modbus_rtu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,9 @@ static std::vector<uint16_t> decode_reply(const uint8_t* buf, int len, uint8_t e
result.reserve((byte_cnt + 1) / 2);

for (int i = start_of_result; i < start_of_result + byte_cnt; i += 2) {
uint16_t t;
memcpy(&t, buf + i, 2);
uint16_t t = 0;
const size_t num_bytes_to_copy = (i < len - 1) ? 2 : 1;
memcpy(&t, buf + i, num_bytes_to_copy);
t = be16toh(t);
result.push_back(t);
}
Expand Down

0 comments on commit f831bc1

Please sign in to comment.