From d4fa0abccf6850836523feffcf2b51871199325b Mon Sep 17 00:00:00 2001 From: Kevin Schoedel Date: Mon, 6 Jun 2022 18:06:54 -0400 Subject: [PATCH] Use EnsureReservedSize() --- src/system/SystemPacketBuffer.cpp | 21 +++++++++------------ src/system/tests/TestSystemPacketBuffer.cpp | 3 ++- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/system/SystemPacketBuffer.cpp b/src/system/SystemPacketBuffer.cpp index 44c86875ca4d69..ce2bc65570aac5 100644 --- a/src/system/SystemPacketBuffer.cpp +++ b/src/system/SystemPacketBuffer.cpp @@ -414,33 +414,30 @@ uint8_t * PacketBuffer::GetReserve(uint16_t aSize, uint16_t aAlignmentMask) return nullptr; } - uintptr_t requestStart = (reserveStart + aAlignmentMask) & ~aAlignmentMask; + const uintptr_t requestStart = (reserveStart + aAlignmentMask) & ~aAlignmentMask; if (requestStart < reserveStart) { // Overflow here means the request can't be satisfied because the alignment is too large. return nullptr; } - const uintptr_t requestEnd = requestStart + aSize; - if (requestEnd < requestStart) + // This cast is safe because the difference is at most `aAlignmentMask`. + const uint16_t reserveAlignmentOffset = static_cast(requestStart - reserveStart); + + // This cast is not safe in itself, but the result is checked. + const uint16_t requestSize = static_cast(reserveAlignmentOffset + aSize); + if (requestSize < aSize) { // Overflow here means the requested size can't possibly fit. return nullptr; } - if (requestEnd <= reinterpret_cast(payload)) - { - // The request fits without moving payload data. - return reinterpret_cast(requestStart); - } - if (requestEnd - reserveStart + len > AllocSize()) + if (!EnsureReservedSize(requestSize)) { - // Not enough space to move the payload. + // The requested size is too large for the available space. return nullptr; } - memmove(reinterpret_cast(requestEnd), payload, len); - payload = reinterpret_cast(requestEnd); return reinterpret_cast(requestStart); } diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index 1c10553805299b..f023fa372fe81b 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -1219,7 +1219,8 @@ void PacketBufferTest::CheckGetReserve(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, config.handle->ReservedSize() == instance.init.reserve_length); NL_TEST_ASSERT(inSuite, config.handle->TotalLength() == instance.init.payload_length); - const uint8_t * const reserve = config.handle->GetReserve(instance.request.length, instance.request.alignment - 1); + const uint8_t * const reserve = + config.handle->GetReserve(instance.request.length, static_cast(instance.request.alignment - 1)); if (instance.expect.success) { NL_TEST_ASSERT(inSuite, reserve != nullptr);