Browse Source

nice: fix overflow checking in int_add_no_wrap()

In C, signed integer overflow is undefined behavior.  Many compilers
optimize away checks like `a + b < a'.

Use safe precondition testing instead.

Signed-off-by: Xi Wang <xi@mit.edu>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
Xi Wang 11 years ago
parent
commit
79cd5fb435
1 changed files with 5 additions and 5 deletions
  1. 5 5
      libc/sysdeps/linux/common/nice.c

+ 5 - 5
libc/sysdeps/linux/common/nice.c

@@ -25,15 +25,15 @@ static __inline__ _syscall1(int, __syscall_nice, int, incr)
 
 static __inline__ int int_add_no_wrap(int a, int b)
 {
-	int s = a + b;
-
 	if (b < 0) {
-		if (s > a) s = INT_MIN;
+		if (a < INT_MIN - b)
+			return INT_MIN;
 	} else {
-		if (s < a) s = INT_MAX;
+		if (a > INT_MAX - b)
+			return INT_MAX;
 	}
 
-	return s;
+	return a + b;
 }
 
 static __inline__ int __syscall_nice(int incr)