]> www.infradead.org Git - users/sagi/libnvme.git/commitdiff
types: Cast values to u32 if shift overflows int
authorCaleb Sander <csander@purestorage.com>
Sat, 14 Oct 2023 01:28:33 +0000 (19:28 -0600)
committerDaniel Wagner <wagi@monom.org>
Thu, 2 Nov 2023 13:31:26 +0000 (14:31 +0100)
Bit shifts that overflow the resulting type are undefined behavior in C.
C arithmetic promotes to ints all smaller integer types.
There are several places where a 32-bit unsigned value
is constructed by shifting a u8 or u16 to the most significant bits.
Since this overflows a signed 32-bit integer,
explicitly cast to u32 to avoid the UB.
Technically, an int is allowed to only be 16 bits,
so any shift that could set bit 15 or higher is UB.
But platforms where int is s16 are not very common,
so it's likely not worth the effort to fix the code.

Signed-off-by: Caleb Sander <csander@purestorage.com>
src/nvme/types.h

index e8dbea3774411810a61f1ebe27f993824b098e6b..9aa3ad2eb8a645e7e3357da2c0e862cd178c45f0 100644 (file)
@@ -43,7 +43,7 @@
  * Returns: The 'name' field from 'value'
  */
 #define NVME_SET(value, name) \
-       (((value) & NVME_##name##_MASK) << NVME_##name##_SHIFT)
+       (((__u32)(value) & NVME_##name##_MASK) << NVME_##name##_SHIFT)
 
 /**
  * enum nvme_constants - A place to stash various constant nvme values