x86/lib: Avoid undefined behavior on sign flip

Message ID 20240201001033.9483-1-zgredder@zgredder.pl
State New
Headers
Series x86/lib: Avoid undefined behavior on sign flip |

Commit Message

Bartosz Szreder Feb. 1, 2024, 12:10 a.m. UTC
  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@zgredder.pl>
---
 arch/x86/lib/misc.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
  

Patch

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++;
 	}