From aff159f40c1abc150bf58c3644b42b0d7d19d9e7 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Mon, 26 Feb 2024 18:37:46 -0800 Subject: [PATCH] [link-quality] prevent overflow in `LqiAverager` calculation (#9876) This commit updates `LqiAverager::Add()` to explicitly use a `uint16_t` local variable for calculating the new running average. This prevents potential overflows. --- src/core/thread/link_quality.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/core/thread/link_quality.cpp b/src/core/thread/link_quality.cpp index b2adbdcc7..67475401b 100644 --- a/src/core/thread/link_quality.cpp +++ b/src/core/thread/link_quality.cpp @@ -117,7 +117,8 @@ exit: void LqiAverager::Add(uint8_t aLqi) { - uint8_t count; + uint8_t count; + uint16_t newAverage; if (mCount < NumericLimits::kMax) { @@ -126,7 +127,10 @@ void LqiAverager::Add(uint8_t aLqi) count = Min(static_cast(1 << kCoeffBitShift), mCount); - mAverage = static_cast(((mAverage * (count - 1)) + aLqi) / count); + newAverage = mAverage; + newAverage = (newAverage * (count - 1) + aLqi) / count; + + mAverage = static_cast(newAverage); } void LinkQualityInfo::Clear(void)