Truly independent web browser
LibCore: Drop a Timer event posted before its timer restarted
sideshowbarkerb1b6241e84e7
diff --git a/Libraries/LibCore/Event.h b/Libraries/LibCore/Event.hindex 142febfb1bd..b92970d0cf3 100644--- a/Libraries/LibCore/Event.h+++ b/Libraries/LibCore/Event.h@@ -44,12 +44,18 @@ private:class TimerEvent final : public Event {public:- explicit TimerEvent()+ explicit TimerEvent(u64 timer_generation): Event(Event::Timer)+ , m_timer_generation(timer_generation){}~TimerEvent() = default;++ u64 timer_generation() const { return m_timer_generation; }++private:+ u64 m_timer_generation { 0 };};class NotifierActivationEvent final : public Event {diff --git a/Libraries/LibCore/EventLoopImplementationUnix.cpp b/Libraries/LibCore/EventLoopImplementationUnix.cppindex 6595ccbda2e..fae4658ff6f 100644--- a/Libraries/LibCore/EventLoopImplementationUnix.cpp+++ b/Libraries/LibCore/EventLoopImplementationUnix.cpp@@ -118,12 +118,13 @@ public:}}- ThreadEventQueue::current().post_event(strong_owner, Event::Type::Timer);+ ThreadEventQueue::current().post_timer_event(strong_owner, generation);}AK::Duration interval;bool should_reload { false };WeakPtr<EventReceiver> owner;+ u64 generation { 0 };AK::ThreadID owner_thread;Atomic<bool> is_being_deleted { false };};@@ -583,6 +584,7 @@ intptr_t EventLoopManagerUnix::register_timer(EventReceiver& object, AK::Duratioauto timer = new EventLoopTimer;timer->owner_thread = thread_data.thread_id;timer->owner = object;+ timer->generation = object.timer_generation();timer->interval = interval;// NB: The timer is armed and expired on the precise clock. CLOCK_MONOTONIC_COARSE lags it by up to a scheduler// tick on Linux, so a timer armed against the coarse clock could fire that much before its deadline on thediff --git a/Libraries/LibCore/EventLoopImplementationWindows.cpp b/Libraries/LibCore/EventLoopImplementationWindows.cppindex f7aeab19ecf..b7ccfdeef90 100644--- a/Libraries/LibCore/EventLoopImplementationWindows.cpp+++ b/Libraries/LibCore/EventLoopImplementationWindows.cpp@@ -191,12 +191,13 @@ public:}}- ThreadEventQueue::current().post_event(strong_owner, Event::Type::Timer);+ ThreadEventQueue::current().post_timer_event(strong_owner, generation);}AK::Duration interval;bool should_reload { false };WeakPtr<EventReceiver> owner;+ u64 generation { 0 };};// The Ancillary Function Driver's poll request, which select() and WSAPoll() are built on, is not in the Windows SDK.@@ -863,6 +864,7 @@ intptr_t EventLoopManagerWindows::register_timer(EventReceiver& object, AK::Duraauto timer = make<EventLoopTimer>();timer->owner = object.make_weak_ptr();+ timer->generation = object.timer_generation();timer->interval = interval;timer->should_reload = should_reload;timer->reload(MonotonicTime::now());diff --git a/Libraries/LibCore/EventReceiver.cpp b/Libraries/LibCore/EventReceiver.cppindex f0170fedf37..f671007cef5 100644--- a/Libraries/LibCore/EventReceiver.cpp+++ b/Libraries/LibCore/EventReceiver.cpp@@ -23,10 +23,12 @@ EventReceiver::~EventReceiver()void EventReceiver::event(Core::Event& event){switch (event.type()) {- case Core::Event::Timer:- if (!m_timer_id)- break; // Too late, the timer was already stopped.- return timer_event(static_cast<TimerEvent&>(event));+ case Core::Event::Timer: {+ auto& timer_event = static_cast<TimerEvent&>(event);+ if (!m_timer_id || timer_event.timer_generation() != m_timer_generation)+ break; // Too late, the timer was stopped or started again.+ return this->timer_event(timer_event);+ }case Core::Event::Invalid:VERIFY_NOT_REACHED();break;@@ -46,6 +48,7 @@ void EventReceiver::start_timer(AK::Duration interval)VERIFY_NOT_REACHED();}+ ++m_timer_generation;m_timer_id = Core::EventLoop::register_timer(*this, interval, true);}diff --git a/Libraries/LibCore/EventReceiver.h b/Libraries/LibCore/EventReceiver.hindex 115096395f9..37fcbcc5a65 100644--- a/Libraries/LibCore/EventReceiver.h+++ b/Libraries/LibCore/EventReceiver.h@@ -56,6 +56,8 @@ public:void stop_timer();bool has_timer() const { return m_timer_id; }+ u64 timer_generation() const { return m_timer_generation; }+void deferred_invoke(Function<void()>);void dispatch_event(Core::Event&);@@ -69,6 +71,7 @@ protected:private:intptr_t m_timer_id { 0 };+ u64 m_timer_generation { 0 };};}diff --git a/Libraries/LibCore/ThreadEventQueue.cpp b/Libraries/LibCore/ThreadEventQueue.cppindex 9540a11968e..f6e85a60b86 100644--- a/Libraries/LibCore/ThreadEventQueue.cpp+++ b/Libraries/LibCore/ThreadEventQueue.cpp@@ -25,8 +25,9 @@ struct ThreadEventQueue::Private {AK_MAKE_DEFAULT_MOVABLE(QueuedEvent);public:- QueuedEvent(RefPtr<EventReceiver> const& receiver, Event::Type event_type)+ QueuedEvent(RefPtr<EventReceiver> const& receiver, Event::Type event_type, u64 timer_generation = 0): receiver(receiver)+ , timer_generation(timer_generation), event_type(event_type){}@@ -40,6 +41,7 @@ struct ThreadEventQueue::Private {~QueuedEvent() = default;WeakPtr<EventReceiver> receiver;+ u64 timer_generation { 0 };Function<void()> m_invokee;u8 event_type { Event::Type::Invalid };};@@ -103,6 +105,15 @@ void ThreadEventQueue::post_event(Core::EventReceiver* receiver, Core::Event::TyCore::EventLoopManager::the().did_post_event();}+void ThreadEventQueue::post_timer_event(Core::EventReceiver* receiver, u64 timer_generation)+{+ {+ MutexLocker lock(m_private->mutex);+ m_private->queued_events.empend(receiver, Event::Type::Timer, timer_generation);+ }+ Core::EventLoopManager::the().did_post_event();+}+void ThreadEventQueue::deferred_invoke(Function<void()>&& invokee){{@@ -124,7 +135,7 @@ size_t ThreadEventQueue::process()if (auto receiver = queued_event.receiver.strong_ref()) {switch (queued_event.event_type) {case Event::Type::Timer: {- TimerEvent timer_event;+ TimerEvent timer_event { queued_event.timer_generation };receiver->dispatch_event(timer_event);break;}diff --git a/Libraries/LibCore/ThreadEventQueue.h b/Libraries/LibCore/ThreadEventQueue.hindex 65c48b8c972..1e226e18551 100644--- a/Libraries/LibCore/ThreadEventQueue.h+++ b/Libraries/LibCore/ThreadEventQueue.h@@ -39,6 +39,9 @@ public:// Posts an event to the event queue.void post_event(EventReceiver*, Core::Event::Type);+ // Posts a Timer event for the timer of the given generation to the event queue.+ void post_timer_event(EventReceiver*, u64 timer_generation);+// Post a deferred invocation to the event queue.void deferred_invoke(Function<void()>&&);diff --git a/Tests/LibCore/TestLibCoreEventLoop.cpp b/Tests/LibCore/TestLibCoreEventLoop.cppindex afb6344b0d4..d976fd9a186 100644--- a/Tests/LibCore/TestLibCoreEventLoop.cpp+++ b/Tests/LibCore/TestLibCoreEventLoop.cpp@@ -112,6 +112,72 @@ TEST_CASE(single_shot_timer_fires_once)EXPECT_EQ(count, 1);}+// The Timer event a single-shot timer posts can wait in the queue behind another event whose handler pumps the loop+// again, e.g. through spin_until(). The timer fires again in that nested pump, and its handler runs there. If the+// handler restarts the timer, the event still waiting in the queue is for the registration before the restart, and must+// not fire the restarted timer early.+TEST_CASE(single_shot_timer_fires_once_across_nested_pump)+{+ Core::EventLoop loop;+ int count = 0;+ RefPtr<Core::Timer> timer;+ timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(0), [&] {+ ++count;+ timer->restart(AK::Duration::from_seconds(10));+ });+ timer->start();+ // The pumping event queues itself again until the timer has fired, so the timer's event lands in a batch behind it+ // even where the timer's expiry reaches the loop only after a few polls.+ IGNORE_USE_IN_ESCAPING_LAMBDA Function<void()> pump_nested;+ pump_nested = [&] {+ for (int i = 0; i < 4; ++i)+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ if (count == 0)+ Core::deferred_invoke([&] { pump_nested(); });+ };+ Core::deferred_invoke([&] { pump_nested(); });+ while (count == 0)+ loop.pump(Core::EventLoop::WaitMode::WaitForEvents);+ for (int i = 0; i < 4; ++i)+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(count, 1);+ timer->stop();+}++// A single-shot timer whose Timer event waits in the queue behind an event whose handler spins the loop until the+// timer's handler has run fires again in that nested loop, so the spin ends.+TEST_CASE(single_shot_timer_fires_in_a_nested_pump_while_its_event_waits)+{+ IGNORE_USE_IN_ESCAPING_LAMBDA Core::EventLoop loop;+ IGNORE_USE_IN_ESCAPING_LAMBDA bool fired = false;+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(0), [&] { fired = true; });+ timer->start();+ IGNORE_USE_IN_ESCAPING_LAMBDA bool spin_ended = false;+ Core::deferred_invoke([&] {+ auto deadline = MonotonicTime::now() + AK::Duration::from_seconds(1);+ while (!fired && MonotonicTime::now() < deadline)+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ spin_ended = fired;+ });+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(spin_ended);+}++// A timer made repeating after it started as a single-shot one keeps firing.+TEST_CASE(single_shot_timer_made_repeating_keeps_firing)+{+ Core::EventLoop loop;+ int count = 0;+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(0), [&] {+ if (++count == 3)+ loop.quit(0);+ });+ timer->start();+ timer->set_single_shot(false);+ loop.exec();+ EXPECT_EQ(count, 3);+}+TEST_CASE(zero_interval_repeating_timer){Core::EventLoop loop;diff --git a/UI/Qt/EventLoopImplementationQt.cpp b/UI/Qt/EventLoopImplementationQt.cppindex ce78d4aeceb..151ecb6f2df 100644--- a/UI/Qt/EventLoopImplementationQt.cpp+++ b/UI/Qt/EventLoopImplementationQt.cpp@@ -381,9 +381,9 @@ void EventLoopImplementationQt::set_main_loop()event_loop_manager.set_main_loop_signal_notifiers({});}-static void qt_timer_fired(Core::EventReceiver& object)+static void qt_timer_fired(Core::EventReceiver& object, u64 timer_generation){- Core::TimerEvent event;+ Core::TimerEvent event { timer_generation };object.dispatch_event(event);}@@ -394,11 +394,11 @@ intptr_t EventLoopManagerQt::register_timer(Core::EventReceiver& object, AK::Durtimer->setInterval(AK::clamp_to<int>(interval.to_ceiled_milliseconds()));timer->setSingleShot(!should_reload);auto weak_object = object.make_weak_ptr();- QObject::connect(timer, &QTimer::timeout, [weak_object = move(weak_object)] {+ QObject::connect(timer, &QTimer::timeout, [weak_object = move(weak_object), timer_generation = object.timer_generation()] {auto object = weak_object.strong_ref();if (!object)return;- qt_timer_fired(*object);+ qt_timer_fired(*object, timer_generation);});timer->start();return bit_cast<intptr_t>(timer);