]> git.ipfire.org Git - thirdparty/chrony.git/commitdiff
util: avoid undefined behavior in timestamp conversion
authorMiroslav Lichvar <mlichvar@redhat.com>
Mon, 24 Jul 2017 13:42:27 +0000 (15:42 +0200)
committerMiroslav Lichvar <mlichvar@redhat.com>
Tue, 25 Jul 2017 15:40:35 +0000 (17:40 +0200)
test/unit/util.c
util.c

index 43f6214ec8add485359e3d24b5f4f266ad1e85ef..17f0c2869dc055de78d69c0f0ab875f211addb26 100644 (file)
@@ -43,6 +43,10 @@ void test_unit(void) {
   ntp_ts.hi = htonl(JAN_1970);
   ntp_ts.lo = 0xffffffff;
   UTI_Ntp64ToTimespec(&ntp_ts, &ts);
+  TEST_CHECK(ts.tv_sec == 0);
+  TEST_CHECK(ts.tv_nsec == 999999999);
+
+  UTI_AddDoubleToTimespec(&ts, 1e-9, &ts);
   TEST_CHECK(ts.tv_sec == 1);
   TEST_CHECK(ts.tv_nsec == 0);
 
diff --git a/util.c b/util.c
index ae530c9d592c56f742a40492a3cc8ace2ff263a4..2f4df156e9639299a1e97ebe96ec15f708f4edef 100644 (file)
--- a/util.c
+++ b/util.c
@@ -180,7 +180,7 @@ UTI_DiffTimespecs(struct timespec *result, struct timespec *a, struct timespec *
 double
 UTI_DiffTimespecsToDouble(struct timespec *a, struct timespec *b)
 {
-  return (a->tv_sec - b->tv_sec) + 1.0e-9 * (a->tv_nsec - b->tv_nsec);
+  return ((double)a->tv_sec - (double)b->tv_sec) + 1.0e-9 * (a->tv_nsec - b->tv_nsec);
 }
 
 /* ================================================== */
@@ -778,9 +778,7 @@ UTI_Ntp64ToTimespec(NTP_int64 *src, struct timespec *dest)
   dest->tv_sec = ntp_sec - JAN_1970;
 #endif
 
-  dest->tv_nsec = ntp_frac / NSEC_PER_NTP64 + 0.5;
-
-  UTI_NormaliseTimespec(dest);
+  dest->tv_nsec = ntp_frac / NSEC_PER_NTP64;
 }
 
 /* ================================================== */
@@ -840,12 +838,11 @@ UTI_Log2ToDouble(int l)
 void
 UTI_TimespecNetworkToHost(Timespec *src, struct timespec *dest)
 {
-  uint32_t sec_low;
+  uint32_t sec_low, nsec;
 #ifdef HAVE_LONG_TIME_T
   uint32_t sec_high;
 #endif
 
-  dest->tv_nsec = ntohl(src->tv_nsec);
   sec_low = ntohl(src->tv_sec_low);
 #ifdef HAVE_LONG_TIME_T
   sec_high = ntohl(src->tv_sec_high);
@@ -857,7 +854,8 @@ UTI_TimespecNetworkToHost(Timespec *src, struct timespec *dest)
   dest->tv_sec = sec_low;
 #endif
 
-  UTI_NormaliseTimespec(dest);
+  nsec = ntohl(src->tv_nsec);
+  dest->tv_nsec = CLAMP(0U, nsec, 999999999U);
 }
 
 /* ================================================== */