Skip to contentSkip to conversation

bitops: avoid integer overflow in GENMASK(_ULL)

PATCH New [email protected] 1 participant 1 message Sep 8, 2017 Bitops API

lore
Share & tools
lore
#0 lore raw

PATCH 65/126 bitops: avoid integer overflow in GENMASK(_ULL)

From: Matthias Kaehlcke <[email protected]>
Subject: bitops: avoid integer overflow in GENMASK(_ULL)

GENMASK(_ULL) performs a left-shift of ~0UL(L), which technically results in an integer overflow. clang raises a warning if the overflow occurs in a preprocessor expression. Clear the low-order bits through a substraction instead of the left-shift to avoid the overflow.

(akpm: no change in .text size in my testing)

---

 include/linux/bitops.h |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
include/linux/bitops.h renamed from include/linux/bitops.h~bitops-avoid-integer-overflow-in-genmask_ull +3 -2
diff -puN include/linux/bitops.h~bitops-avoid-integer-overflow-in-genmask_ull include/linux/bitops.h
@@ -19,10 +19,11 @@
  * GENMASK_ULL(39, 21) gives us the 64bit vector 0x000000ffffe00000.
  */
 #define GENMASK(h, l) \
-	(((~0UL) << (l)) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
+	(((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
 
 #define GENMASK_ULL(h, l) \
-	(((~0ULL) << (l)) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
+	(((~0ULL) - (1ULL << (l)) + 1) & \
+	 (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
 
 extern unsigned int __sw_hweight8(unsigned int w);
 extern unsigned int __sw_hweight16(unsigned int w);

_