[PATCH] x86/lib: Avoid undefined behavior on sign flip

From: Bartosz Szreder
Date: Wed Jan 31 2024 - 19:23:21 EST


If argument to function num_digits() is equal to INT_MIN, the sign change
operation results in undefined behavior due to signed integer overflow.

Avoid that issue by converting to unsigned type.

Signed-off-by: Bartosz Szreder <zgredder@xxxxxxxxxxx>
---
arch/x86/lib/misc.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/arch/x86/lib/misc.c b/arch/x86/lib/misc.c
index 40b81c338ae5..778ab6d27372 100644
--- a/arch/x86/lib/misc.c
+++ b/arch/x86/lib/misc.c
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
#include <asm/misc.h>
+#include <linux/limits.h>

/*
* Count the digits of @val including a possible sign.
@@ -9,14 +10,17 @@
int num_digits(int val)
{
long long m = 10;
+ unsigned int tmp = val;
int d = 1;

if (val < 0) {
d++;
- val = -val;
+
+ if (val != INT_MIN)
+ tmp = -val;
}

- while (val >= m) {
+ while (tmp >= m) {
m *= 10;
d++;
}
--
2.43.0