This is an automated email from the ASF dual-hosted git repository. xiaoxiang781216 pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/nuttx.git
commit dc7cc0d67031c2c04c97537d463647d1b08a50b5 Author: ouyangxiangzhen <[email protected]> AuthorDate: Thu Nov 5 09:47:45 2026 +0800 lib/math32: make FLS() width-generic and 64-bit safe on all hosts FLS() only examined the high 32 bits when UINTPTR_MAX > UINT32_MAX, because that branch shifted a size_t: on 32-bit hosts FLS() returned wrong results for inputs above 2^32 (e.g. FLS(1ULL << 40) returned 0 instead of 41), silently breaking LOG2_FLOOR()/LOG2_CEIL() for 64-bit values. Split the bit scan into width layers (FLS32 is the shared building block of FLS64 and FLS128) so that every argument width is handled correctly on every host. FLS() is FLS64 directly when the compiler provides no uint128_t; otherwise sizeof() selects FLS128 for arguments wider than 64 bits. The wider layers widen the argument before shifting, so narrower types never see an oversized shift count. Negative signed values are scanned as their widened two's-complement bit pattern. Like before, the macros evaluate their argument multiple times, so the argument must be free of side effects. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]> --- include/nuttx/lib/math32.h | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/include/nuttx/lib/math32.h b/include/nuttx/lib/math32.h index 1b1a03d86b4..368ebd610bb 100644 --- a/include/nuttx/lib/math32.h +++ b/include/nuttx/lib/math32.h @@ -45,16 +45,10 @@ (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d))) /* Returns one plus the index of the most significant 1-bit of n, - * or if n is zero, returns zero. + * or if n is zero, returns zero. The argument is evaluated multiple + * times and must be free of side effects. */ -#if UINTPTR_MAX > UINT32_MAX -# define FLS(n) ((n) & UINT64_C(0xffffffff00000000) ? 32 + \ - FLS32((size_t)(n) >> 32) : FLS32(n)) -#else -# define FLS(n) FLS32(n) -#endif - #define FLS32(n) ((n) & 0xffff0000 ? 16 + FLS16((n) >> 16) : FLS16(n)) #define FLS16(n) ((n) & 0xff00 ? 8 + FLS8 ((n) >> 8) : FLS8 (n)) #define FLS8(n) ((n) & 0xf0 ? 4 + FLS4 ((n) >> 4) : FLS4 (n)) @@ -62,6 +56,19 @@ #define FLS2(n) ((n) & 0x2 ? 1 + FLS1 ((n) >> 1) : FLS1 (n)) #define FLS1(n) ((n) & 0x1 ? 1 : 0) +/* Widen before shifting so narrow types never see oversized shift counts. */ + +#define FLS64(n) ((uint64_t)(n) >> 32 ? \ + 32 + FLS32((uint32_t)((uint64_t)(n) >> 32)) : FLS32(n)) + +#ifdef __INT128_DEFINED +# define FLS128(n) ((_uint128_t)(n) >> 64 ? \ + 64 + FLS64((uint64_t)((_uint128_t)(n) >> 64)) : FLS64(n)) +# define FLS(n) (sizeof((n)) <= sizeof(uint64_t) ? FLS64(n) : FLS128(n)) +#else +# define FLS(n) FLS64(n) +#endif + /* Checks if an integer is power of two at compile time */ #define IS_POWER_OF_2(n) ((n) > 0 && ((n) & (n - 1)) == 0)
