From 6c9420978b4e7a0b83d124b0e54255df4a64a9f3 Mon Sep 17 00:00:00 2001 From: Ulf Lilleengen Date: Wed, 20 Oct 2021 09:05:44 +0200 Subject: [PATCH] Prevent overflow in std timer driver This prevents the std time driver from overflowing when setting the next wakeup time. If an overflow occurs, default to sleeping up to 1 second. Fixes #438 --- embassy/src/time/driver_std.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/embassy/src/time/driver_std.rs b/embassy/src/time/driver_std.rs index 29911c4d2..c67884465 100644 --- a/embassy/src/time/driver_std.rs +++ b/embassy/src/time/driver_std.rs @@ -5,6 +5,7 @@ use std::mem::MaybeUninit; use std::sync::{Condvar, Mutex, Once}; use std::time::Duration as StdDuration; use std::time::Instant as StdInstant; +use std::time::SystemTime; use std::{ptr, thread}; use crate::time::driver::{AlarmHandle, Driver}; @@ -63,6 +64,7 @@ impl TimeDriver { } fn alarm_thread() { + let zero = unsafe { DRIVER.zero_instant.read() }; loop { let now = DRIVER.now(); @@ -86,8 +88,10 @@ impl TimeDriver { } } - let until = - unsafe { DRIVER.zero_instant.read() } + StdDuration::from_micros(next_alarm); + // Ensure we don't overflow + let until = zero + .checked_add(StdDuration::from_micros(next_alarm)) + .unwrap_or(zero + StdDuration::from_secs(1)); unsafe { DRIVER.signaler.as_ref() }.wait_until(until); }