From 9c648c17493d3f3382adeef809d76a1b027db57f Mon Sep 17 00:00:00 2001 From: Luke Dashjr Date: Wed, 11 Jul 2012 20:10:52 +0000 Subject: [PATCH] Bugfix: Calculate nsec in nmsleep correctly The old algorithm (msecs * 1000000) - (sec / 1000000000) gets total nsec, including seconds, since the sec/1e9 should be multiplying. It's also vulnerable to easy overflows. Using ldiv gets the quotient and remainder in a single operation (at least on x86) and avoids overflow. --- util.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/util.c b/util.c index c6b82048..822e61df 100644 --- a/util.c +++ b/util.c @@ -694,9 +694,11 @@ void nmsleep(unsigned int msecs) { struct timespec twait, tleft; int ret; + ldiv_t d; - tleft.tv_sec = msecs / 1000; - tleft.tv_nsec = (uint64_t)(msecs * 1000000) - (uint64_t)(twait.tv_sec / 1000000000); + d = ldiv(msecs, 1000); + tleft.tv_sec = d.quot; + tleft.tv_nsec = d.rem * 1000000; do { twait.tv_sec = tleft.tv_sec; twait.tv_nsec = tleft.tv_nsec;