From b8fa50b5b71e3496fb7dc0ef311a9f02589b5b27 Mon Sep 17 00:00:00 2001 From: Pradip De Date: Sat, 10 Feb 2024 23:35:22 -0800 Subject: [PATCH] Adjust storage and processing in SystemPacketBuffer and associated code for large payloads. Extend uint16_t type variables to size_t for the APIs and all applicable places. --- src/app/BufferedReadCallback.cpp | 2 +- src/app/server/EchoHandler.cpp | 3 +- src/ble/BtpEngine.cpp | 10 +- src/inet/TCPEndPoint.cpp | 8 +- src/inet/TCPEndPoint.h | 8 +- src/inet/TCPEndPointImplLwIP.cpp | 10 +- src/inet/TCPEndPointImplLwIP.h | 2 +- src/inet/TCPEndPointImplOpenThread.cpp | 2 +- src/inet/TCPEndPointImplOpenThread.h | 2 +- src/inet/TCPEndPointImplSockets.cpp | 10 +- src/inet/TCPEndPointImplSockets.h | 4 +- src/inet/UDPEndPointImplLwIP.cpp | 2 +- src/inet/UDPEndPointImplOpenThread.cpp | 2 +- src/inet/UDPEndPointImplSockets.cpp | 7 +- src/inet/tests/TestInetLayer.cpp | 2 +- src/inet/tests/TestInetLayerCommon.cpp | 46 ++++---- src/lib/core/tests/TestTLV.cpp | 6 +- src/messaging/tests/echo/echo_requester.cpp | 3 +- src/messaging/tests/echo/echo_responder.cpp | 2 +- src/platform/ESP32/nimble/BLEManagerImpl.cpp | 2 +- src/platform/Zephyr/BLEManagerImpl.cpp | 4 +- src/platform/android/BLEManagerImpl.cpp | 3 +- .../bouffalolab/common/BLEManagerImpl.cpp | 4 +- src/platform/mbed/BLEManagerImpl.cpp | 2 +- src/protocols/secure_channel/CASESession.cpp | 2 +- .../UserDirectedCommissioningClient.cpp | 2 +- .../UserDirectedCommissioningServer.cpp | 2 +- src/system/SystemPacketBuffer.cpp | 104 ++++++++++++------ src/system/SystemPacketBuffer.h | 42 +++---- src/system/TLVPacketBufferBackingStore.cpp | 12 +- src/system/tests/TestSystemPacketBuffer.cpp | 101 +++++++++-------- src/transport/SecureMessageCodec.cpp | 10 +- src/transport/SessionManager.cpp | 2 +- src/transport/raw/MessageHeader.cpp | 16 +-- src/transport/raw/MessageHeader.h | 20 ++-- 35 files changed, 260 insertions(+), 199 deletions(-) diff --git a/src/app/BufferedReadCallback.cpp b/src/app/BufferedReadCallback.cpp index da38d0b38418bb..3752a3e65aef08 100644 --- a/src/app/BufferedReadCallback.cpp +++ b/src/app/BufferedReadCallback.cpp @@ -65,7 +65,7 @@ CHIP_ERROR BufferedReadCallback::GenerateListTLV(TLV::ScopedBufferTLVReader & aR // // To avoid that, a single contiguous buffer is the best likely approach for now. // - uint32_t totalBufSize = 0; + size_t totalBufSize = 0; for (const auto & packetBuffer : mBufferedList) { totalBufSize += packetBuffer->TotalLength(); diff --git a/src/app/server/EchoHandler.cpp b/src/app/server/EchoHandler.cpp index 2f9323426943b6..975b1c60a94d36 100644 --- a/src/app/server/EchoHandler.cpp +++ b/src/app/server/EchoHandler.cpp @@ -40,7 +40,8 @@ chip::Protocols::Echo::EchoServer gEchoServer; */ void HandleEchoRequestReceived(chip::Messaging::ExchangeContext * ec, chip::System::PacketBufferHandle && payload) { - ChipLogProgress(AppServer, "Echo Request, len=%u ... sending response.\n", payload->DataLength()); + ChipLogProgress(AppServer, "Echo Request, len=%" PRIu32 "... sending response.\n", + static_cast(payload->DataLength())); } } // namespace diff --git a/src/ble/BtpEngine.cpp b/src/ble/BtpEngine.cpp index 3183c6db79aed1..7925538ddd6230 100644 --- a/src/ble/BtpEngine.cpp +++ b/src/ble/BtpEngine.cpp @@ -310,7 +310,7 @@ CHIP_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle && // mRxFragnentSize may be smaller than the characteristic size. Make sure // we're not truncating to a data length smaller than what we have already consumed. VerifyOrExit(reader.OctetsRead() <= mRxFragmentSize, err = BLE_ERROR_REASSEMBLER_INCORRECT_STATE); - data->SetDataLength(chip::min(data->DataLength(), mRxFragmentSize)); + data->SetDataLength(chip::min(data->DataLength(), static_cast(mRxFragmentSize))); // Now mark the bytes we consumed as consumed. data->ConsumeHead(static_cast(reader.OctetsRead())); @@ -374,11 +374,11 @@ CHIP_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle && if (rx_flags.Has(HeaderFlags::kEndMessage)) { // Trim remainder, if any, of the received packet buffer based on sender-specified length of reassembled message. - int padding = mRxBuf->DataLength() - mRxLength; + int padding = static_cast(mRxBuf->DataLength()) - mRxLength; if (padding > 0) { - mRxBuf->SetDataLength(mRxLength); + mRxBuf->SetDataLength(static_cast(mRxLength)); } // Ensure all received fragments add up to sender-specified total message size. @@ -403,7 +403,7 @@ CHIP_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle && } if (!mRxBuf.IsNull()) { - ChipLogError(Ble, "With rx buf data length = %u", mRxBuf->DataLength()); + ChipLogError(Ble, "With rx buf data length = %u", static_cast(mRxBuf->DataLength())); } LogState(); @@ -456,7 +456,7 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s mTxBuf = std::move(data); mTxState = kState_InProgress; - mTxLength = mTxBuf->DataLength(); + mTxLength = static_cast(mTxBuf->DataLength()); ChipLogDebugBtpEngine(Ble, ">>> CHIPoBle preparing to send whole message:"); PrintBufDebug(mTxBuf); diff --git a/src/inet/TCPEndPoint.cpp b/src/inet/TCPEndPoint.cpp index 15b14151a235ce..7fed0b0c26a1ec 100644 --- a/src/inet/TCPEndPoint.cpp +++ b/src/inet/TCPEndPoint.cpp @@ -126,7 +126,7 @@ CHIP_ERROR TCPEndPoint::SetReceivedDataForTesting(System::PacketBufferHandle && return CHIP_NO_ERROR; } -uint32_t TCPEndPoint::PendingSendLength() +size_t TCPEndPoint::PendingSendLength() { if (!mSendQueue.IsNull()) { @@ -135,7 +135,7 @@ uint32_t TCPEndPoint::PendingSendLength() return 0; } -uint32_t TCPEndPoint::PendingReceiveLength() +size_t TCPEndPoint::PendingReceiveLength() { if (!mRcvQueue.IsNull()) { @@ -333,8 +333,8 @@ void TCPEndPoint::DriveReceiving() { // Acknowledgement is done after handling the buffers to allow the // application processing to throttle flow. - uint16_t ackLength = mRcvQueue->TotalLength(); - CHIP_ERROR err = OnDataReceived(this, std::move(mRcvQueue)); + size_t ackLength = mRcvQueue->TotalLength(); + CHIP_ERROR err = OnDataReceived(this, std::move(mRcvQueue)); if (err != CHIP_NO_ERROR) { DoClose(err, false); diff --git a/src/inet/TCPEndPoint.h b/src/inet/TCPEndPoint.h index 0e4c17b12d5876..0c00e327cc3d71 100644 --- a/src/inet/TCPEndPoint.h +++ b/src/inet/TCPEndPoint.h @@ -274,7 +274,7 @@ class DLL_EXPORT TCPEndPoint : public EndPointBasis * received. The operational semantics are undefined if \c len is larger * than the total outstanding unacknowledged received data. */ - virtual CHIP_ERROR AckReceive(uint16_t len) = 0; + virtual CHIP_ERROR AckReceive(size_t len) = 0; /** * @brief Set the receive queue, for testing. @@ -295,7 +295,7 @@ class DLL_EXPORT TCPEndPoint : public EndPointBasis * * @return Number of untransmitted bytes in the transmit queue. */ - uint32_t PendingSendLength(); + size_t PendingSendLength(); /** * @brief Extract the length of the unacknowledged receive data. @@ -303,7 +303,7 @@ class DLL_EXPORT TCPEndPoint : public EndPointBasis * @return Number of bytes in the receive queue that have not yet been * acknowledged with AckReceive(uint16_t len). */ - uint32_t PendingReceiveLength(); + size_t PendingReceiveLength(); /** * @brief Initiate TCP half close, in other words, finished with sending. @@ -447,7 +447,7 @@ class DLL_EXPORT TCPEndPoint : public EndPointBasis * is the length of the message text added to the TCP transmit window, * which are eligible for sending by the underlying network stack. */ - typedef void (*OnDataSentFunct)(TCPEndPoint * endPoint, uint16_t len); + typedef void (*OnDataSentFunct)(TCPEndPoint * endPoint, size_t len); /** * The endpoint's message text transmission event handling function diff --git a/src/inet/TCPEndPointImplLwIP.cpp b/src/inet/TCPEndPointImplLwIP.cpp index 02e5ac97b46d16..236d26974c67e3 100644 --- a/src/inet/TCPEndPointImplLwIP.cpp +++ b/src/inet/TCPEndPointImplLwIP.cpp @@ -351,7 +351,7 @@ CHIP_ERROR TCPEndPointImplLwIP::DriveSendingImpl() { VerifyOrDie(!startOfUnsent.buffer.IsNull()); - uint16_t bufDataLen = startOfUnsent.buffer->DataLength(); + uint16_t bufDataLen = static_cast(startOfUnsent.buffer->DataLength()); // Get a pointer to the start of unsent data within the first buffer on the unsent queue. const uint8_t * sendData = startOfUnsent.buffer->Start() + startOfUnsent.offset; @@ -503,16 +503,18 @@ void TCPEndPointImplLwIP::DoCloseImpl(CHIP_ERROR err, State oldState) } } -CHIP_ERROR TCPEndPointImplLwIP::AckReceive(uint16_t len) +CHIP_ERROR TCPEndPointImplLwIP::AckReceive(size_t len) { VerifyOrReturnError(IsConnected(), CHIP_ERROR_INCORRECT_STATE); CHIP_ERROR res = CHIP_NO_ERROR; + VerifyOrReturnError(len < UINT16_MAX, CHIP_ERROR_INVALID_ARGUMENT); + // Lock LwIP stack LOCK_TCPIP_CORE(); if (mTCP != nullptr) - tcp_recved(mTCP, len); + tcp_recved(mTCP, static_cast(len)); else res = CHIP_ERROR_CONNECTION_ABORTED; @@ -570,7 +572,7 @@ TCPEndPointImplLwIP::BufferOffset TCPEndPointImplLwIP::FindStartOfUnsent() while (leftToSkip > 0) { VerifyOrDie(!startOfUnsent.buffer.IsNull()); - uint16_t bufDataLen = startOfUnsent.buffer->DataLength(); + uint16_t bufDataLen = static_cast(startOfUnsent.buffer->DataLength()); if (leftToSkip >= bufDataLen) { // We have more to skip than current packet buffer size. diff --git a/src/inet/TCPEndPointImplLwIP.h b/src/inet/TCPEndPointImplLwIP.h index b680f86b3b64e5..86a151f591d303 100644 --- a/src/inet/TCPEndPointImplLwIP.h +++ b/src/inet/TCPEndPointImplLwIP.h @@ -51,7 +51,7 @@ class TCPEndPointImplLwIP : public TCPEndPoint, public EndPointStateLwIP CHIP_ERROR EnableNoDelay() override; CHIP_ERROR EnableKeepAlive(uint16_t interval, uint16_t timeoutCount) override; CHIP_ERROR DisableKeepAlive() override; - CHIP_ERROR AckReceive(uint16_t len) override; + CHIP_ERROR AckReceive(size_t len) override; #if INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT void TCPUserTimeoutHandler() override; #endif // INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT diff --git a/src/inet/TCPEndPointImplOpenThread.cpp b/src/inet/TCPEndPointImplOpenThread.cpp index 36522ca3c47459..97943787dcf1e7 100644 --- a/src/inet/TCPEndPointImplOpenThread.cpp +++ b/src/inet/TCPEndPointImplOpenThread.cpp @@ -54,7 +54,7 @@ CHIP_ERROR TCPEndPointImplOT::DisableKeepAlive() { return CHIP_ERROR_NOT_IMPLEMENTED; } -CHIP_ERROR TCPEndPointImplOT::AckReceive(uint16_t len) +CHIP_ERROR TCPEndPointImplOT::AckReceive(size_t len) { return CHIP_ERROR_NOT_IMPLEMENTED; } diff --git a/src/inet/TCPEndPointImplOpenThread.h b/src/inet/TCPEndPointImplOpenThread.h index c62c63cdc85f55..007d3cfb118bee 100644 --- a/src/inet/TCPEndPointImplOpenThread.h +++ b/src/inet/TCPEndPointImplOpenThread.h @@ -46,7 +46,7 @@ class TCPEndPointImplOT : public TCPEndPoint, public EndPointStateOpenThread CHIP_ERROR EnableNoDelay() override; CHIP_ERROR EnableKeepAlive(uint16_t interval, uint16_t timeoutCount) override; CHIP_ERROR DisableKeepAlive() override; - CHIP_ERROR AckReceive(uint16_t len) override; + CHIP_ERROR AckReceive(size_t len) override; #if INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT void TCPUserTimeoutHandler() override; #endif // INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT diff --git a/src/inet/TCPEndPointImplSockets.cpp b/src/inet/TCPEndPointImplSockets.cpp index fc8c6e2da2a77e..1117eaff54423a 100644 --- a/src/inet/TCPEndPointImplSockets.cpp +++ b/src/inet/TCPEndPointImplSockets.cpp @@ -441,7 +441,7 @@ CHIP_ERROR TCPEndPointImplSockets::DisableKeepAlive() return CHIP_NO_ERROR; } -CHIP_ERROR TCPEndPointImplSockets::AckReceive(uint16_t len) +CHIP_ERROR TCPEndPointImplSockets::AckReceive(size_t len) { VerifyOrReturnError(IsConnected(), CHIP_ERROR_INCORRECT_STATE); @@ -483,7 +483,7 @@ CHIP_ERROR TCPEndPointImplSockets::DriveSendingImpl() while (!mSendQueue.IsNull()) { - uint16_t bufLen = mSendQueue->DataLength(); + uint32_t bufLen = static_cast(mSendQueue->DataLength()); ssize_t lenSentRaw = send(mSocket, mSendQueue->Start(), bufLen, sendFlags); @@ -496,14 +496,14 @@ CHIP_ERROR TCPEndPointImplSockets::DriveSendingImpl() break; } - if (lenSentRaw < 0 || lenSentRaw > bufLen) + if (lenSentRaw < 0 || bufLen < static_cast(lenSentRaw)) { err = CHIP_ERROR_INCORRECT_STATE; break; } - // Cast is safe because bufLen is uint16_t. - uint16_t lenSent = static_cast(lenSentRaw); + // Cast is safe because bufLen is uint32_t. + uint32_t lenSent = static_cast(lenSentRaw); // Mark the connection as being active. MarkActive(); diff --git a/src/inet/TCPEndPointImplSockets.h b/src/inet/TCPEndPointImplSockets.h index 40e81eeb6a0d06..1d9b86b1c9bb66 100644 --- a/src/inet/TCPEndPointImplSockets.h +++ b/src/inet/TCPEndPointImplSockets.h @@ -46,7 +46,7 @@ class TCPEndPointImplSockets : public TCPEndPoint, public EndPointStateSockets CHIP_ERROR EnableNoDelay() override; CHIP_ERROR EnableKeepAlive(uint16_t interval, uint16_t timeoutCount) override; CHIP_ERROR DisableKeepAlive() override; - CHIP_ERROR AckReceive(uint16_t len) override; + CHIP_ERROR AckReceive(size_t len) override; #if INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT void TCPUserTimeoutHandler() override; #endif // INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT @@ -72,7 +72,7 @@ class TCPEndPointImplSockets : public TCPEndPoint, public EndPointStateSockets #if INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT /// This counts the number of bytes written on the TCP socket since thelast probe into the TCP outqueue was made. - uint32_t mBytesWrittenSinceLastProbe; + size_t mBytesWrittenSinceLastProbe; /// This is the measured size(in bytes) of the kernel TCP send queue at the end of the last user timeout window. uint32_t mLastTCPKernelSendQueueLen; diff --git a/src/inet/UDPEndPointImplLwIP.cpp b/src/inet/UDPEndPointImplLwIP.cpp index 7627ff667db57d..9d0d3bb396f482 100755 --- a/src/inet/UDPEndPointImplLwIP.cpp +++ b/src/inet/UDPEndPointImplLwIP.cpp @@ -352,7 +352,7 @@ void UDPEndPointImplLwIP::LwIPReceiveUDPMessage(void * arg, struct udp_pcb * pcb if (buf->HasChainedBuffer()) { // Have to allocate a new big-enough buffer and copy. - uint16_t messageSize = buf->TotalLength(); + size_t messageSize = buf->TotalLength(); System::PacketBufferHandle copy = System::PacketBufferHandle::New(messageSize, 0); if (copy.IsNull() || buf->Read(copy->Start(), messageSize) != CHIP_NO_ERROR) { diff --git a/src/inet/UDPEndPointImplOpenThread.cpp b/src/inet/UDPEndPointImplOpenThread.cpp index 073f633bd8a38c..00587c96ed940e 100644 --- a/src/inet/UDPEndPointImplOpenThread.cpp +++ b/src/inet/UDPEndPointImplOpenThread.cpp @@ -237,7 +237,7 @@ CHIP_ERROR UDPEndPointImplOT::SendMsgImpl(const IPPacketInfo * aPktInfo, System: message = otUdpNewMessage(mOTInstance, NULL); VerifyOrExit(message != NULL, error = OT_ERROR_NO_BUFS); - error = otMessageAppend(message, msg->Start(), msg->DataLength()); + error = otMessageAppend(message, msg->Start(), static_cast(msg->DataLength())); if (error == OT_ERROR_NONE) { diff --git a/src/inet/UDPEndPointImplSockets.cpp b/src/inet/UDPEndPointImplSockets.cpp index f5e89e69fc10fe..22231d97e5f75e 100644 --- a/src/inet/UDPEndPointImplSockets.cpp +++ b/src/inet/UDPEndPointImplSockets.cpp @@ -416,7 +416,10 @@ CHIP_ERROR UDPEndPointImplSockets::SendMsgImpl(const IPPacketInfo * aPktInfo, Sy { return CHIP_ERROR_POSIX(errno); } - if (lenSent != msg->DataLength()) + + size_t len = static_cast(lenSent); + + if (len != msg->DataLength()) { return CHIP_ERROR_OUTBOUND_MESSAGE_TOO_BIG; } @@ -612,7 +615,7 @@ void UDPEndPointImplSockets::HandlePendingIO(System::SocketEvents events) { lStatus = CHIP_ERROR_POSIX(errno); } - else if (rcvLen > lBuffer->AvailableDataLength()) + else if (lBuffer->AvailableDataLength() < static_cast(rcvLen)) { lStatus = CHIP_ERROR_INBOUND_MESSAGE_TOO_BIG; } diff --git a/src/inet/tests/TestInetLayer.cpp b/src/inet/tests/TestInetLayer.cpp index 47e83316228b5f..5dae8b8feffd43 100644 --- a/src/inet/tests/TestInetLayer.cpp +++ b/src/inet/tests/TestInetLayer.cpp @@ -569,7 +569,7 @@ static void HandleTCPConnectionClosed(TCPEndPoint * aEndPoint, CHIP_ERROR aError } } -static void HandleTCPDataSent(TCPEndPoint * aEndPoint, uint16_t len) {} +static void HandleTCPDataSent(TCPEndPoint * aEndPoint, size_t len) {} static CHIP_ERROR HandleTCPDataReceived(TCPEndPoint * aEndPoint, PacketBufferHandle && aBuffer) { diff --git a/src/inet/tests/TestInetLayerCommon.cpp b/src/inet/tests/TestInetLayerCommon.cpp index 7a60a2778239ba..71db2d88a894c1 100644 --- a/src/inet/tests/TestInetLayerCommon.cpp +++ b/src/inet/tests/TestInetLayerCommon.cpp @@ -123,9 +123,9 @@ bool WasSuccessful(const TestStatus & aTestStatus) return (lStatus); } -static void FillDataBufferPattern(uint8_t * aBuffer, uint16_t aLength, uint16_t aPatternStartOffset, uint8_t aFirstValue) +static void FillDataBufferPattern(uint8_t * aBuffer, size_t aLength, size_t aPatternStartOffset, uint8_t aFirstValue) { - for (uint16_t i = aPatternStartOffset; i < aLength; i++) + for (size_t i = aPatternStartOffset; i < aLength; i++) { const uint8_t lValue = static_cast(aFirstValue & 0xFF); @@ -135,9 +135,9 @@ static void FillDataBufferPattern(uint8_t * aBuffer, uint16_t aLength, uint16_t } } -static bool CheckDataBufferPattern(const uint8_t * aBuffer, uint16_t aLength, uint16_t aPatternStartOffset, uint8_t aFirstValue) +static bool CheckDataBufferPattern(const uint8_t * aBuffer, size_t aLength, size_t aPatternStartOffset, size_t aFirstValue) { - for (uint16_t i = aPatternStartOffset; i < aLength; i++) + for (size_t i = aPatternStartOffset; i < aLength; i++) { const uint8_t lValue = aBuffer[i]; @@ -145,8 +145,8 @@ static bool CheckDataBufferPattern(const uint8_t * aBuffer, uint16_t aLength, ui { printf("Bad data value at offset %u (0x%04x): " "expected 0x%02x, found 0x%02x\n", - i, i, aFirstValue, lValue); - DumpMemory(aBuffer + aPatternStartOffset, aLength - aPatternStartOffset, "0x", 16); + static_cast(i), static_cast(i), static_cast(aFirstValue), lValue); + DumpMemory(aBuffer + aPatternStartOffset, static_cast(aLength - aPatternStartOffset), "0x", 16); return false; } @@ -156,7 +156,7 @@ static bool CheckDataBufferPattern(const uint8_t * aBuffer, uint16_t aLength, ui return true; } -static PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint16_t aPatternStartOffset, uint8_t aFirstValue) +static PacketBufferHandle MakeDataBuffer(size_t aDesiredLength, size_t aPatternStartOffset, uint8_t aFirstValue) { VerifyOrReturnError(aPatternStartOffset <= aDesiredLength, PacketBufferHandle()); @@ -172,14 +172,14 @@ static PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint16_t aPatt return lBuffer; } -static PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint16_t aPatternStartOffset) +static PacketBufferHandle MakeDataBuffer(size_t aDesiredLength, size_t aPatternStartOffset) { constexpr uint8_t lFirstValue = 0; return MakeDataBuffer(aDesiredLength, aPatternStartOffset, lFirstValue); } template -static PacketBufferHandle MakeICMPDataBuffer(uint16_t aDesiredUserLength, uint16_t aHeaderLength, uint16_t aPatternStartOffset, +static PacketBufferHandle MakeICMPDataBuffer(size_t aDesiredUserLength, uint16_t aHeaderLength, size_t aPatternStartOffset, uint8_t aType) { static uint16_t lSequenceNumber = 0; @@ -188,7 +188,7 @@ static PacketBufferHandle MakeICMPDataBuffer(uint16_t aDesiredUserLength, uint16 // To ensure there is enough room for the user data and the ICMP // header, include both the user data size and the ICMP header length. - lBuffer = MakeDataBuffer(static_cast(aDesiredUserLength + aHeaderLength), aPatternStartOffset); + lBuffer = MakeDataBuffer(aDesiredUserLength + aHeaderLength, aPatternStartOffset); if (!lBuffer.IsNull()) { @@ -204,7 +204,7 @@ static PacketBufferHandle MakeICMPDataBuffer(uint16_t aDesiredUserLength, uint16 return (lBuffer); } -PacketBufferHandle MakeICMPv4DataBuffer(uint16_t aDesiredUserLength) +PacketBufferHandle MakeICMPv4DataBuffer(size_t aDesiredUserLength) { constexpr uint16_t lICMPHeaderLength = sizeof(ICMPv4EchoHeader); constexpr uint16_t lPatternStartOffset = lICMPHeaderLength; @@ -213,7 +213,7 @@ PacketBufferHandle MakeICMPv4DataBuffer(uint16_t aDesiredUserLength) return MakeICMPDataBuffer(aDesiredUserLength, lICMPHeaderLength, lPatternStartOffset, lType); } -PacketBufferHandle MakeICMPv6DataBuffer(uint16_t aDesiredUserLength) +PacketBufferHandle MakeICMPv6DataBuffer(size_t aDesiredUserLength) { constexpr uint16_t lICMPHeaderLength = sizeof(ICMPv6EchoHeader); constexpr uint16_t lPatternStartOffset = lICMPHeaderLength; @@ -222,44 +222,44 @@ PacketBufferHandle MakeICMPv6DataBuffer(uint16_t aDesiredUserLength) return MakeICMPDataBuffer(aDesiredUserLength, lICMPHeaderLength, lPatternStartOffset, lType); } -PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint8_t aFirstValue) +PacketBufferHandle MakeDataBuffer(size_t aDesiredLength, uint8_t aFirstValue) { - constexpr uint16_t lPatternStartOffset = 0; + constexpr size_t lPatternStartOffset = 0; return MakeDataBuffer(aDesiredLength, lPatternStartOffset, aFirstValue); } -PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength) +PacketBufferHandle MakeDataBuffer(size_t aDesiredLength) { - constexpr uint16_t lPatternStartOffset = 0; + constexpr size_t lPatternStartOffset = 0; return MakeDataBuffer(aDesiredLength, lPatternStartOffset); } static bool HandleDataReceived(const PacketBufferHandle & aBuffer, TransferStats & aStats, bool aStatsByPacket, bool aCheckBuffer, - uint16_t aPatternStartOffset, uint8_t aFirstValue) + size_t aPatternStartOffset, size_t aFirstValue) { - uint16_t lTotalDataLength = 0; + size_t lTotalDataLength = 0; // Walk through each buffer in the packet chain, checking the // buffer for the expected pattern, if requested. for (PacketBufferHandle lBuffer = aBuffer.Retain(); !lBuffer.IsNull(); lBuffer.Advance()) { - const uint16_t lDataLength = lBuffer->DataLength(); - const uint8_t * const p = lBuffer->Start(); + const size_t lDataLength = lBuffer->DataLength(); + const uint8_t * const p = lBuffer->Start(); if (aCheckBuffer && !CheckDataBufferPattern(p, lDataLength, aPatternStartOffset, aFirstValue)) { return false; } - lTotalDataLength = static_cast(lTotalDataLength + lDataLength); - aFirstValue = static_cast(aFirstValue + lDataLength); + lTotalDataLength = lTotalDataLength + lDataLength; + aFirstValue = aFirstValue + lDataLength; } // If we are accumulating stats by packet rather than by size, // then increment by one (1) rather than the total buffer length. - aStats.mReceive.mActual += ((aStatsByPacket) ? 1 : lTotalDataLength); + aStats.mReceive.mActual += ((aStatsByPacket) ? 1 : static_cast(lTotalDataLength)); return true; } diff --git a/src/lib/core/tests/TestTLV.cpp b/src/lib/core/tests/TestTLV.cpp index f71bce13fbd70b..12d6bb96a04e1f 100644 --- a/src/lib/core/tests/TestTLV.cpp +++ b/src/lib/core/tests/TestTLV.cpp @@ -277,7 +277,7 @@ void TestBufferContents(nlTestSuite * inSuite, const System::PacketBufferHandle System::PacketBufferHandle buf = buffer.Retain(); while (!buf.IsNull()) { - uint16_t len = buf->DataLength(); + uint32_t len = static_cast(buf->DataLength()); NL_TEST_ASSERT(inSuite, len <= expectedLen); NL_TEST_ASSERT(inSuite, memcmp(buf->Start(), expectedVal, len) == 0); @@ -2990,8 +2990,8 @@ void CheckBufferOverflow(nlTestSuite * inSuite, void * inContext) System::PacketBufferTLVReader reader; System::PacketBufferHandle buf = System::PacketBufferHandle::New(sizeof(Encoding1), 0); - uint16_t maxDataLen = buf->MaxDataLength(); - uint16_t reserve = static_cast((sizeof(Encoding1) < maxDataLen) ? (maxDataLen - sizeof(Encoding1)) + 2 : 0); + uint32_t maxDataLen = static_cast(buf->MaxDataLength()); + uint32_t reserve = static_cast((sizeof(Encoding1) < maxDataLen) ? (maxDataLen - sizeof(Encoding1)) + 2 : 0); // Repeatedly write and read a TLV encoding to a chain of PacketBuffers. Use progressively larger // and larger amounts of space in the first buffer to force the encoding to overlap the diff --git a/src/messaging/tests/echo/echo_requester.cpp b/src/messaging/tests/echo/echo_requester.cpp index bc5d96d694bb33..016ad60358c18a 100644 --- a/src/messaging/tests/echo/echo_requester.cpp +++ b/src/messaging/tests/echo/echo_requester.cpp @@ -184,7 +184,8 @@ void HandleEchoResponseReceived(chip::Messaging::ExchangeContext * ec, chip::Sys gEchoRespCount++; printf("Echo Response: %" PRIu64 "/%" PRIu64 "(%.2f%%) len=%u time=%.3fs\n", gEchoRespCount, gEchoCount, - static_cast(gEchoRespCount) * 100 / static_cast(gEchoCount), payload->DataLength(), + static_cast(gEchoRespCount) * 100 / static_cast(gEchoCount), + static_cast(payload->DataLength()), static_cast(chip::System::Clock::Milliseconds32(transitTime).count()) / 1000); } diff --git a/src/messaging/tests/echo/echo_responder.cpp b/src/messaging/tests/echo/echo_responder.cpp index 3cf56553294ccb..4383479406648c 100644 --- a/src/messaging/tests/echo/echo_responder.cpp +++ b/src/messaging/tests/echo/echo_responder.cpp @@ -49,7 +49,7 @@ chip::SessionHolder gSession; // Callback handler when a CHIP EchoRequest is received. void HandleEchoRequestReceived(chip::Messaging::ExchangeContext * ec, chip::System::PacketBufferHandle && payload) { - printf("Echo Request, len=%u ... sending response.\n", payload->DataLength()); + printf("Echo Request, len=%u ... sending response.\n", static_cast(payload->DataLength())); } } // namespace diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index 877f49e5fb006c..378257b5faef2a 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -575,7 +575,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU ESP_LOGD(TAG, "Sending indication for CHIPoBLE TX characteristic (con %u, len %u)", conId, data->DataLength()); - om = ble_hs_mbuf_from_flat(data->Start(), data->DataLength()); + om = ble_hs_mbuf_from_flat(data->Start(), static_cast(data->DataLength())); if (om == NULL) { ChipLogError(DeviceLayer, "ble_hs_mbuf_from_flat failed:"); diff --git a/src/platform/Zephyr/BLEManagerImpl.cpp b/src/platform/Zephyr/BLEManagerImpl.cpp index 09ddd4fbe34304..61bfef9d7ea899 100644 --- a/src/platform/Zephyr/BLEManagerImpl.cpp +++ b/src/platform/Zephyr/BLEManagerImpl.cpp @@ -658,7 +658,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU params->attr = &sChipoBleAttributes[kCHIPoBLE_CCC_AttributeIndex]; params->func = HandleTXIndicated; params->data = pBuf->Start(); - params->len = pBuf->DataLength(); + params->len = static_cast(pBuf->DataLength()); status = bt_gatt_indicate(conId, params); VerifyOrExit(status == 0, err = MapErrorZephyr(status)); @@ -837,7 +837,7 @@ ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gat } return bt_gatt_attr_read(conId, attr, buf, len, offset, sInstance.c3CharDataBufferHandle->Start(), - sInstance.c3CharDataBufferHandle->DataLength()); + static_cast(sInstance.c3CharDataBufferHandle->DataLength())); } #endif diff --git a/src/platform/android/BLEManagerImpl.cpp b/src/platform/android/BLEManagerImpl.cpp index 05dfb5f560fbb5..a4dd3964ef4a1f 100644 --- a/src/platform/android/BLEManagerImpl.cpp +++ b/src/platform/android/BLEManagerImpl.cpp @@ -384,7 +384,8 @@ bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::Ch err = JniReferences::GetInstance().N2J_ByteArray(env, static_cast(charId->bytes), 16, charIdObj); SuccessOrExit(err); - err = JniReferences::GetInstance().N2J_ByteArray(env, pBuf->Start(), pBuf->DataLength(), characteristicDataObj); + err = JniReferences::GetInstance().N2J_ByteArray(env, pBuf->Start(), static_cast(pBuf->DataLength()), + characteristicDataObj); SuccessOrExit(err); env->ExceptionClear(); diff --git a/src/platform/bouffalolab/common/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp index 1612f080d03575..887e45f1d7bddd 100644 --- a/src/platform/bouffalolab/common/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -669,7 +669,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU params->attr = &sChipoBleAttributes[kCHIPoBLE_CCC_AttributeIndex]; params->func = HandleTXIndicated; params->data = pBuf->Start(); - params->len = pBuf->DataLength(); + params->len = static_cast(pBuf->DataLength()); status = bt_gatt_indicate(conId, params); VerifyOrExit(status == 0, err = MapErrorZephyr(status)); @@ -849,7 +849,7 @@ ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gat } return bt_gatt_attr_read(conId, attr, buf, len, offset, sInstance.c3CharDataBufferHandle->Start(), - sInstance.c3CharDataBufferHandle->DataLength()); + static_cast(sInstance.c3CharDataBufferHandle->DataLength())); } #endif diff --git a/src/platform/mbed/BLEManagerImpl.cpp b/src/platform/mbed/BLEManagerImpl.cpp index aa797ff95f6f4c..b42801adb908d7 100644 --- a/src/platform/mbed/BLEManagerImpl.cpp +++ b/src/platform/mbed/BLEManagerImpl.cpp @@ -1007,7 +1007,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU "(connHandle=%d, attHandle=%d, data_len=%u)", conId, att_handle, pBuf->DataLength()); - mbed_err = gatt_server.write(att_handle, pBuf->Start(), pBuf->DataLength(), false); + mbed_err = gatt_server.write(att_handle, pBuf->Start(), static_cast(pBuf->DataLength()), false); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR(chip::ChipError::Range::kOS, mbed_err)); exit: diff --git a/src/protocols/secure_channel/CASESession.cpp b/src/protocols/secure_channel/CASESession.cpp index ee8feaefb5f93d..7fa0f66822389c 100644 --- a/src/protocols/secure_channel/CASESession.cpp +++ b/src/protocols/secure_channel/CASESession.cpp @@ -1575,7 +1575,7 @@ CHIP_ERROR CASESession::HandleSigma3a(System::PacketBufferHandle && msg) TLV::TLVType containerType = TLV::kTLVType_Structure; const uint8_t * buf = msg->Start(); - const uint16_t bufLen = msg->DataLength(); + const uint32_t bufLen = static_cast(msg->DataLength()); constexpr size_t kCaseOverheadForFutureTbeData = 128; diff --git a/src/protocols/user_directed_commissioning/UserDirectedCommissioningClient.cpp b/src/protocols/user_directed_commissioning/UserDirectedCommissioningClient.cpp index 3bb69c099612e3..bf7db199ca2d53 100644 --- a/src/protocols/user_directed_commissioning/UserDirectedCommissioningClient.cpp +++ b/src/protocols/user_directed_commissioning/UserDirectedCommissioningClient.cpp @@ -255,7 +255,7 @@ void UserDirectedCommissioningClient::OnMessageReceived(const Transport::PeerAdd PayloadHeader payloadHeader; ReturnOnFailure(payloadHeader.DecodeAndConsume(msg)); - ChipLogProgress(AppServer, "CommissionerDeclaration DataLength()=%d", msg->DataLength()); + ChipLogProgress(AppServer, "CommissionerDeclaration DataLength()=%u", static_cast(msg->DataLength())); uint8_t udcPayload[IdentificationDeclaration::kUdcTLVDataMaxBytes]; size_t udcPayloadLength = std::min(msg->DataLength(), sizeof(udcPayload)); diff --git a/src/protocols/user_directed_commissioning/UserDirectedCommissioningServer.cpp b/src/protocols/user_directed_commissioning/UserDirectedCommissioningServer.cpp index 746df853436877..b875bdc4b7be3a 100644 --- a/src/protocols/user_directed_commissioning/UserDirectedCommissioningServer.cpp +++ b/src/protocols/user_directed_commissioning/UserDirectedCommissioningServer.cpp @@ -52,7 +52,7 @@ void UserDirectedCommissioningServer::OnMessageReceived(const Transport::PeerAdd PayloadHeader payloadHeader; ReturnOnFailure(payloadHeader.DecodeAndConsume(msg)); - ChipLogProgress(AppServer, "IdentityDeclaration DataLength()=%d", msg->DataLength()); + ChipLogProgress(AppServer, "IdentityDeclaration DataLength()=%u", static_cast(msg->DataLength())); uint8_t udcPayload[IdentificationDeclaration::kUdcTLVDataMaxBytes]; size_t udcPayloadLength = std::min(msg->DataLength(), sizeof(udcPayload)); diff --git a/src/system/SystemPacketBuffer.cpp b/src/system/SystemPacketBuffer.cpp index 32f4b8e3830077..1db47449dd8ed4 100644 --- a/src/system/SystemPacketBuffer.cpp +++ b/src/system/SystemPacketBuffer.cpp @@ -121,7 +121,8 @@ void PacketBuffer::InternalCheck(const PacketBuffer * buffer) VerifyOrDieWithMsg(::chip::Platform::MemoryDebugCheckPointer(buffer, buffer->alloc_size + kStructureSize), chipSystemLayer, "invalid packet buffer pointer"); VerifyOrDieWithMsg(buffer->alloc_size >= buffer->ReservedSize() + buffer->len, chipSystemLayer, - "packet buffer overflow %u < %u+%u", buffer->alloc_size, buffer->ReservedSize(), buffer->len); + "packet buffer overflow %u < %u+%u", static_cast(buffer->alloc_size), buffer->ReservedSize(), + static_cast(buffer->len)); } } #endif // CHIP_SYSTEM_PACKETBUFFER_HAS_CHECK @@ -140,7 +141,7 @@ void PacketBufferHandle::InternalRightSize() // Reallocate only if enough space will be saved. const uint8_t * const start = mBuffer->ReserveStart(); const uint8_t * const payload = mBuffer->Start(); - const uint16_t usedSize = static_cast(payload - start + mBuffer->len); + const size_t usedSize = static_cast(static_cast(payload - start) + mBuffer->len); if (usedSize + kRightSizingThreshold > mBuffer->alloc_size) { return; @@ -160,7 +161,7 @@ void PacketBufferHandle::InternalRightSize() newBuffer->tot_len = mBuffer->tot_len; newBuffer->len = mBuffer->len; newBuffer->ref = 1; - newBuffer->alloc_size = static_cast(usedSize); + newBuffer->alloc_size = usedSize; memcpy(newStart, start, usedSize); PacketBuffer::Free(mBuffer); @@ -207,25 +208,36 @@ void PacketBuffer::SetStart(uint8_t * aNewStart) aNewStart = kEnd; ptrdiff_t lDelta = aNewStart - static_cast(this->payload); - if (lDelta > this->len) - lDelta = this->len; + if (lDelta > static_cast(this->len)) + lDelta = static_cast(this->len); - this->len = static_cast(static_cast(this->len) - lDelta); - this->tot_len = static_cast(static_cast(this->tot_len) - lDelta); +#if CHIP_SYSTEM_CONFIG_USE_LWIP + this->len = static_cast(static_cast(this->len) - lDelta); + this->tot_len = static_cast(static_cast(this->tot_len) - lDelta); +#else + this->len = static_cast(static_cast(this->len) - lDelta); + this->tot_len = static_cast(static_cast(this->tot_len) - lDelta); +#endif this->payload = aNewStart; } -void PacketBuffer::SetDataLength(uint16_t aNewLen, PacketBuffer * aChainHead) +void PacketBuffer::SetDataLength(size_t aNewLen, PacketBuffer * aChainHead) { - const uint16_t kMaxDataLen = this->MaxDataLength(); + const size_t kMaxDataLen = this->MaxDataLength(); if (aNewLen > kMaxDataLen) aNewLen = kMaxDataLen; - ptrdiff_t lDelta = static_cast(aNewLen) - static_cast(this->len); + int32_t lDelta = static_cast(aNewLen) - static_cast(this->len); +#if CHIP_SYSTEM_CONFIG_USE_LWIP + VerifyOrDieWithMsg(aNewLen < UINT16_MAX, chipSystemLayer, "LwIP buffer length cannot exceed UINT16_MAX"); + this->len = static_cast(aNewLen); + this->tot_len = static_cast(static_cast(this->tot_len) + lDelta); +#else this->len = aNewLen; - this->tot_len = static_cast(this->tot_len + lDelta); + this->tot_len = static_cast(static_cast(this->tot_len) + lDelta); +#endif // SetDataLength is often called after a client finished writing to the buffer, // so it's a good time to check for possible corruption. @@ -234,12 +246,16 @@ void PacketBuffer::SetDataLength(uint16_t aNewLen, PacketBuffer * aChainHead) while (aChainHead != nullptr && aChainHead != this) { Check(aChainHead); - aChainHead->tot_len = static_cast(aChainHead->tot_len + lDelta); - aChainHead = aChainHead->ChainedBuffer(); +#if CHIP_SYSTEM_CONFIG_USE_LWIP + aChainHead->tot_len = static_cast(static_cast(aChainHead->tot_len) + lDelta); +#else + aChainHead->tot_len = static_cast(static_cast(aChainHead->tot_len) + lDelta); +#endif + aChainHead = aChainHead->ChainedBuffer(); } } -uint16_t PacketBuffer::MaxDataLength() const +size_t PacketBuffer::MaxDataLength() const { #if CHIP_SYSTEM_CONFIG_USE_LWIP if (!(PBUF_STRUCT_DATA_CONTIGUOUS(this))) @@ -247,12 +263,12 @@ uint16_t PacketBuffer::MaxDataLength() const return DataLength(); } #endif - return static_cast(AllocSize() - ReservedSize()); + return static_cast(AllocSize() - ReservedSize()); } -uint16_t PacketBuffer::AvailableDataLength() const +size_t PacketBuffer::AvailableDataLength() const { - return static_cast(this->MaxDataLength() - this->DataLength()); + return (this->MaxDataLength() - this->DataLength()); } uint16_t PacketBuffer::ReservedSize() const @@ -296,8 +312,8 @@ void PacketBuffer::AddToEnd(PacketBufferHandle && aPacketHandle) while (true) { - uint16_t old_total_length = lCursor->tot_len; - lCursor->tot_len = static_cast(lCursor->tot_len + aPacket->tot_len); + size_t old_total_length = lCursor->tot_len; + lCursor->tot_len = lCursor->tot_len + aPacket->tot_len; VerifyOrDieWithMsg(lCursor->tot_len >= old_total_length, chipSystemLayer, "buffer chain too large"); if (!lCursor->HasChainedBuffer()) { @@ -320,37 +336,48 @@ void PacketBuffer::CompactHead() this->payload = kStart; } - uint16_t lAvailLength = this->AvailableDataLength(); + size_t lAvailLength = this->AvailableDataLength(); while (lAvailLength > 0 && HasChainedBuffer()) { PacketBuffer & lNextPacket = *ChainedBuffer(); VerifyOrDieWithMsg(lNextPacket.ref == 1, chipSystemLayer, "next buffer %p is not exclusive to this chain", &lNextPacket); - uint16_t lMoveLength = lNextPacket.len; + size_t lMoveLength = lNextPacket.len; if (lMoveLength > lAvailLength) lMoveLength = lAvailLength; memcpy(static_cast(this->payload) + this->len, lNextPacket.payload, lMoveLength); lNextPacket.payload = static_cast(lNextPacket.payload) + lMoveLength; + lAvailLength = lAvailLength - lMoveLength; +#if CHIP_SYSTEM_CONFIG_USE_LWIP this->len = static_cast(this->len + lMoveLength); - lAvailLength = static_cast(lAvailLength - lMoveLength); lNextPacket.len = static_cast(lNextPacket.len - lMoveLength); lNextPacket.tot_len = static_cast(lNextPacket.tot_len - lMoveLength); +#else + this->len = this->len + lMoveLength; + lNextPacket.len = lNextPacket.len - lMoveLength; + lNextPacket.tot_len = lNextPacket.tot_len - lMoveLength; +#endif if (lNextPacket.len == 0) this->next = this->FreeHead(&lNextPacket); } } -void PacketBuffer::ConsumeHead(uint16_t aConsumeLength) +void PacketBuffer::ConsumeHead(size_t aConsumeLength) { if (aConsumeLength > this->len) aConsumeLength = this->len; this->payload = static_cast(this->payload) + aConsumeLength; +#if CHIP_SYSTEM_CONFIG_USE_LWIP this->len = static_cast(this->len - aConsumeLength); this->tot_len = static_cast(this->tot_len - aConsumeLength); +#else + this->len = this->len - aConsumeLength; + this->tot_len = this->tot_len - aConsumeLength; +#endif } /** @@ -364,18 +391,18 @@ void PacketBuffer::ConsumeHead(uint16_t aConsumeLength) * * @return the first buffer from the current chain that contains any remaining data. If no data remains, nullptr is returned. */ -PacketBuffer * PacketBuffer::Consume(uint16_t aConsumeLength) +PacketBuffer * PacketBuffer::Consume(size_t aConsumeLength) { PacketBuffer * lPacket = this; while (lPacket != nullptr && aConsumeLength > 0) { - const uint16_t kLength = lPacket->DataLength(); + const size_t kLength = lPacket->DataLength(); if (aConsumeLength >= kLength) { lPacket = PacketBuffer::FreeHead(lPacket); - aConsumeLength = static_cast(aConsumeLength - kLength); + aConsumeLength = aConsumeLength - kLength; } else { @@ -482,7 +509,13 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese static_assert(PacketBuffer::kStructureSize == sizeof(PacketBuffer), "PacketBuffer size mismatch"); static_assert(PacketBuffer::kStructureSize < UINT16_MAX, "Check for overflow more carefully"); static_assert(SIZE_MAX >= INT_MAX, "Our additions might not fit in size_t"); - static_assert(PacketBuffer::kMaxSizeWithoutReserve <= UINT16_MAX, "PacketBuffer may have size not fitting uint16_t"); + static_assert(PacketBuffer::kMaxSizeWithoutReserve <= UINT32_MAX, "PacketBuffer may have size not fitting uint32_t"); +#if CHIP_SYSTEM_CONFIG_USE_LWIP + // LwIP based APIs have a maximum buffer size of UINT16_MAX. Ensure that + // limit is met during allocation. + VerifyOrDieWithMsg(aAvailableSize + aReservedSize < UINT16_MAX, chipSystemLayer, + "LwIP based systems can handle only up to UINT16_MAX!"); +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP // When `aAvailableSize` fits in uint16_t (as tested below) and size_t is at least 32 bits (as asserted above), // these additions will not overflow. @@ -492,7 +525,8 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese CHIP_SYSTEM_FAULT_INJECT(FaultInjection::kFault_PacketBufferNew, return PacketBufferHandle()); - if (aAvailableSize > UINT16_MAX || lAllocSize > PacketBuffer::kMaxSizeWithoutReserve || lBlockSize > UINT16_MAX) + // TODO: Change the max to a lower value + if (aAvailableSize > UINT32_MAX || lAllocSize > PacketBuffer::kMaxSizeWithoutReserve || lBlockSize > UINT32_MAX) { ChipLogError(chipSystemLayer, "PacketBuffer: allocation too large."); return PacketBufferHandle(); @@ -545,13 +579,13 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese lPacket->next = nullptr; lPacket->ref = 1; #if CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP - lPacket->alloc_size = static_cast(lAllocSize); + lPacket->alloc_size = lAllocSize; #endif return PacketBufferHandle(lPacket); } -PacketBufferHandle PacketBufferHandle::NewWithData(const void * aData, size_t aDataSize, uint16_t aAdditionalSize, +PacketBufferHandle PacketBufferHandle::NewWithData(const void * aData, size_t aDataSize, size_t aAdditionalSize, uint16_t aReservedSize) { if (aDataSize > UINT16_MAX) @@ -565,7 +599,11 @@ PacketBufferHandle PacketBufferHandle::NewWithData(const void * aData, size_t aD if (buffer.mBuffer != nullptr) { memcpy(buffer.mBuffer->payload, aData, aDataSize); +#if CHIP_SYSTEM_CONFIG_USE_LWIP buffer.mBuffer->len = buffer.mBuffer->tot_len = static_cast(aDataSize); +#else + buffer.mBuffer->len = buffer.mBuffer->tot_len = aDataSize; +#endif } return buffer; } @@ -681,7 +719,7 @@ PacketBufferHandle PacketBufferHandle::CloneData() const for (PacketBuffer * original = mBuffer; original != nullptr; original = original->ChainedBuffer()) { - uint16_t originalDataSize = original->MaxDataLength(); + size_t originalDataSize = original->MaxDataLength(); uint16_t originalReservedSize = original->ReservedSize(); if (originalDataSize + originalReservedSize > PacketBuffer::kMaxSizeWithoutReserve) @@ -695,7 +733,7 @@ PacketBufferHandle PacketBufferHandle::CloneData() const } // Otherwise, reduce the requested data size. This subtraction can not underflow because the above test // guarantees originalReservedSize <= PacketBuffer::kMaxSizeWithoutReserve. - originalDataSize = static_cast(PacketBuffer::kMaxSizeWithoutReserve - originalReservedSize); + originalDataSize = PacketBuffer::kMaxSizeWithoutReserve - originalReservedSize; } PacketBufferHandle clone = PacketBufferHandle::New(originalDataSize, originalReservedSize); @@ -729,7 +767,7 @@ System::PacketBufferHandle PacketBufferWriterUtil::Finalize(BufferWriter & aBuff { // Since mPacket was successfully allocated to hold the maximum length, // we know that the actual length fits in a uint16_t. - aPacket->SetDataLength(static_cast(aBufferWriter.Needed())); + aPacket->SetDataLength(aBufferWriter.Needed()); } else { diff --git a/src/system/SystemPacketBuffer.h b/src/system/SystemPacketBuffer.h index 88db4196438c1d..6bc43b3e2647c3 100644 --- a/src/system/SystemPacketBuffer.h +++ b/src/system/SystemPacketBuffer.h @@ -56,11 +56,11 @@ struct pbuf { struct pbuf * next; void * payload; - uint16_t tot_len; - uint16_t len; + size_t tot_len; + size_t len; uint16_t ref; #if CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP - uint16_t alloc_size; + size_t alloc_size; #endif }; #endif // !CHIP_SYSTEM_CONFIG_USE_LWIP @@ -114,9 +114,9 @@ class DLL_EXPORT PacketBuffer : private pbuf private: // The effective size of the packet buffer structure. #if CHIP_SYSTEM_CONFIG_USE_LWIP - static constexpr uint16_t kStructureSize = LWIP_MEM_ALIGN_SIZE(sizeof(struct ::pbuf)); + static constexpr size_t kStructureSize = LWIP_MEM_ALIGN_SIZE(sizeof(struct ::pbuf)); #else // CHIP_SYSTEM_CONFIG_USE_LWIP - static constexpr uint16_t kStructureSize = CHIP_SYSTEM_ALIGN_SIZE(sizeof(::chip::System::pbuf), 4u); + static constexpr size_t kStructureSize = CHIP_SYSTEM_ALIGN_SIZE(sizeof(::chip::System::pbuf), 4u); #endif // CHIP_SYSTEM_CONFIG_USE_LWIP public: @@ -124,9 +124,9 @@ class DLL_EXPORT PacketBuffer : private pbuf * The maximum size buffer an application can allocate with no protocol header reserve. */ #if CHIP_SYSTEM_CONFIG_USE_LWIP - static constexpr uint16_t kMaxSizeWithoutReserve = LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE); + static constexpr size_t kMaxSizeWithoutReserve = LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE); #else - static constexpr uint16_t kMaxSizeWithoutReserve = CHIP_SYSTEM_CONFIG_PACKETBUFFER_CAPACITY_MAX; + static constexpr size_t kMaxSizeWithoutReserve = CHIP_SYSTEM_CONFIG_PACKETBUFFER_CAPACITY_MAX; #endif /** @@ -138,7 +138,7 @@ class DLL_EXPORT PacketBuffer : private pbuf /** * The maximum size buffer an application can allocate with the default protocol header reserve. */ - static constexpr uint16_t kMaxSize = kMaxSizeWithoutReserve - kDefaultHeaderReserve; + static constexpr size_t kMaxSize = kMaxSizeWithoutReserve - kDefaultHeaderReserve; /** * Return the size of the allocation including the reserved and payload data spaces but not including space @@ -148,7 +148,7 @@ class DLL_EXPORT PacketBuffer : private pbuf * * @return size of the allocation */ - uint16_t AllocSize() const + size_t AllocSize() const { #if CHIP_SYSTEM_PACKETBUFFER_FROM_LWIP_STANDARD_POOL || CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_POOL return kMaxSizeWithoutReserve; @@ -191,7 +191,7 @@ class DLL_EXPORT PacketBuffer : private pbuf * * @return length, in bytes (current payload length). */ - uint16_t DataLength() const { return this->len; } + size_t DataLength() const { return this->len; } /** * Set the length, in bytes, of data in a packet buffer, adjusting total length accordingly. @@ -206,29 +206,29 @@ class DLL_EXPORT PacketBuffer : private pbuf * @param[in,out] aChainHead - the head of the buffer chain the current buffer belongs to. May be \c nullptr if the current * buffer is the head of the buffer chain. */ - void SetDataLength(uint16_t aNewLen, const PacketBufferHandle & aChainHead); - void SetDataLength(uint16_t aNewLen) { SetDataLength(aNewLen, nullptr); } + void SetDataLength(size_t aNewLen, const PacketBufferHandle & aChainHead); + void SetDataLength(size_t aNewLen) { SetDataLength(aNewLen, nullptr); } /** * Get the total length of packet data in the buffer chain. * * @return total length, in octets. */ - uint16_t TotalLength() const { return this->tot_len; } + size_t TotalLength() const { return this->tot_len; } /** * Get the maximum amount, in bytes, of data that will fit in the buffer given the current start position and buffer size. * * @return number of bytes that fits in the buffer given the current start position. */ - uint16_t MaxDataLength() const; + size_t MaxDataLength() const; /** * Get the number of bytes of data that can be added to the current buffer given the current start position and data length. * * @return the length, in bytes, of data that will fit in the current buffer given the current start position and data length. */ - uint16_t AvailableDataLength() const; + size_t AvailableDataLength() const; /** * Get the number of bytes within the current buffer between the start of the buffer and the current data start position. @@ -274,7 +274,7 @@ class DLL_EXPORT PacketBuffer : private pbuf * * @param[in] aConsumeLength - number of bytes to consume from the current buffer. */ - void ConsumeHead(uint16_t aConsumeLength); + void ConsumeHead(size_t aConsumeLength); /** * Ensure the buffer has at least the specified amount of reserved space. @@ -379,9 +379,9 @@ class DLL_EXPORT PacketBuffer : private pbuf static PacketBuffer * FreeHead(PacketBuffer * aPacket); PacketBuffer * ChainedBuffer() const { return static_cast(this->next); } - PacketBuffer * Consume(uint16_t aConsumeLength); + PacketBuffer * Consume(size_t aConsumeLength); void Clear(); - void SetDataLength(uint16_t aNewLen, PacketBuffer * aChainHead); + void SetDataLength(size_t aNewLen, PacketBuffer * aChainHead); /** * Get a pointer to the start of the reserved space (which comes before the @@ -542,7 +542,7 @@ class DLL_EXPORT PacketBufferHandle * * @param[in] aConsumeLength - number of bytes to consume from the current chain. */ - void Consume(uint16_t aConsumeLength) { mBuffer = mBuffer->Consume(aConsumeLength); } + void Consume(size_t aConsumeLength) { mBuffer = mBuffer->Consume(aConsumeLength); } /** * Copy the given buffer to a right-sized buffer if applicable. @@ -630,7 +630,7 @@ class DLL_EXPORT PacketBufferHandle * * @return On success, a PacketBufferHandle to the allocated buffer. On fail, \c nullptr. */ - static PacketBufferHandle NewWithData(const void * aData, size_t aDataSize, uint16_t aAdditionalSize = 0, + static PacketBufferHandle NewWithData(const void * aData, size_t aDataSize, size_t aAdditionalSize = 0, uint16_t aReservedSize = PacketBuffer::kDefaultHeaderReserve); /** @@ -699,7 +699,7 @@ class DLL_EXPORT PacketBufferHandle friend class ::PacketBufferTest; }; -inline void PacketBuffer::SetDataLength(uint16_t aNewLen, const PacketBufferHandle & aChainHead) +inline void PacketBuffer::SetDataLength(size_t aNewLen, const PacketBufferHandle & aChainHead) { SetDataLength(aNewLen, aChainHead.mBuffer); } diff --git a/src/system/TLVPacketBufferBackingStore.cpp b/src/system/TLVPacketBufferBackingStore.cpp index 5059f837ff69a3..ef71a3cfdb413f 100644 --- a/src/system/TLVPacketBufferBackingStore.cpp +++ b/src/system/TLVPacketBufferBackingStore.cpp @@ -31,7 +31,7 @@ namespace System { CHIP_ERROR TLVPacketBufferBackingStore::OnInit(chip::TLV::TLVReader & reader, const uint8_t *& bufStart, uint32_t & bufLen) { bufStart = mHeadBuffer->Start(); - bufLen = mHeadBuffer->DataLength(); + bufLen = static_cast(mHeadBuffer->DataLength()); return CHIP_NO_ERROR; } @@ -54,7 +54,7 @@ CHIP_ERROR TLVPacketBufferBackingStore::GetNextBuffer(chip::TLV::TLVReader & rea else { bufStart = mCurrentBuffer->Start(); - bufLen = mCurrentBuffer->DataLength(); + bufLen = static_cast(mCurrentBuffer->DataLength()); } return CHIP_NO_ERROR; @@ -63,7 +63,7 @@ CHIP_ERROR TLVPacketBufferBackingStore::GetNextBuffer(chip::TLV::TLVReader & rea CHIP_ERROR TLVPacketBufferBackingStore::OnInit(chip::TLV::TLVWriter & writer, uint8_t *& bufStart, uint32_t & bufLen) { bufStart = mHeadBuffer->Start() + mHeadBuffer->DataLength(); - bufLen = mHeadBuffer->AvailableDataLength(); + bufLen = static_cast(mHeadBuffer->AvailableDataLength()); return CHIP_NO_ERROR; } @@ -72,11 +72,11 @@ CHIP_ERROR TLVPacketBufferBackingStore::FinalizeBuffer(chip::TLV::TLVWriter & wr uint8_t * endPtr = bufStart + dataLen; intptr_t length = endPtr - mCurrentBuffer->Start(); - if (!CanCastTo(length)) + if (!CanCastTo(length)) { return CHIP_ERROR_INVALID_ARGUMENT; } - mCurrentBuffer->SetDataLength(static_cast(length), mHeadBuffer); + mCurrentBuffer->SetDataLength(static_cast(length), mHeadBuffer); return CHIP_NO_ERROR; } @@ -107,7 +107,7 @@ CHIP_ERROR TLVPacketBufferBackingStore::GetNewBuffer(chip::TLV::TLVWriter & writ else { bufStart = mCurrentBuffer->Start(); - bufLen = mCurrentBuffer->MaxDataLength(); + bufLen = static_cast(mCurrentBuffer->MaxDataLength()); } return CHIP_NO_ERROR; diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index 9bf2597d7a92b5..9a65500635467e 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -70,9 +70,9 @@ using ::chip::System::pbuf; #define OF_LWIP_PBUF(x) (reinterpret_cast(reinterpret_cast(x))) namespace { -void ScrambleData(uint8_t * start, uint16_t length) +void ScrambleData(uint8_t * start, size_t length) { - for (uint16_t i = 0; i < length; ++i) + for (size_t i = 0; i < length; ++i) ++start[i]; } } // namespace @@ -137,7 +137,7 @@ class PacketBufferTest static void PrintHandle(const char * tag, const PacketBuffer * buffer) { - printf("%s %p ref=%u len=%-4u next=%p\n", StringOrNullMarker(tag), buffer, buffer ? buffer->ref : 0, + printf("%s %p ref=%u len=%-4zu next=%p\n", StringOrNullMarker(tag), buffer, buffer ? buffer->ref : 0, buffer ? buffer->len : 0, buffer ? buffer->next : nullptr); } static void PrintHandle(const char * tag, const PacketBufferHandle & handle) { PrintHandle(tag, handle.mBuffer); } @@ -152,7 +152,7 @@ class PacketBufferTest handle(nullptr) {} - uint16_t init_len; + size_t init_len; uint16_t reserved_size; uint8_t * start_buffer; uint8_t * end_buffer; @@ -163,7 +163,7 @@ class PacketBufferTest static void PrintHandle(const char * tag, const BufferConfiguration & config) { PrintHandle(tag, config.handle); } static void PrintConfig(const char * tag, const BufferConfiguration & config) { - printf("%s pay=%-4zu len=%-4u res=%-4u:", StringOrNullMarker(tag), config.payload_ptr - config.start_buffer, + printf("%s pay=%-4zu len=%-4zu res=%-4u:", StringOrNullMarker(tag), config.payload_ptr - config.start_buffer, config.init_len, config.reserved_size); PrintHandle("", config.handle); } @@ -287,21 +287,18 @@ void PacketBufferTest::PrepareTestBuffer(BufferConfiguration * config, int flags if (config->handle.IsNull()) { config->handle = PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (config->handle.IsNull()) - { - printf("NewPacketBuffer: Failed to allocate packet buffer (%u retained): %s\n", - static_cast(handles.size()), strerror(errno)); - exit(EXIT_FAILURE); - } + VerifyOrDieWithMsg(!config->handle.IsNull(), chipSystemLayer, + "NewPacketBuffer: Failed to allocate packet buffer (%u retained): %s", + static_cast(handles.size()), strerror(errno)); if (flags & kRecordHandle) { handles.push_back(config->handle.Retain()); } } - else if ((flags & kAllowHandleReuse) == 0) + else { - printf("Dirty test configuration\n"); - exit(EXIT_FAILURE); + VerifyOrDieWithMsg((flags & kAllowHandleReuse) != 0, chipSystemLayer, "Dirty test configuration"); + } const size_t lInitialSize = PacketBuffer::kStructureSize + config->reserved_size; @@ -329,8 +326,15 @@ void PacketBufferTest::PrepareTestBuffer(BufferConfiguration * config, int flags config->handle->next = nullptr; } config->handle->payload = config->payload_ptr; +#if CHIP_SYSTEM_CONFIG_USE_LWIP + VerifyOrDieWithMsg(config->init_len < UINT16_MAX, chipSystemLayer, "Max Length exceeded for LwIP based systems"); + + config->handle->len = static_cast(config->init_len); + config->handle->tot_len = static_cast(config->init_len); +#else config->handle->len = config->init_len; config->handle->tot_len = config->init_len; +#endif } bool PacketBufferTest::ResetHandles() @@ -492,7 +496,7 @@ void PacketBufferTest::CheckSetStart(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, config.handle->payload == verify_start); - if ((verify_start - config.payload_ptr) > config.init_len) + if (verify_start - config.payload_ptr > static_cast(config.init_len)) { // Set start to the beginning of payload, right after handle's header. NL_TEST_ASSERT(inSuite, config.handle->len == 0); @@ -501,7 +505,10 @@ void PacketBufferTest::CheckSetStart(nlTestSuite * inSuite, void * inContext) { // Set start to somewhere between the end of the handle's // header and the end of payload. - NL_TEST_ASSERT(inSuite, config.handle->len == (config.init_len - (verify_start - config.payload_ptr))); + NL_TEST_ASSERT( + inSuite, + config.handle->len == + static_cast((static_cast(config.init_len) - (verify_start - config.payload_ptr)))); } } } @@ -560,8 +567,10 @@ void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContex if (length > (config_2.end_buffer - config_2.payload_ptr)) { - NL_TEST_ASSERT(inSuite, config_2.handle->len == (config_2.end_buffer - config_2.payload_ptr)); - NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == (config_2.end_buffer - config_2.payload_ptr)); + NL_TEST_ASSERT(inSuite, + config_2.handle->len == static_cast(config_2.end_buffer - config_2.payload_ptr)); + NL_TEST_ASSERT(inSuite, + config_2.handle->tot_len == static_cast(config_2.end_buffer - config_2.payload_ptr)); NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); } else @@ -578,14 +587,17 @@ void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContex if (length > (config_2.end_buffer - config_2.payload_ptr)) { - NL_TEST_ASSERT(inSuite, config_2.handle->len == (config_2.end_buffer - config_2.payload_ptr)); - NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == (config_2.end_buffer - config_2.payload_ptr)); + NL_TEST_ASSERT(inSuite, + config_2.handle->len == static_cast(config_2.end_buffer - config_2.payload_ptr)); + NL_TEST_ASSERT(inSuite, + config_2.handle->tot_len == static_cast(config_2.end_buffer - config_2.payload_ptr)); NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); NL_TEST_ASSERT(inSuite, config_1.handle->tot_len == - (config_1.init_len + static_cast(config_2.end_buffer - config_2.payload_ptr) - - static_cast(config_2.init_len))); + static_cast(static_cast(config_1.init_len) + + static_cast(config_2.end_buffer - config_2.payload_ptr) - + static_cast(config_2.init_len))); } else { @@ -593,10 +605,11 @@ void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContex NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == length); NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); - NL_TEST_ASSERT( - inSuite, - config_1.handle->tot_len == - (config_1.init_len + static_cast(length) - static_cast(config_2.init_len))); + NL_TEST_ASSERT(inSuite, + config_1.handle->tot_len == + static_cast(static_cast(config_1.init_len) + + static_cast(length) - + static_cast(config_2.init_len))); } } } @@ -633,7 +646,7 @@ void PacketBufferTest::CheckMaxDataLength(nlTestSuite * inSuite, void * inContex { test->PrepareTestBuffer(&config, kRecordHandle); - NL_TEST_ASSERT(inSuite, config.handle->MaxDataLength() == (config.end_buffer - config.payload_ptr)); + NL_TEST_ASSERT(inSuite, config.handle->MaxDataLength() == static_cast(config.end_buffer - config.payload_ptr)); } } @@ -651,7 +664,9 @@ void PacketBufferTest::CheckAvailableDataLength(nlTestSuite * inSuite, void * in test->PrepareTestBuffer(&config, kRecordHandle); NL_TEST_ASSERT(inSuite, - config.handle->AvailableDataLength() == ((config.end_buffer - config.payload_ptr) - config.init_len)); + config.handle->AvailableDataLength() == + static_cast(static_cast(config.end_buffer - config.payload_ptr) - + static_cast(config.init_len))); } } @@ -861,7 +876,7 @@ void PacketBufferTest::CheckCompactHead(nlTestSuite * inSuite, void * inContext) test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); config.handle->SetDataLength(length, config.handle); - const uint16_t data_length = config.handle->DataLength(); + const uint32_t data_length = static_cast(config.handle->DataLength()); config.handle->CompactHead(); @@ -904,14 +919,14 @@ void PacketBufferTest::CheckCompactHead(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, config_2.handle.IsNull()); config_1.handle->SetDataLength(length_1, config_1.handle); - const uint16_t data_length_1 = config_1.handle->DataLength(); + const uint32_t data_length_1 = static_cast(config_1.handle->DataLength()); // This chain will cause buffer_2 to be freed. config_1.handle->next = buffer_2; // Add various lengths to the second buffer buffer_2->SetDataLength(length_2, config_1.handle); - const uint16_t data_length_2 = buffer_2->DataLength(); + const uint32_t data_length_2 = static_cast(buffer_2->DataLength()); config_1.handle->CompactHead(); @@ -1045,8 +1060,8 @@ void PacketBufferTest::CheckConsume(nlTestSuite * inSuite, void * inContext) config_1.handle->SetDataLength(len_1, config_1.handle); config_2.handle->SetDataLength(len_2, config_1.handle); - const uint16_t buf_1_len = config_1.handle->len; - const uint16_t buf_2_len = config_2.handle->len; + const uint32_t buf_1_len = static_cast(config_1.handle->len); + const uint32_t buf_2_len = static_cast(config_2.handle->len); PacketBufferHandle original_handle_1 = config_1.handle.Retain(); NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); // config_1.handle and original_handle_1 @@ -1117,7 +1132,7 @@ void PacketBufferTest::CheckEnsureReservedSize(nlTestSuite * inSuite, void * inC const uint16_t length = theContext->lengths[i]; test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); - const uint16_t kAllocSize = config.handle->AllocSize(); + const uint32_t kAllocSize = static_cast(config.handle->AllocSize()); uint16_t reserved_size = config.reserved_size; if (PacketBuffer::kStructureSize + config.reserved_size > kAllocSize) @@ -1163,7 +1178,7 @@ void PacketBufferTest::CheckAlignPayload(nlTestSuite * inSuite, void * inContext for (size_t n = 0; n < theContext->length_count; ++n) { test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); - const uint16_t kAllocSize = config.handle->AllocSize(); + const uint32_t kAllocSize = static_cast(config.handle->AllocSize()); if (theContext->lengths[n] == 0) { @@ -1171,17 +1186,17 @@ void PacketBufferTest::CheckAlignPayload(nlTestSuite * inSuite, void * inContext continue; } - uint16_t reserved_size = config.reserved_size; + uint32_t reserved_size = config.reserved_size; if (config.reserved_size > kAllocSize) { reserved_size = kAllocSize; } - const uint16_t payload_offset = + const uint32_t payload_offset = static_cast(reinterpret_cast(config.handle->Start()) % theContext->lengths[n]); - uint16_t payload_shift = 0; + uint32_t payload_shift = 0; if (payload_offset > 0) - payload_shift = static_cast(theContext->lengths[n] - payload_offset); + payload_shift = static_cast(theContext->lengths[n] - payload_offset); if (payload_shift <= kAllocSize - reserved_size) { @@ -1307,10 +1322,10 @@ void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) test->PrepareTestBuffer(&config_1, kAllowHandleReuse); test->PrepareTestBuffer(&config_2, kAllowHandleReuse); - const uint16_t length_1 = config_1.handle->MaxDataLength(); - const uint16_t length_2 = config_2.handle->MaxDataLength(); + const size_t length_1 = config_1.handle->MaxDataLength(); + const size_t length_2 = config_2.handle->MaxDataLength(); const size_t length_sum = length_1 + length_2; - const uint16_t length_total = static_cast(length_sum); + const uint32_t length_total = static_cast(length_sum); NL_TEST_ASSERT(inSuite, length_total == length_sum); memcpy(config_1.handle->Start(), payloads, length_1); @@ -1338,7 +1353,7 @@ void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); // Check that running off the end of a corrupt buffer chain is detected. - if (length_total < UINT16_MAX) + if (length_total < UINT32_MAX) { // First case: TotalLength() is wrong. config_1.handle->tot_len = static_cast(config_1.handle->tot_len + 1); diff --git a/src/transport/SecureMessageCodec.cpp b/src/transport/SecureMessageCodec.cpp index 9c08d535ff57a3..b5617e72996e5a 100644 --- a/src/transport/SecureMessageCodec.cpp +++ b/src/transport/SecureMessageCodec.cpp @@ -43,13 +43,13 @@ CHIP_ERROR Encrypt(const CryptoContext & context, CryptoContext::ConstNonceView VerifyOrReturnError(!msgBuf->HasChainedBuffer(), CHIP_ERROR_INVALID_MESSAGE_LENGTH); VerifyOrReturnError(msgBuf->TotalLength() <= kMaxAppMessageLen, CHIP_ERROR_MESSAGE_TOO_LONG); - static_assert(std::is_sameTotalLength()), uint16_t>::value, + static_assert(std::is_sameTotalLength()), size_t>::value, "Addition to generate payloadLength might overflow"); ReturnErrorOnFailure(payloadHeader.EncodeBeforeData(msgBuf)); uint8_t * data = msgBuf->Start(); - uint16_t totalLen = msgBuf->TotalLength(); + uint32_t totalLen = static_cast(msgBuf->TotalLength()); MessageAuthenticationCode mac; ReturnErrorOnFailure(context.Encrypt(data, totalLen, data, nonce, packetHeader, mac)); @@ -57,8 +57,8 @@ CHIP_ERROR Encrypt(const CryptoContext & context, CryptoContext::ConstNonceView uint16_t taglen = 0; ReturnErrorOnFailure(mac.Encode(packetHeader, &data[totalLen], msgBuf->AvailableDataLength(), &taglen)); - VerifyOrReturnError(CanCastTo(totalLen + taglen), CHIP_ERROR_INTERNAL); - msgBuf->SetDataLength(static_cast(totalLen + taglen)); + VerifyOrReturnError(CanCastTo(totalLen + taglen), CHIP_ERROR_INTERNAL); + msgBuf->SetDataLength(static_cast(totalLen + taglen)); return CHIP_NO_ERROR; } @@ -69,7 +69,7 @@ CHIP_ERROR Decrypt(const CryptoContext & context, CryptoContext::ConstNonceView ReturnErrorCodeIf(msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); uint8_t * data = msg->Start(); - uint16_t len = msg->DataLength(); + uint32_t len = static_cast(msg->DataLength()); PacketBufferHandle origMsg; #if CHIP_SYSTEM_CONFIG_USE_LWIP diff --git a/src/transport/SessionManager.cpp b/src/transport/SessionManager.cpp index 085fda948629c7..added4e99d5740 100644 --- a/src/transport/SessionManager.cpp +++ b/src/transport/SessionManager.cpp @@ -877,7 +877,7 @@ void SessionManager::SecureGroupMessageDispatch(const PacketHeader & partialPack // Extract MIC from the end of the message. uint8_t * data = msg->Start(); - uint16_t len = msg->DataLength(); + size_t len = msg->DataLength(); uint16_t footerLen = partialPacketHeader.MICTagLength(); VerifyOrReturn(footerLen <= len); diff --git a/src/transport/raw/MessageHeader.cpp b/src/transport/raw/MessageHeader.cpp index 2947756b644d1a..ab769abc387ae9 100644 --- a/src/transport/raw/MessageHeader.cpp +++ b/src/transport/raw/MessageHeader.cpp @@ -156,12 +156,12 @@ CHIP_ERROR PacketHeader::DecodeFixedCommon(Encoding::LittleEndian::Reader & read CHIP_ERROR PacketHeader::DecodeFixed(const System::PacketBufferHandle & buf) { const uint8_t * const data = buf->Start(); - uint16_t size = buf->DataLength(); + size_t size = buf->DataLength(); LittleEndian::Reader reader(data, size); return DecodeFixedCommon(reader); } -CHIP_ERROR PacketHeader::Decode(const uint8_t * const data, uint16_t size, uint16_t * decode_len) +CHIP_ERROR PacketHeader::Decode(const uint8_t * const data, size_t size, uint16_t * decode_len) { CHIP_ERROR err = CHIP_NO_ERROR; LittleEndian::Reader reader(data, size); @@ -247,7 +247,7 @@ CHIP_ERROR PacketHeader::DecodeAndConsume(const System::PacketBufferHandle & buf return CHIP_NO_ERROR; } -CHIP_ERROR PayloadHeader::Decode(const uint8_t * const data, uint16_t size, uint16_t * decode_len) +CHIP_ERROR PayloadHeader::Decode(const uint8_t * const data, size_t size, uint16_t * decode_len) { CHIP_ERROR err = CHIP_NO_ERROR; LittleEndian::Reader reader(data, size); @@ -312,7 +312,7 @@ CHIP_ERROR PayloadHeader::DecodeAndConsume(const System::PacketBufferHandle & bu return CHIP_NO_ERROR; } -CHIP_ERROR PacketHeader::Encode(uint8_t * data, uint16_t size, uint16_t * encode_size) const +CHIP_ERROR PacketHeader::Encode(uint8_t * data, size_t size, uint16_t * encode_size) const { VerifyOrReturnError(size >= EncodeSizeBytes(), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(!(mDestinationNodeId.HasValue() && mDestinationGroupId.HasValue()), CHIP_ERROR_INTERNAL); @@ -364,9 +364,9 @@ CHIP_ERROR PacketHeader::EncodeBeforeData(const System::PacketBufferHandle & buf return CHIP_NO_ERROR; } -CHIP_ERROR PayloadHeader::Encode(uint8_t * data, uint16_t size, uint16_t * encode_size) const +CHIP_ERROR PayloadHeader::Encode(uint8_t * data, size_t size, uint16_t * encode_size) const { - VerifyOrReturnError(size >= EncodeSizeBytes(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(size >= static_cast(EncodeSizeBytes()), CHIP_ERROR_INVALID_ARGUMENT); uint8_t * p = data; const uint8_t header = mExchangeFlags.Raw(); @@ -404,7 +404,7 @@ CHIP_ERROR PayloadHeader::EncodeBeforeData(const System::PacketBufferHandle & bu return CHIP_NO_ERROR; } -CHIP_ERROR MessageAuthenticationCode::Decode(const PacketHeader & packetHeader, const uint8_t * const data, uint16_t size, +CHIP_ERROR MessageAuthenticationCode::Decode(const PacketHeader & packetHeader, const uint8_t * const data, size_t size, uint16_t * decode_len) { const uint16_t taglen = packetHeader.MICTagLength(); @@ -419,7 +419,7 @@ CHIP_ERROR MessageAuthenticationCode::Decode(const PacketHeader & packetHeader, return CHIP_NO_ERROR; } -CHIP_ERROR MessageAuthenticationCode::Encode(const PacketHeader & packetHeader, uint8_t * data, uint16_t size, +CHIP_ERROR MessageAuthenticationCode::Encode(const PacketHeader & packetHeader, uint8_t * data, size_t size, uint16_t * encode_size) const { uint8_t * p = data; diff --git a/src/transport/raw/MessageHeader.h b/src/transport/raw/MessageHeader.h index 7c637fa782d957..ef4f86d3993793 100644 --- a/src/transport/raw/MessageHeader.h +++ b/src/transport/raw/MessageHeader.h @@ -418,13 +418,13 @@ class PacketHeader * CHIP_ERROR_INVALID_ARGUMENT on insufficient buffer size * CHIP_ERROR_VERSION_MISMATCH if header version is not supported. */ - CHIP_ERROR Decode(const uint8_t * data, uint16_t size, uint16_t * decode_size); + CHIP_ERROR Decode(const uint8_t * data, size_t size, uint16_t * decode_size); /** * A version of Decode that uses the type system to determine available * space. */ - template + template inline CHIP_ERROR Decode(const uint8_t (&data)[N], uint16_t * decode_size) { return Decode(data, N, decode_size); @@ -448,13 +448,13 @@ class PacketHeader * Possible failures: * CHIP_ERROR_INVALID_ARGUMENT on insufficient buffer size */ - CHIP_ERROR Encode(uint8_t * data, uint16_t size, uint16_t * encode_size) const; + CHIP_ERROR Encode(uint8_t * data, size_t size, uint16_t * encode_size) const; /** * A version of Encode that uses the type system to determine available * space. */ - template + template inline CHIP_ERROR Encode(uint8_t (&data)[N], uint16_t * encode_size) const { return Encode(data, N, encode_size); @@ -662,13 +662,13 @@ class PayloadHeader * CHIP_ERROR_INVALID_ARGUMENT on insufficient buffer size * CHIP_ERROR_VERSION_MISMATCH if header version is not supported. */ - CHIP_ERROR Decode(const uint8_t * data, uint16_t size, uint16_t * decode_size); + CHIP_ERROR Decode(const uint8_t * data, size_t size, uint16_t * decode_size); /** * A version of Decode that uses the type system to determine available * space. */ - template + template inline CHIP_ERROR Decode(const uint8_t (&data)[N], uint16_t * decode_size) { return Decode(data, N, decode_size); @@ -692,13 +692,13 @@ class PayloadHeader * Possible failures: * CHIP_ERROR_INVALID_ARGUMENT on insufficient buffer size */ - CHIP_ERROR Encode(uint8_t * data, uint16_t size, uint16_t * encode_size) const; + CHIP_ERROR Encode(uint8_t * data, size_t size, uint16_t * encode_size) const; /** * A version of Encode that uses the type system to determine available * space. */ - template + template inline CHIP_ERROR Encode(uint8_t (&data)[N], uint16_t * decode_size) const { return Encode(data, N, decode_size); @@ -779,7 +779,7 @@ class MessageAuthenticationCode * CHIP_ERROR_INVALID_ARGUMENT on insufficient buffer size * CHIP_ERROR_VERSION_MISMATCH if header version is not supported. */ - CHIP_ERROR Decode(const PacketHeader & packetHeader, const uint8_t * data, uint16_t size, uint16_t * decode_size); + CHIP_ERROR Decode(const PacketHeader & packetHeader, const uint8_t * data, size_t size, uint16_t * decode_size); /** * Encodes the Messae Authentication Tag into the given buffer. @@ -794,7 +794,7 @@ class MessageAuthenticationCode * Possible failures: * CHIP_ERROR_INVALID_ARGUMENT on insufficient buffer size */ - CHIP_ERROR Encode(const PacketHeader & packetHeader, uint8_t * data, uint16_t size, uint16_t * encode_size) const; + CHIP_ERROR Encode(const PacketHeader & packetHeader, uint8_t * data, size_t size, uint16_t * encode_size) const; private: /// Message authentication tag generated at encryption of the message.