qemu-devel.nongnu.org archive mirror
 help / color / mirror / Atom feed
* [Qemu-devel] [PATCH for-2.5] hw/timer/hpet.c: Avoid signed integer overflow which results in bugs on OSX
@ 2015-11-09 14:56 Peter Maydell
  2015-11-09 15:25 ` Paolo Bonzini
                   ` (2 more replies)
  0 siblings, 3 replies; 11+ messages in thread
From: Peter Maydell @ 2015-11-09 14:56 UTC (permalink / raw)
  To: qemu-devel; +Cc: Aaron Elkins, Paolo Bonzini, Michael S. Tsirkin, patches

Signed integer overflow in C is undefined behaviour, and the compiler
is at liberty to assume it can never happen and optimize accordingly.
In particular, the subtractions in hpet_time_after() and hpet_time_after64()
were causing OSX clang to optimize the code such that it was prone to
hangs and complaints about the main loop stalling (presumably because
we were spending all our time trying to service very high frequency
HPET timer callbacks). The clang sanitizer confirms the UB:

hw/timer/hpet.c:119:26: runtime error: signed integer overflow: -2146967296 - 2147003978 cannot be represented in type 'int'

Fix this by doing the subtraction as an unsigned operation and then
converting to signed for the comparison.

Reported-by: Aaron Elkins <threcius@yahoo.com>
Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
---
 hw/timer/hpet.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/hw/timer/hpet.c b/hw/timer/hpet.c
index 3037bef..7f0391c 100644
--- a/hw/timer/hpet.c
+++ b/hw/timer/hpet.c
@@ -116,12 +116,12 @@ static uint32_t timer_enabled(HPETTimer *t)
 
 static uint32_t hpet_time_after(uint64_t a, uint64_t b)
 {
-    return ((int32_t)(b) - (int32_t)(a) < 0);
+    return ((int32_t)(b - a) < 0);
 }
 
 static uint32_t hpet_time_after64(uint64_t a, uint64_t b)
 {
-    return ((int64_t)(b) - (int64_t)(a) < 0);
+    return ((int64_t)(b - a) < 0);
 }
 
 static uint64_t ticks_to_ns(uint64_t value)
-- 
2.6.2

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

end of thread, other threads:[~2015-11-10 11:58 UTC | newest]

Thread overview: 11+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2015-11-09 14:56 [Qemu-devel] [PATCH for-2.5] hw/timer/hpet.c: Avoid signed integer overflow which results in bugs on OSX Peter Maydell
2015-11-09 15:25 ` Paolo Bonzini
2015-11-09 15:26   ` Peter Maydell
2015-11-09 16:27     ` Peter Maydell
2015-11-09 20:17 ` Michael S. Tsirkin
2015-11-10 10:04   ` Peter Maydell
2015-11-10 11:57     ` Michael S. Tsirkin
2015-11-09 22:25 ` Laszlo Ersek
2015-11-10  8:57   ` Laszlo Ersek
2015-11-10  9:26     ` Paolo Bonzini
2015-11-10  9:51       ` Laszlo Ersek

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).