[PATCH] tmon: Fix undefined behavior in left shift

Kuan-Wei Chiu posted 1 patch 1 month ago
tools/thermal/tmon/tmon.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH] tmon: Fix undefined behavior in left shift
Posted by Kuan-Wei Chiu 1 month ago
Using 1 << j when j reaches 31 triggers undefined behavior because
the constant 1 is of type int, and shifting it left by 31 exceeds
the range of signed int. UBSAN reports:

tmon.c:174:54: runtime error: left shift of 1 by 31 places cannot be represented in type 'int'

According to the C11 standard:

"If E1 has a signed type and E1 x 2^E2 is not representable in the
result type, the behavior is undefined."

Fix this by using 1U << j, ensuring the shift is performed on an
unsigned type where all 32 bits are representable.

Fixes: 94f69966faf8 ("tools/thermal: Introduce tmon, a tool for thermal subsystem")
Signed-off-by: Kuan-Wei Chiu <visitorckw@gmail.com>
---
 tools/thermal/tmon/tmon.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/thermal/tmon/tmon.c b/tools/thermal/tmon/tmon.c
index 7eb3216a27f4..ef67cd1a4861 100644
--- a/tools/thermal/tmon/tmon.c
+++ b/tools/thermal/tmon/tmon.c
@@ -171,7 +171,7 @@ static void prepare_logging(void)
 
 		memset(binding_str, 0, sizeof(binding_str));
 		for (j = 0; j < 32; j++)
-			binding_str[j] = (ptdata.tzi[i].cdev_binding & (1 << j)) ?
+			binding_str[j] = (ptdata.tzi[i].cdev_binding & (1U << j)) ?
 				'1' : '0';
 
 		fprintf(tmon_log, "#thermal zone %s%02d cdevs binding: %32s\n",
-- 
2.34.1
Re: [PATCH] tmon: Fix undefined behavior in left shift
Posted by Kuan-Wei Chiu 1 month ago
On Mon, Sep 01, 2025 at 10:47:56PM +0800, Kuan-Wei Chiu wrote:
> Using 1 << j when j reaches 31 triggers undefined behavior because
> the constant 1 is of type int, and shifting it left by 31 exceeds
> the range of signed int. UBSAN reports:
> 
> tmon.c:174:54: runtime error: left shift of 1 by 31 places cannot be represented in type 'int'
> 

I forgot to mention in the commit message that the UBSAN report was
triggered when running sudo ./tmon -l. Let me know if you'd like me
to include that detail, and I can update and resend as v2.

Regards,
Kuan-Wei