Skip to contentSkip to conversation

kstrtox: delete division from inner parsing loop

PATCH In review Alexey Dobriyan 2 participants 2 messages Jul 3 Library code

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 kstrtox: delete division from inner parsing loop

Overflow conditions can be checked on the fly resulting in at most 2 very predictable branches and zero division instructions:

_parse_integer_limit:
...
mov rax, rdx
mul rsi
seto bl
add rax, rcx
mov rdx, rax
setb al
...

---
 lib/kstrtox.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)
lib/kstrtox.c +5 -9
index 97be2a39f537..efd55db0533a 100644
@@ -71,15 +71,11 @@ unsigned int _parse_integer_limit(const char *s, unsigned int base, unsigned lon
 
 		if (val >= base)
 			break;
-		/*
-		 * Check for overflow only if we are within range of
-		 * it in the max base we support (16)
-		 */
-		if (unlikely(res & (~0ull << 60))) {
-			if (res > div_u64(ULLONG_MAX - val, base))
-				rv |= KSTRTOX_OVERFLOW;
-		}
-		res = res * base + val;
+
+		if (check_mul_overflow(res, base, &res))
+			rv |= KSTRTOX_OVERFLOW;
+		if (check_add_overflow(res, val, &res))
+			rv |= KSTRTOX_OVERFLOW;
 		rv++;
 		s++;
 	}
Signature · 1 line
2.54.0
#1 lore raw
Quoted 11 lines · Alexey Dobriyan

Overflow conditions can be checked on the fly resulting in at most 2 very predictable branches and zero division instructions:

_parse_integer_limit:
...
mov rax, rdx
mul rsi
seto bl
add rax, rcx
mov rdx, rax
setb al

Trust my word, there is a huge world beyond x86.

Dmitry