From 99f78eb7085b19c78153bdfbff9d24a2098a2a57 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 4 Mar 2024 14:47:29 -0800 Subject: QTimer/QObject::startTimer: improve the detection of overflow Converting from int milliseconds to int64_t nanoseconds can't overflow (it won't even for picoseconds, so we'll be fine for a couple more decades), so we only need to address the cases where the millisecond value was passed in int64_t: that is, in the std::chrono::milliseconds overloads. For the other cases, I added a comment. Amends bfc7535a10f7a6e3723f354b41f08a0fe1d18719 to not allow the detected overflow to happen at all, which could cause the timer to become very small. Instead, we saturate to the maximum, which is about 292 years (just under 106752 days). That's longer than computers have existed, so the chance that some Qt application is still running on a computer without any reboots from today to 24th century is remote at best. This parallels QDeadlineTimer, which already has code to saturate when using milliseconds. Change-Id: I6818d78a57394e37857bfffd17b9b1465b6a5d19 Reviewed-by: Ahmad Samir --- src/corelib/kernel/qtimer.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/corelib/kernel/qtimer.cpp') diff --git a/src/corelib/kernel/qtimer.cpp b/src/corelib/kernel/qtimer.cpp index cc46c1433b5..294369c1b33 100644 --- a/src/corelib/kernel/qtimer.cpp +++ b/src/corelib/kernel/qtimer.cpp @@ -213,7 +213,7 @@ void QTimer::start() if (d->isActive()) // stop running timer stop(); - const auto newId = Qt::TimerId{QObject::startTimer(d->inter * 1ms, d->type)}; + Qt::TimerId newId{ QObject::startTimer(d->inter * 1ms, d->type) }; // overflow impossible if (newId > Qt::TimerId::Invalid) { d->id = newId; d->isActiveData.notify(); @@ -332,7 +332,7 @@ void QTimer::singleShotImpl(std::chrono::milliseconds msec, Qt::TimerType timerT return; } - new QSingleShotTimer(msec, timerType, receiver, slotObj); + new QSingleShotTimer(QSingleShotTimer::fromMsecs(msec), timerType, receiver, slotObj); } /*! @@ -396,7 +396,7 @@ void QTimer::singleShot(std::chrono::milliseconds msec, Qt::TimerType timerType, Qt::QueuedConnection); return; } - (void) new QSingleShotTimer(msec, timerType, receiver, member); + (void) new QSingleShotTimer(QSingleShotTimer::fromMsecs(msec), timerType, receiver, member); } } @@ -592,7 +592,7 @@ void QTimer::setInterval(std::chrono::milliseconds interval) d->inter.setValueBypassingBindings(msec); if (d->isActive()) { // create new timer QObject::killTimer(d->id); // restart timer - const auto newId = Qt::TimerId{QObject::startTimer(msec * 1ms, d->type)}; + Qt::TimerId newId{ QObject::startTimer(msec * 1ms, d->type) }; // overflow impossible if (newId > Qt::TimerId::Invalid) { // Restarted successfully. No need to update the active state. d->id = newId; -- cgit v1.2.3