From ae4ff36c635ef0330ca4b7ea7426f438bad7e8d1 Mon Sep 17 00:00:00 2001 From: Archit Gupta Date: Fri, 10 Sep 2021 19:29:16 -0700 Subject: [PATCH] Fix prvWriteMessageToBuffer on big endian 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. --- stream_buffer.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/stream_buffer.c b/stream_buffer.c index 8a7a2e0d073..a0a151b692f 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 {