From d7000862e8ca14e6521942a6d63e5e6b91437931 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Mon, 23 Feb 2026 08:26:30 -0800 Subject: [PATCH] [message] update `SetOffset()` and `MoveOffset()` to clamp offset (#12522) Updates `SetOffset()` to ensure the offset is always clamped to the current message length. This guarantees that the offset remains valid and does not exceed the message size. Updates `MoveOffset()` to accept `int16_t` as the delta and ensures the calculated new offset is clamped within `0` and `NumericLimits::kMax` before setting it. Updates `SetLength()` to rely on the new `SetOffset()` behavior to automatically adjust the offset when the message length is reduced. --- src/core/common/message.cpp | 21 ++++++++------------- src/core/common/message.hpp | 2 +- src/core/instance/instance.hpp | 2 ++ 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/core/common/message.cpp b/src/core/common/message.cpp index 06a498918..6565f2891 100644 --- a/src/core/common/message.cpp +++ b/src/core/common/message.cpp @@ -281,10 +281,7 @@ Error Message::SetLength(uint16_t aLength) GetMetadata().mLength = aLength; // Correct the offset in case shorter length is set. - if (GetOffset() > aLength) - { - SetOffset(aLength); - } + SetOffset(GetOffset()); exit: return error; @@ -314,18 +311,16 @@ uint8_t Message::GetBufferCount(void) const return rval; } -void Message::MoveOffset(int aDelta) +void Message::MoveOffset(int16_t aDelta) { - OT_ASSERT(GetOffset() + aDelta <= GetLength()); - GetMetadata().mOffset += static_cast(aDelta); - OT_ASSERT(GetMetadata().mOffset <= GetLength()); + int32_t newOffset = static_cast(GetOffset()) + aDelta; + + newOffset = Clamp(newOffset, 0, NumericLimits::kMax); + + SetOffset(static_cast(newOffset)); } -void Message::SetOffset(uint16_t aOffset) -{ - OT_ASSERT(aOffset <= GetLength()); - GetMetadata().mOffset = aOffset; -} +void Message::SetOffset(uint16_t aOffset) { GetMetadata().mOffset = Min(aOffset, GetLength()); } uint16_t Message::DetermineLengthAfterOffset(void) const { diff --git a/src/core/common/message.hpp b/src/core/common/message.hpp index 251752c36..f2bc6b209 100644 --- a/src/core/common/message.hpp +++ b/src/core/common/message.hpp @@ -528,7 +528,7 @@ public: * * @param[in] aDelta The number of bytes to move the current offset, which may be positive or negative. */ - void MoveOffset(int aDelta); + void MoveOffset(int16_t aDelta); /** * Sets the byte offset within the message. diff --git a/src/core/instance/instance.hpp b/src/core/instance/instance.hpp index 143d330af..2529b7f1c 100644 --- a/src/core/instance/instance.hpp +++ b/src/core/instance/instance.hpp @@ -54,6 +54,8 @@ #include "common/log.hpp" #include "common/message.hpp" #include "common/non_copyable.hpp" +#include "common/num_utils.hpp" +#include "common/numeric_limits.hpp" #include "common/random.hpp" #include "common/serial_number.hpp" #include "common/string.hpp"