From e2b6581cf39367d089449ac93d83234170564a91 Mon Sep 17 00:00:00 2001 From: AniruddhaKanhere <60444055+AniruddhaKanhere@users.noreply.github.com> Date: Tue, 7 Jul 2026 21:46:35 -0700 Subject: [PATCH] stream_buffer: reject message length truncation at runtime in writer Defect: prvWriteMessageToBuffer() can write a truncated message-length header into a message buffer when the data length does not fit the configured configMESSAGE_BUFFER_LENGTH_TYPE and configASSERT() is compiled out, desynchronizing framing at the receiver. Root cause: the writer stores the length as a configMESSAGE_BUFFER_LENGTH_TYPE value xMessageLength and only guards the "fits without truncation" condition with configASSERT( ( size_t ) xMessageLength == xDataLengthBytes ). The subsequent write was gated solely on available space, so with asserts disabled a length that overflows the length type is written truncated while the full data is copied, corrupting the message framing seen by the receiver. Fix: gate the length-plus-data write on ( ( size_t ) xMessageLength == xDataLengthBytes ) in addition to the space check. When the length cannot be represented without truncation, take the "not enough space" path and write nothing. This runtime check is the only guard against truncation when asserts are disabled. A host regression test kept outside this repository demonstrates the fault before the change and its absence afterwards (red then green). --- stream_buffer.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/stream_buffer.c b/stream_buffer.c index 0e7478a7e..087838c5e 100644 --- a/stream_buffer.c +++ b/stream_buffer.c @@ -1065,16 +1065,21 @@ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, /* Ensure the data length given fits within configMESSAGE_BUFFER_LENGTH_TYPE. */ configASSERT( ( size_t ) xMessageLength == xDataLengthBytes ); - if( xSpace >= xRequiredSpace ) + if( ( ( size_t ) xMessageLength == xDataLengthBytes ) && ( xSpace >= xRequiredSpace ) ) { - /* There is enough space to write both the message length and the message + /* The message length fits within configMESSAGE_BUFFER_LENGTH_TYPE and + * there is enough space to write both the message length and the message * itself into the buffer. Start by writing the length of the data, the data * itself will be written later in this function. */ xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xMessageLength ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead ); } else { - /* Not enough space, so do not write data to the buffer. */ + /* Either there is not enough space, or the message length cannot be + * represented by configMESSAGE_BUFFER_LENGTH_TYPE without truncation. + * Writing a truncated length header would corrupt the message + * framing at the receiver, so do not write any data to the buffer. When asserts are + * disabled this runtime check is the only guard against truncation. */ xDataLengthBytes = 0; } }