[<prev] [next>] [day] [month] [year] [list]
Message-ID: <bc0958d7-385f-49b5-97e9-6355b29a2502@p183>
Date: Sun, 22 Oct 2023 22:39:54 +0300
From: Alexey Dobriyan <adobriyan@...il.com>
To: linux-kernel@...r.kernel.org
Cc: torvalds@...r.kernel.org
Subject: PSA: BITS_TO_LONGS() most likely returns size_t, not what you think
I wrote the following code today (don't ask):
for (int i = 0; i <= BITS_TO_LONGS(NR_CPUS) - 2; i += 1) {
}
only to get near infinite loop. Note that NR_CPUS is "int".
This is because BITS_TO_LONGS() and __KERNEL_DIV_ROUND_UP() macros work
together to promote everything to "size_t". The loop essientially
becomes:
for (int i = 0; i <= (size_t)-1; i += 1) {
}
This is easily fixable by doing very sketchy and obvious thing.
--- a/include/linux/bitops.h
+++ b/include/linux/bitops.h
@@ -16,7 +16,7 @@
# define aligned_byte_mask(n) (~0xffUL << (BITS_PER_LONG - 8 - 8*(n)))
#endif
-#define BITS_PER_TYPE(type) (sizeof(type) * BITS_PER_BYTE)
+#define BITS_PER_TYPE(type) ((int)sizeof(type) * BITS_PER_BYTE)
#define BITS_TO_LONGS(nr) __KERNEL_DIV_ROUND_UP(nr, BITS_PER_TYPE(long))
#define BITS_TO_U64(nr) __KERNEL_DIV_ROUND_UP(nr, BITS_PER_TYPE(u64))
#define BITS_TO_U32(nr) __KERNEL_DIV_ROUND_UP(nr, BITS_PER_TYPE(u32))
Ideally __KERNEL_DIV_ROUND_UP() should return the type of the first
argument but this stuff is UAPI header which complicates things.
Powered by blists - more mailing lists