Skip to content

Commit

Permalink
timing: Fix timeout expiration checking nearing uptime counter overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
dragonmux committed May 3, 2024
1 parent 187dde4 commit eef7e8a
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/timing.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,17 @@ void platform_timeout_set(platform_timeout_s *const t, uint32_t ms)

bool platform_timeout_is_expired(const platform_timeout_s *const t)
{
return platform_time_ms() > t->time;
/* Cache the current time for the whole calculation */
const uint32_t counter = platform_time_ms();
/*
* Check for the tricky overflow condition and handle that properly -
* when time_ms approaches UINT32_MAX and we try to set a timeout that
* overflows to a low t->time value, if we simply compare with `<`, we will
* erroneously consider the timeout expired for a few ms right at the start of
* the valid interval. Instead, force that region of time to be considered
* not expired by checking the MSb's of the two values and handling that specially.
*/
if ((counter & UINT32_C(0x80000000)) && !(t->time & UINT32_C(0x80000000)))
return false;
return counter > t->time;
}

0 comments on commit eef7e8a

Please sign in to comment.