public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH] x86/lib: Fix num_digits() signed overflow for INT_MIN
@ 2026-01-20  9:42 David Desobry
  2026-01-20 16:23 ` H. Peter Anvin
  0 siblings, 1 reply; 15+ messages in thread
From: David Desobry @ 2026-01-20  9:42 UTC (permalink / raw)
  To: tglx, mingo, bp, dave.hansen; +Cc: x86, hpa, linux-kernel, David Desobry

In num_digits(), the negation of the input value "val = -val"
causes undefined behavior when val is INT_MIN, as its absolute
value cannot be represented as a signed 32-bit integer.

This leads to incorrect results (returning 2 instead of 11).
By promoting the value to long long before negation, we ensure
the absolute value is correctly handled.

Signed-off-by: David Desobry <david.desobry@formalgen.com>
---
 arch/x86/lib/misc.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/arch/x86/lib/misc.c b/arch/x86/lib/misc.c
index 40b81c338ae5..c975db6ccb9f 100644
--- a/arch/x86/lib/misc.c
+++ b/arch/x86/lib/misc.c
@@ -8,15 +8,16 @@
  */
 int num_digits(int val)
 {
+	long long v = val;
 	long long m = 10;
 	int d = 1;
 
-	if (val < 0) {
+	if (v < 0) {
 		d++;
-		val = -val;
+		v = -v;
 	}
 
-	while (val >= m) {
+	while (v >= m) {
 		m *= 10;
 		d++;
 	}
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 15+ messages in thread

end of thread, other threads:[~2026-01-21 10:59 UTC | newest]

Thread overview: 15+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-01-20  9:42 [PATCH] x86/lib: Fix num_digits() signed overflow for INT_MIN David Desobry
2026-01-20 16:23 ` H. Peter Anvin
2026-01-20 16:40   ` Borislav Petkov
2026-01-20 18:02     ` H. Peter Anvin
2026-01-20 18:17       ` H. Peter Anvin
2026-01-20 19:16         ` Borislav Petkov
2026-01-20 19:50           ` H. Peter Anvin
2026-01-20 20:13             ` Borislav Petkov
2026-01-21 10:59               ` David Laight
     [not found]           ` <14738799-afb2-428b-9829-f1ed038f3872@formalgen.com>
2026-01-20 20:24             ` H. Peter Anvin
2026-01-20 21:22               ` Borislav Petkov
2026-01-20 21:21             ` Borislav Petkov
2026-01-20 17:48   ` David Desobry
2026-01-20 22:15     ` David Laight
2026-01-20 18:58   ` David Laight

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox