12 Commits

Author SHA1 Message Date
Abtin Keshavarzian b9bbf71d34 [num-utils] add SafeMultiply() for overflow-safe multiplication (#12220)
This commit introduces `SafeMultiply()` in `num_utils.hpp` as a
centralized and safe way to multiply two unsigned integers while
checking for overflow.

It updates `Coap::TxParameters::IsValid()` to use this new helper for
validating `TxParameters`, replacing a less robust local `Multiply`
implementation.

It also updates `Heap::CAlloc()` to use this function for safely
calculating the total allocation size.

Unit tests are updated to verify `SafeMultiply()` implementation.
2025-12-17 13:01:36 -08:00
Abtin Keshavarzian d952ad9085 [bit-utils] add CountMatchingBits utility function (#11893)
This change introduces a new utility function `CountMatchingBits()` to
calculate the number of matching leading bits between two byte
arrays.

This new fn replaces the now-removed `Ip6::Prefix::MatchLength()`.
The previous implementation was specific to the `Ip6::Prefix`
class. The new generic function is placed in `common/bit_utils` and
is used to update `Ip6::Prefix`, `Ip6::Address`, `Ip4::Cidr`, and
`PrefixTlv`.

A new unit test `test_bit_utils` is added with comprehensive tests for
the new function. The existing tests for `CountBitsInMask` are also
moved into this new test file.
2025-09-03 22:29:15 -07:00
Abtin Keshavarzian aeba105a6f [common] introduce bit_utils.hpp for bit manipulation (#11884)
This commit introduces a new header file, `common/bit_utils.hpp`, to
consolidate bit manipulation utility functions.

These functions were previously located in `common/num_utils.hpp`.
Moving them to a dedicated file improves code organization and
clarity by separating them from general numerical utilities. All
files that used these functions have been updated to include the new
header.
2025-09-02 08:04:28 -07:00
Abtin Keshavarzian 968dbb2a04 [message] check for potential integer overflows (#11834)
This commit adds checks to prevent potential integer overflow issues
within the `Message` class.

Previously, calculations involving message offset and length, such as
`offset + length`, assumed the caller would provide values within a
safe range. However, in some edge cases where larger values are
given, this addition could wrap around. This could lead to incorrect
behavior, potential memory corruption, or assertion failures.

To address this, this change introduces a new generic utility
function, `CanAddSafely()`, to detect unsigned integer addition
overflows. This check is now applied in the following `Message`
methods to validate lengths and offsets before performing
arithmetic:

- `AppendBytes()`: Returns an error if `offset + length` overflows.
- `AppendBytesFromMessage()`: Returns an error on overflow.
- `GetFirstChunk()`: Safely clamps the read length to the available
  message length.
- `WriteBytes()`: Asserts if `offset + length` overflows.

Unit tests for the new `CanAddSafely()` utility are included, covering
`uint8_t` and `uint16_t` cases.
2025-08-20 22:22:39 -07:00
Abtin Keshavarzian a67454f8cc [mle] update kAloc16ServiceEnd and add explicit ALOC16 range check (#11300)
This commit updates `kAloc16ServiceEnd` to `0xfc1f`, aligning it with
recent changes in the Thread specification. The range `0xfc10-0xfc1f`
is now used for service ALOC16 corresponding to the 16 service IDs,
and the range `0xfc20-0xfc2f` is reserved for future use.

It also updates the `NetworkData::Leader::AnycastLookup()` to
explicitly check a given `aAloc16` against the defined ALOC16 ranges.
This replaces the previous model, which assumed that ALOC16 ranges
followed each other sequentially. While this assumption held true
previously, the introduction of the reserved range disrupts this
pattern. The explicit range check ensures correct behavior regardless
of future changes, making it a safer and more robust approach.
2025-02-26 16:16:24 -08:00
Abtin Keshavarzian ada03e6159 [num-utils] add DivideAndRoundUp() helper (#10960)
This commit introduces the `DivideAndRoundUp()` method, which divides
two given unsigned integers and always rounds the result up.
2024-11-22 18:53:45 -08:00
Abtin Keshavarzian e8f3ec0fd3 [common] add Preference helper methods for 2-bit preference value (#8895)
This commit introduces a common `Preference` class which defines
constants and helper methods (e.g., to convert between an `int8_t`
preference and its 2-bit unsigned representation). This is used for
`RoutePreference` in Network Data entries and also for Parent
Priority in `ConnectivityTlv`.
2023-03-23 18:47:57 -07:00
Abtin Keshavarzian 89e403815a [mle] update RouteTlv to check number of allocated IDs (#8463)
This commit contains smaller enhancements in `RouteTlv`:

- `RouteTlv::IsValid()` checks that number of allocated IDs in
  the Router ID Mask is less than max number of routers.
- It also checks that the TLV contains correct number of Route
  Data entries matching the number of allocated router IDs.
- A new method `SetRouteData()` is added to set all the
  data fields (link quality in/out and route cost) for a given
  router index.
- These changes help ensure that messages containing invalid
  `RouteTlv` are rejected (avoid situation where we may have
  more allocated router IDs than max routers).
2022-12-01 19:45:31 -08:00
Abtin Keshavarzian 989a56e96d [link-metrics] update the scaling of link margin and RSSI metrics (#8078)
This commit updates the scaling of the link margin and RSSI metrics.
The metric values are scaled when appended in the message (in a
Report sub-TLV) or when they are read back from received message. The
stored value in `MetricsValues` are changed to be always the actual
metric value (not the scaled value). This ensures that the value are
stored in proper int type (e.g., RSSI is `int8` vs the scaled value
which is `[0,255]`). Methods are added to perform the scaling which
now rounds to closest integer ensuring the reverse scaling gives back
the original value. Unit test is added to validate the scaling
methods.
2022-08-25 11:08:44 -07:00
Abtin Keshavarzian 142b8cf58c [core] add generic three-way comparison function (#8050)
This commit adds a generic `ThreeWayCompare()` function. It also
renames header to `num_utils.hpp` from `min_max.hpp`.
2022-08-22 19:52:02 -07:00
Abtin Keshavarzian fda4549df7 [core] add new generic Min(), Max() and Clamp() functions (#8017)
This commit adds generic helper functions:

- `Min()` to get the minimum of two values,
- `Max()` to get the maximum of two values, and
- `Clamp()` to clamp a value to a given closed range from a minimum
   up to a maximum value. It also adds functions
- `ClampToUint8()` and `ClampToUint16()` to clamp a `uint` value to
   a smaller bit-size (`uint8_t` or `uint16_t`) range.
2022-08-12 09:22:18 -07:00
Abtin Keshavarzian e04c8e3307 [common] add SerialNumber::Is{Greater/Less}>() (#7334)
This commit adds `SerialNumber` class which provides `static` methods
`IsGeater<UintType>()` and `IsLess<UintType()` to compare two serial
numbers, taking into account the wrapping of serial number values
(similar to RFC-1982). This is then used in `MleRouter` and other
modules. This helps us avoid casting of `uint` to `int` for the
comparison (such a casting is undefined behavior in C++11 though
toolchains often implement it as expected). This commit also adds a
unit test `test_serial_number` to validate the new methods.
2022-01-20 16:54:46 -08:00