[PATCH 9/9] tools/include: fix signed shift overflow in 32-bit unaligned accessors
From: lzhan011
Date: Mon Oct 05 2026 - 06:48:53 EST
From: lzhan011 <zhangleizhen645@xxxxxxxxx>
In __get_unaligned_le32() and __get_unaligned_be32() the most significant
byte is promoted to int before being shifted left by 24. If the byte is
0x80 or higher, the result does not fit in an int, which is undefined
behaviour. This happens for every kernel virtual address, e.g. in
sorttable, and UBSan reports:
tools/include/tools/le_byteshift.h:14: runtime error: left shift of
255 by 24 places cannot be represented in type 'int'
Cast the byte to uint32_t before shifting.
Fixes: a07f7672d7cf ("tools/include: Add byteshift headers for endian access")
Assisted-by: Claude:claude-opus-5-5 UBSan
Signed-off-by: lzhan011 <zhangleizhen645@xxxxxxxxx>
---
tools/include/tools/be_byteshift.h | 2 +-
tools/include/tools/le_byteshift.h | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/tools/include/tools/be_byteshift.h b/tools/include/tools/be_byteshift.h
index f7d1d1698..2bda8d199 100644
--- a/tools/include/tools/be_byteshift.h
+++ b/tools/include/tools/be_byteshift.h
@@ -11,7 +11,7 @@ static inline uint16_t __get_unaligned_be16(const uint8_t *p)
static inline uint32_t __get_unaligned_be32(const uint8_t *p)
{
- return p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
+ return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
}
static inline uint64_t __get_unaligned_be64(const uint8_t *p)
diff --git a/tools/include/tools/le_byteshift.h b/tools/include/tools/le_byteshift.h
index dc8565f39..e5c78a48a 100644
--- a/tools/include/tools/le_byteshift.h
+++ b/tools/include/tools/le_byteshift.h
@@ -11,7 +11,7 @@ static inline uint16_t __get_unaligned_le16(const uint8_t *p)
static inline uint32_t __get_unaligned_le32(const uint8_t *p)
{
- return p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24;
+ return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;
}
static inline uint64_t __get_unaligned_le64(const uint8_t *p)
--
2.34.1