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
This commit is contained in:
Ulf Lilleengen 2021-10-20 09:05:44 +02:00
parent acce0f1d25
commit 6c9420978b

View File

@ -5,6 +5,7 @@ use std::mem::MaybeUninit;
use std::sync::{Condvar, Mutex, Once}; use std::sync::{Condvar, Mutex, Once};
use std::time::Duration as StdDuration; use std::time::Duration as StdDuration;
use std::time::Instant as StdInstant; use std::time::Instant as StdInstant;
use std::time::SystemTime;
use std::{ptr, thread}; use std::{ptr, thread};
use crate::time::driver::{AlarmHandle, Driver}; use crate::time::driver::{AlarmHandle, Driver};
@ -63,6 +64,7 @@ impl TimeDriver {
} }
fn alarm_thread() { fn alarm_thread() {
let zero = unsafe { DRIVER.zero_instant.read() };
loop { loop {
let now = DRIVER.now(); let now = DRIVER.now();
@ -86,8 +88,10 @@ impl TimeDriver {
} }
} }
let until = // Ensure we don't overflow
unsafe { DRIVER.zero_instant.read() } + StdDuration::from_micros(next_alarm); 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); unsafe { DRIVER.signaler.as_ref() }.wait_until(until);
} }