From patchwork Mon Nov 9 14:56:31 2015 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Peter Maydell X-Patchwork-Id: 56226 Delivered-To: patches@linaro.org Received: by 10.112.155.196 with SMTP id vy4csp224989lbb; Mon, 9 Nov 2015 06:56:32 -0800 (PST) X-Received: by 10.194.59.108 with SMTP id y12mr3644548wjq.33.1447080992913; Mon, 09 Nov 2015 06:56:32 -0800 (PST) Return-Path: Received: from mnementh.archaic.org.uk (mnementh.archaic.org.uk. [2001:8b0:1d0::1]) by mx.google.com with ESMTPS id f19si18549687wjr.157.2015.11.09.06.56.32 for (version=TLSv1.2 cipher=RC4-SHA bits=128/128); Mon, 09 Nov 2015 06:56:32 -0800 (PST) Received-SPF: pass (google.com: best guess record for domain of pm215@archaic.org.uk designates 2001:8b0:1d0::1 as permitted sender) client-ip=2001:8b0:1d0::1; Authentication-Results: mx.google.com; spf=pass (google.com: best guess record for domain of pm215@archaic.org.uk designates 2001:8b0:1d0::1 as permitted sender) smtp.mailfrom=pm215@archaic.org.uk Received: from pm215 by mnementh.archaic.org.uk with local (Exim 4.80) (envelope-from ) id 1Zvnrz-0006Vc-Ak; Mon, 09 Nov 2015 14:56:31 +0000 From: Peter Maydell To: qemu-devel@nongnu.org Cc: patches@linaro.org, "Michael S. Tsirkin" , Paolo Bonzini , Aaron Elkins Subject: [PATCH for-2.5] hw/timer/hpet.c: Avoid signed integer overflow which results in bugs on OSX Date: Mon, 9 Nov 2015 14:56:31 +0000 Message-Id: <1447080991-24995-1-git-send-email-peter.maydell@linaro.org> X-Mailer: git-send-email 1.7.10.4 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 Signed-off-by: Peter Maydell --- hw/timer/hpet.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) -- 2.6.2 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)