From d649a771282b2d23c3ab212cede3ad32d841747d Mon Sep 17 00:00:00 2001 From: Archit Gupta <71798289+archigup@users.noreply.github.com> Date: Sat, 16 Oct 2021 16:36:44 -0700 Subject: [PATCH] Fix prvWriteMessageToBuffer on big endian (#391) prvWriteMessageToBuffer wrote the first sbBYTES_TO_STORE_MESSAGE_LENGTH bytes of the size_t-typed length to the buffer as the data length. While this functions on little endian, it copies the wrong bytes on big endian. This fix converts the length to configMESSAGE_BUFFER_LENGTH_TYPE first, and then copies the exact amount, thus fixing the issue. Additionally it adds an assert to verify the size is not greater than the max value of configMESSAGE_BUFFER_LENGTH_TYPE; previously this would truncate silently. Co-authored-by: Gaurav-Aggarwal-AWS <33462878+aggarg@users.noreply.github.com> --- stream_buffer.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/stream_buffer.c b/stream_buffer.c index 8a7a2e0d0..a0a151b69 100644 --- a/stream_buffer.c +++ b/stream_buffer.c @@ -728,17 +728,24 @@ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, size_t xRequiredSpace ) { size_t xNextHead = pxStreamBuffer->xHead; + configMESSAGE_BUFFER_LENGTH_TYPE xMessageLength; if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { /* This is a message buffer, as opposed to a stream buffer. */ + /* Convert xDataLengthBytes to the message length type. */ + xMessageLength = ( configMESSAGE_BUFFER_LENGTH_TYPE ) xDataLengthBytes; + + /* Ensure the data length given fits within configMESSAGE_BUFFER_LENGTH_TYPE. */ + configASSERT( ( size_t ) xMessageLength == xDataLengthBytes ); + if( xSpace >= xRequiredSpace ) { /* 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 * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead ); + xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xMessageLength ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead ); } else {