From a0e58837e181c9509f989b8f01e96f78f4bfb459 Mon Sep 17 00:00:00 2001 From: Matthias Grob Date: Wed, 10 Jul 2024 14:52:09 +0200 Subject: [PATCH] drv_hrt: robustify wrap protection with half the range of the 64 bit timestamp This disallows any timespans longer than 292k years instead of disallowing any negative timespans which can occur and be processed correctly when the timestamp wraps e.g. because a timestamp is calculated by subtracting more time than already passed since boot (or after 584k years). --- src/drivers/drv_hrt.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/drivers/drv_hrt.h b/src/drivers/drv_hrt.h index bb62da0189..b9b6f0a496 100644 --- a/src/drivers/drv_hrt.h +++ b/src/drivers/drv_hrt.h @@ -164,10 +164,11 @@ static inline hrt_abstime hrt_elapsed_time(const hrt_abstime *then) { hrt_abstime now = hrt_absolute_time(); - // Cannot allow a negative elapsed time as this would appear - // to be a huge positive elapsed time when represented as an - // unsigned value! - if (*then > now) { + + // Zero out time differences bigger than half the timestamp range (~292k years) + // because this is indicating an unwanted wrap of the unsigned timestamp + // and hence a negative time difference (*then lies in the future). + if ((now - *then) > ((uint64_t)(-1) >> 1)) { return 0; }