From 6c9420978b4e7a0b83d124b0e54255df4a64a9f3 Mon Sep 17 00:00:00 2001 From: Ulf Lilleengen Date: Wed, 20 Oct 2021 09:05:44 +0200 Subject: [PATCH 1/3] 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 29911c4d..c6788446 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); } From 3c2daf0d32fab3a545da2f34a24881acb30a4ea5 Mon Sep 17 00:00:00 2001 From: Ulf Lilleengen Date: Wed, 20 Oct 2021 12:42:05 +0200 Subject: [PATCH 2/3] Remove unused import --- embassy/src/time/driver_std.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/embassy/src/time/driver_std.rs b/embassy/src/time/driver_std.rs index c6788446..a571d521 100644 --- a/embassy/src/time/driver_std.rs +++ b/embassy/src/time/driver_std.rs @@ -5,7 +5,6 @@ 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}; From 5e6ee59ecd255c1d25bb0f687240183b63c4887d Mon Sep 17 00:00:00 2001 From: Ulf Lilleengen Date: Wed, 20 Oct 2021 14:25:34 +0200 Subject: [PATCH 3/3] Fix time calculation Use unwrap_or_get to avoid checking time when not necessary --- embassy/src/time/driver_std.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/embassy/src/time/driver_std.rs b/embassy/src/time/driver_std.rs index a571d521..0b5c6f85 100644 --- a/embassy/src/time/driver_std.rs +++ b/embassy/src/time/driver_std.rs @@ -90,7 +90,7 @@ impl TimeDriver { // Ensure we don't overflow let until = zero .checked_add(StdDuration::from_micros(next_alarm)) - .unwrap_or(zero + StdDuration::from_secs(1)); + .unwrap_or_else(|| StdInstant::now() + StdDuration::from_secs(1)); unsafe { DRIVER.signaler.as_ref() }.wait_until(until); }