blob: 4f01fa90772aa0bc67f1c33106285218117fa96f [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
[email protected]b44d5cc2009-06-15 10:30:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]59e69e742013-06-18 20:27:525#include "base/message_loop/message_pump_glib.h"
[email protected]b44d5cc2009-06-15 10:30:446
[email protected]d90efd52012-06-28 19:57:267#include <glib.h>
[email protected]23d35392009-06-15 19:53:088#include <math.h>
9
[email protected]b44d5cc2009-06-15 10:30:4410#include <algorithm>
11#include <vector>
[email protected]23d35392009-06-15 19:53:0812
[email protected]8f5a7e492012-01-01 02:14:4713#include "base/bind.h"
[email protected]763839e2011-12-09 23:06:0214#include "base/callback.h"
danakjdb9ae7942020-11-11 16:01:3515#include "base/callback_helpers.h"
Nick Diego Yamane58914192019-08-08 17:12:4816#include "base/files/file_util.h"
Hans Wennborgafeb3902020-06-17 14:42:2917#include "base/logging.h"
Carlos Caballerof5b6f91c2019-12-20 14:07:3818#include "base/memory/ptr_util.h"
Keishi Hattorif28f4f82022-06-21 11:32:1519#include "base/memory/raw_ptr.h"
[email protected]3b63f8f42011-03-28 01:54:1520#include "base/memory/ref_counted.h"
Carlos Caballerodd8bf7b042019-07-30 14:14:1521#include "base/message_loop/message_pump_type.h"
Nick Diego Yamane58914192019-08-08 17:12:4822#include "base/posix/eintr_wrapper.h"
[email protected]7ff48ca2013-02-06 16:56:1923#include "base/run_loop.h"
Nick Diego Yamane58914192019-08-08 17:12:4824#include "base/synchronization/waitable_event.h"
25#include "base/synchronization/waitable_event_watcher.h"
Carlos Caballerob25fe8472020-07-17 10:27:1726#include "base/task/current_thread.h"
Carlos Caballerof5b6f91c2019-12-20 14:07:3827#include "base/task/single_thread_task_executor.h"
Patrick Monette643cdf62021-10-15 19:13:4228#include "base/task/single_thread_task_runner.h"
Carlos Caballerof5b6f91c2019-12-20 14:07:3829#include "base/test/task_environment.h"
[email protected]34b99632011-01-01 01:01:0630#include "base/threading/thread.h"
fdoray2df4a9e2016-07-18 23:47:1631#include "base/threading/thread_task_runner_handle.h"
[email protected]b44d5cc2009-06-15 10:30:4432#include "testing/gtest/include/gtest/gtest.h"
33
[email protected]7ff48ca2013-02-06 16:56:1934namespace base {
[email protected]b44d5cc2009-06-15 10:30:4435namespace {
36
37// This class injects dummy "events" into the GLib loop. When "handled" these
38// events can run tasks. This is intended to mock gtk events (the corresponding
39// GLib source runs at the same priority).
40class EventInjector {
41 public:
42 EventInjector() : processed_events_(0) {
43 source_ = static_cast<Source*>(g_source_new(&SourceFuncs, sizeof(Source)));
44 source_->injector = this;
Ivan Kotenkova16212a52017-11-08 12:37:3345 g_source_attach(source_, nullptr);
[email protected]b44d5cc2009-06-15 10:30:4446 g_source_set_can_recurse(source_, TRUE);
47 }
48
Peter Boström7319bbd2021-09-15 22:59:3849 EventInjector(const EventInjector&) = delete;
50 EventInjector& operator=(const EventInjector&) = delete;
51
[email protected]b44d5cc2009-06-15 10:30:4452 ~EventInjector() {
53 g_source_destroy(source_);
54 g_source_unref(source_);
55 }
56
57 int HandlePrepare() {
58 // If the queue is empty, block.
59 if (events_.empty())
60 return -1;
[email protected]59e69e742013-06-18 20:27:5261 TimeDelta delta = events_[0].time - Time::NowFromSystemTime();
[email protected]b44d5cc2009-06-15 10:30:4462 return std::max(0, static_cast<int>(ceil(delta.InMillisecondsF())));
63 }
64
65 bool HandleCheck() {
66 if (events_.empty())
67 return false;
[email protected]59e69e742013-06-18 20:27:5268 return events_[0].time <= Time::NowFromSystemTime();
[email protected]b44d5cc2009-06-15 10:30:4469 }
70
71 void HandleDispatch() {
72 if (events_.empty())
73 return;
tzika8cc2202017-04-18 07:01:1574 Event event = std::move(events_[0]);
[email protected]b44d5cc2009-06-15 10:30:4475 events_.erase(events_.begin());
76 ++processed_events_;
[email protected]8f5a7e492012-01-01 02:14:4777 if (!event.callback.is_null())
tzika8cc2202017-04-18 07:01:1578 std::move(event.callback).Run();
[email protected]8f5a7e492012-01-01 02:14:4779 else if (!event.task.is_null())
tzika8cc2202017-04-18 07:01:1580 std::move(event.task).Run();
[email protected]b44d5cc2009-06-15 10:30:4481 }
82
[email protected]763839e2011-12-09 23:06:0283 // Adds an event to the queue. When "handled", executes |callback|.
[email protected]b44d5cc2009-06-15 10:30:4484 // delay_ms is relative to the last event if any, or to Now() otherwise.
tzika8cc2202017-04-18 07:01:1585 void AddEvent(int delay_ms, OnceClosure callback) {
86 AddEventHelper(delay_ms, std::move(callback), OnceClosure());
[email protected]763839e2011-12-09 23:06:0287 }
88
89 void AddDummyEvent(int delay_ms) {
tzika8cc2202017-04-18 07:01:1590 AddEventHelper(delay_ms, OnceClosure(), OnceClosure());
[email protected]763839e2011-12-09 23:06:0291 }
92
tzika8cc2202017-04-18 07:01:1593 void AddEventAsTask(int delay_ms, OnceClosure task) {
94 AddEventHelper(delay_ms, OnceClosure(), std::move(task));
[email protected]b44d5cc2009-06-15 10:30:4495 }
96
97 void Reset() {
98 processed_events_ = 0;
99 events_.clear();
100 }
101
102 int processed_events() const { return processed_events_; }
103
104 private:
105 struct Event {
[email protected]59e69e742013-06-18 20:27:52106 Time time;
tzika8cc2202017-04-18 07:01:15107 OnceClosure callback;
108 OnceClosure task;
[email protected]b44d5cc2009-06-15 10:30:44109 };
110
111 struct Source : public GSource {
Keishi Hattorif28f4f82022-06-21 11:32:15112 raw_ptr<EventInjector> injector;
[email protected]b44d5cc2009-06-15 10:30:44113 };
114
tzika8cc2202017-04-18 07:01:15115 void AddEventHelper(int delay_ms, OnceClosure callback, OnceClosure task) {
[email protected]59e69e742013-06-18 20:27:52116 Time last_time;
[email protected]8f5a7e492012-01-01 02:14:47117 if (!events_.empty())
[email protected]763839e2011-12-09 23:06:02118 last_time = (events_.end()-1)->time;
[email protected]8f5a7e492012-01-01 02:14:47119 else
[email protected]59e69e742013-06-18 20:27:52120 last_time = Time::NowFromSystemTime();
[email protected]8f5a7e492012-01-01 02:14:47121
Peter Kasting53fd6ee2021-10-05 20:40:48122 Time future = last_time + Milliseconds(delay_ms);
tzika8cc2202017-04-18 07:01:15123 EventInjector::Event event = {future, std::move(callback), std::move(task)};
124 events_.push_back(std::move(event));
[email protected]763839e2011-12-09 23:06:02125 }
126
[email protected]b44d5cc2009-06-15 10:30:44127 static gboolean Prepare(GSource* source, gint* timeout_ms) {
128 *timeout_ms = static_cast<Source*>(source)->injector->HandlePrepare();
129 return FALSE;
130 }
131
132 static gboolean Check(GSource* source) {
133 return static_cast<Source*>(source)->injector->HandleCheck();
134 }
135
136 static gboolean Dispatch(GSource* source,
137 GSourceFunc unused_func,
138 gpointer unused_data) {
139 static_cast<Source*>(source)->injector->HandleDispatch();
140 return TRUE;
141 }
142
Keishi Hattorif28f4f82022-06-21 11:32:15143 raw_ptr<Source> source_;
[email protected]b44d5cc2009-06-15 10:30:44144 std::vector<Event> events_;
145 int processed_events_;
146 static GSourceFuncs SourceFuncs;
[email protected]b44d5cc2009-06-15 10:30:44147};
148
Ivan Kotenkova16212a52017-11-08 12:37:33149GSourceFuncs EventInjector::SourceFuncs = {EventInjector::Prepare,
150 EventInjector::Check,
151 EventInjector::Dispatch, nullptr};
[email protected]b44d5cc2009-06-15 10:30:44152
[email protected]b44d5cc2009-06-15 10:30:44153void IncrementInt(int *value) {
154 ++*value;
155}
156
157// Checks how many events have been processed by the injector.
158void ExpectProcessedEvents(EventInjector* injector, int count) {
159 EXPECT_EQ(injector->processed_events(), count);
160}
161
[email protected]b44d5cc2009-06-15 10:30:44162// Posts a task on the current message loop.
Brett Wilson8e88b312017-09-12 05:22:16163void PostMessageLoopTask(const Location& from_here, OnceClosure task) {
tzika8cc2202017-04-18 07:01:15164 ThreadTaskRunnerHandle::Get()->PostTask(from_here, std::move(task));
[email protected]b44d5cc2009-06-15 10:30:44165}
166
167// Test fixture.
168class MessagePumpGLibTest : public testing::Test {
169 public:
Carlos Caballerof5b6f91c2019-12-20 14:07:38170 MessagePumpGLibTest() = default;
Peter Boström75cd3c02021-09-28 15:23:18171
172 MessagePumpGLibTest(const MessagePumpGLibTest&) = delete;
173 MessagePumpGLibTest& operator=(const MessagePumpGLibTest&) = delete;
174
Carlos Caballerof5b6f91c2019-12-20 14:07:38175 EventInjector* injector() { return &injector_; }
[email protected]b44d5cc2009-06-15 10:30:44176
177 private:
Carlos Caballerof5b6f91c2019-12-20 14:07:38178 test::SingleThreadTaskEnvironment task_environment_{
179 test::SingleThreadTaskEnvironment::MainThreadType::UI};
180 EventInjector injector_;
[email protected]b44d5cc2009-06-15 10:30:44181};
182
183} // namespace
184
[email protected]b44d5cc2009-06-15 10:30:44185TEST_F(MessagePumpGLibTest, TestQuit) {
186 // Checks that Quit works and that the basic infrastructure is working.
187
188 // Quit from a task
[email protected]7ff48ca2013-02-06 16:56:19189 RunLoop().RunUntilIdle();
[email protected]b44d5cc2009-06-15 10:30:44190 EXPECT_EQ(0, injector()->processed_events());
191
192 injector()->Reset();
193 // Quit from an event
Wezfda077b2018-06-07 21:18:11194 RunLoop run_loop;
195 injector()->AddEvent(0, run_loop.QuitClosure());
196 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44197 EXPECT_EQ(1, injector()->processed_events());
198}
199
200TEST_F(MessagePumpGLibTest, TestEventTaskInterleave) {
201 // Checks that tasks posted by events are executed before the next event if
202 // the posted task queue is empty.
203 // MessageLoop doesn't make strong guarantees that it is the case, but the
204 // current implementation ensures it and the tests below rely on it.
205 // If changes cause this test to fail, it is reasonable to change it, but
206 // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
207 // changed accordingly, otherwise they can become flaky.
Peter Kasting341e1fb2018-02-24 00:03:01208 injector()->AddEventAsTask(0, DoNothing());
tzika8cc2202017-04-18 07:01:15209 OnceClosure check_task =
210 BindOnce(&ExpectProcessedEvents, Unretained(injector()), 2);
211 OnceClosure posted_task =
212 BindOnce(&PostMessageLoopTask, FROM_HERE, std::move(check_task));
213 injector()->AddEventAsTask(0, std::move(posted_task));
Peter Kasting341e1fb2018-02-24 00:03:01214 injector()->AddEventAsTask(0, DoNothing());
Wezfda077b2018-06-07 21:18:11215 {
216 RunLoop run_loop;
217 injector()->AddEvent(0, run_loop.QuitClosure());
218 run_loop.Run();
219 }
[email protected]b44d5cc2009-06-15 10:30:44220 EXPECT_EQ(4, injector()->processed_events());
221
222 injector()->Reset();
Peter Kasting341e1fb2018-02-24 00:03:01223 injector()->AddEventAsTask(0, DoNothing());
tzika8cc2202017-04-18 07:01:15224 check_task = BindOnce(&ExpectProcessedEvents, Unretained(injector()), 2);
225 posted_task =
226 BindOnce(&PostMessageLoopTask, FROM_HERE, std::move(check_task));
227 injector()->AddEventAsTask(0, std::move(posted_task));
Peter Kasting341e1fb2018-02-24 00:03:01228 injector()->AddEventAsTask(10, DoNothing());
Wezfda077b2018-06-07 21:18:11229 {
230 RunLoop run_loop;
231 injector()->AddEvent(0, run_loop.QuitClosure());
232 run_loop.Run();
233 }
[email protected]b44d5cc2009-06-15 10:30:44234 EXPECT_EQ(4, injector()->processed_events());
235}
236
237TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
238 int task_count = 0;
239 // Tests that we process tasks while waiting for new events.
240 // The event queue is empty at first.
241 for (int i = 0; i < 10; ++i) {
Carlos Caballerof5b6f91c2019-12-20 14:07:38242 ThreadTaskRunnerHandle::Get()->PostTask(
243 FROM_HERE, BindOnce(&IncrementInt, &task_count));
[email protected]b44d5cc2009-06-15 10:30:44244 }
245 // After all the previous tasks have executed, enqueue an event that will
246 // quit.
Wezfda077b2018-06-07 21:18:11247 {
248 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38249 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11250 FROM_HERE, BindOnce(&EventInjector::AddEvent, Unretained(injector()), 0,
251 run_loop.QuitClosure()));
252 run_loop.Run();
253 }
[email protected]b44d5cc2009-06-15 10:30:44254 ASSERT_EQ(10, task_count);
255 EXPECT_EQ(1, injector()->processed_events());
256
257 // Tests that we process delayed tasks while waiting for new events.
258 injector()->Reset();
259 task_count = 0;
260 for (int i = 0; i < 10; ++i) {
Carlos Caballerof5b6f91c2019-12-20 14:07:38261 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48262 FROM_HERE, BindOnce(&IncrementInt, &task_count), Milliseconds(10 * i));
[email protected]b44d5cc2009-06-15 10:30:44263 }
264 // After all the previous tasks have executed, enqueue an event that will
265 // quit.
266 // This relies on the fact that delayed tasks are executed in delay order.
267 // That is verified in message_loop_unittest.cc.
Wezfda077b2018-06-07 21:18:11268 {
269 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38270 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Wezfda077b2018-06-07 21:18:11271 FROM_HERE,
272 BindOnce(&EventInjector::AddEvent, Unretained(injector()), 0,
273 run_loop.QuitClosure()),
Peter Kasting53fd6ee2021-10-05 20:40:48274 Milliseconds(150));
Wezfda077b2018-06-07 21:18:11275 run_loop.Run();
276 }
[email protected]b44d5cc2009-06-15 10:30:44277 ASSERT_EQ(10, task_count);
278 EXPECT_EQ(1, injector()->processed_events());
279}
280
281TEST_F(MessagePumpGLibTest, TestEventsWhileWaitingForWork) {
282 // Tests that we process events while waiting for work.
283 // The event queue is empty at first.
284 for (int i = 0; i < 10; ++i) {
[email protected]763839e2011-12-09 23:06:02285 injector()->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44286 }
287 // After all the events have been processed, post a task that will check that
288 // the events have been processed (note: the task executes after the event
289 // that posted it has been handled, so we expect 11 at that point).
tzika8cc2202017-04-18 07:01:15290 OnceClosure check_task =
291 BindOnce(&ExpectProcessedEvents, Unretained(injector()), 11);
292 OnceClosure posted_task =
293 BindOnce(&PostMessageLoopTask, FROM_HERE, std::move(check_task));
294 injector()->AddEventAsTask(10, std::move(posted_task));
[email protected]b44d5cc2009-06-15 10:30:44295
296 // And then quit (relies on the condition tested by TestEventTaskInterleave).
Wezfda077b2018-06-07 21:18:11297 RunLoop run_loop;
298 injector()->AddEvent(10, run_loop.QuitClosure());
299 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44300
301 EXPECT_EQ(12, injector()->processed_events());
302}
303
304namespace {
305
306// This class is a helper for the concurrent events / posted tasks test below.
307// It will quit the main loop once enough tasks and events have been processed,
308// while making sure there is always work to do and events in the queue.
[email protected]59e69e742013-06-18 20:27:52309class ConcurrentHelper : public RefCounted<ConcurrentHelper> {
[email protected]b44d5cc2009-06-15 10:30:44310 public:
Wezfda077b2018-06-07 21:18:11311 ConcurrentHelper(EventInjector* injector, OnceClosure done_closure)
[email protected]b44d5cc2009-06-15 10:30:44312 : injector_(injector),
Wezfda077b2018-06-07 21:18:11313 done_closure_(std::move(done_closure)),
[email protected]b44d5cc2009-06-15 10:30:44314 event_count_(kStartingEventCount),
Wezfda077b2018-06-07 21:18:11315 task_count_(kStartingTaskCount) {}
[email protected]b44d5cc2009-06-15 10:30:44316
317 void FromTask() {
318 if (task_count_ > 0) {
319 --task_count_;
320 }
321 if (task_count_ == 0 && event_count_ == 0) {
Wezfda077b2018-06-07 21:18:11322 std::move(done_closure_).Run();
[email protected]b44d5cc2009-06-15 10:30:44323 } else {
fdoray2df4a9e2016-07-18 23:47:16324 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44325 FROM_HERE, BindOnce(&ConcurrentHelper::FromTask, this));
[email protected]b44d5cc2009-06-15 10:30:44326 }
327 }
328
329 void FromEvent() {
330 if (event_count_ > 0) {
331 --event_count_;
332 }
333 if (task_count_ == 0 && event_count_ == 0) {
Wezfda077b2018-06-07 21:18:11334 std::move(done_closure_).Run();
[email protected]b44d5cc2009-06-15 10:30:44335 } else {
tzika8cc2202017-04-18 07:01:15336 injector_->AddEventAsTask(0,
337 BindOnce(&ConcurrentHelper::FromEvent, this));
[email protected]b44d5cc2009-06-15 10:30:44338 }
339 }
340
341 int event_count() const { return event_count_; }
342 int task_count() const { return task_count_; }
343
344 private:
[email protected]59e69e742013-06-18 20:27:52345 friend class RefCounted<ConcurrentHelper>;
[email protected]877d55d2009-11-05 21:53:08346
347 ~ConcurrentHelper() {}
348
[email protected]b44d5cc2009-06-15 10:30:44349 static const int kStartingEventCount = 20;
350 static const int kStartingTaskCount = 20;
351
Keishi Hattorif28f4f82022-06-21 11:32:15352 raw_ptr<EventInjector> injector_;
Wezfda077b2018-06-07 21:18:11353 OnceClosure done_closure_;
[email protected]b44d5cc2009-06-15 10:30:44354 int event_count_;
355 int task_count_;
356};
357
358} // namespace
359
360TEST_F(MessagePumpGLibTest, TestConcurrentEventPostedTask) {
361 // Tests that posted tasks don't starve events, nor the opposite.
362 // We use the helper class above. We keep both event and posted task queues
363 // full, the helper verifies that both tasks and events get processed.
364 // If that is not the case, either event_count_ or task_count_ will not get
[email protected]91cae2592013-01-10 14:56:17365 // to 0, and MessageLoop::QuitWhenIdle() will never be called.
Wezfda077b2018-06-07 21:18:11366 RunLoop run_loop;
367 scoped_refptr<ConcurrentHelper> helper =
368 new ConcurrentHelper(injector(), run_loop.QuitClosure());
[email protected]b44d5cc2009-06-15 10:30:44369
370 // Add 2 events to the queue to make sure it is always full (when we remove
371 // the event before processing it).
tzika8cc2202017-04-18 07:01:15372 injector()->AddEventAsTask(0, BindOnce(&ConcurrentHelper::FromEvent, helper));
373 injector()->AddEventAsTask(0, BindOnce(&ConcurrentHelper::FromEvent, helper));
[email protected]b44d5cc2009-06-15 10:30:44374
375 // Similarly post 2 tasks.
Carlos Caballerof5b6f91c2019-12-20 14:07:38376 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44377 FROM_HERE, BindOnce(&ConcurrentHelper::FromTask, helper));
Carlos Caballerof5b6f91c2019-12-20 14:07:38378 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44379 FROM_HERE, BindOnce(&ConcurrentHelper::FromTask, helper));
[email protected]b44d5cc2009-06-15 10:30:44380
Wezfda077b2018-06-07 21:18:11381 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44382 EXPECT_EQ(0, helper->event_count());
383 EXPECT_EQ(0, helper->task_count());
384}
385
386namespace {
387
Wezfda077b2018-06-07 21:18:11388void AddEventsAndDrainGLib(EventInjector* injector, OnceClosure on_drained) {
[email protected]b44d5cc2009-06-15 10:30:44389 // Add a couple of dummy events
[email protected]763839e2011-12-09 23:06:02390 injector->AddDummyEvent(0);
391 injector->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44392 // Then add an event that will quit the main loop.
Wezfda077b2018-06-07 21:18:11393 injector->AddEvent(0, std::move(on_drained));
[email protected]b44d5cc2009-06-15 10:30:44394
395 // Post a couple of dummy tasks
Peter Kasting341e1fb2018-02-24 00:03:01396 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
397 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
[email protected]b44d5cc2009-06-15 10:30:44398
399 // Drain the events
Ivan Kotenkova16212a52017-11-08 12:37:33400 while (g_main_context_pending(nullptr)) {
401 g_main_context_iteration(nullptr, FALSE);
[email protected]b44d5cc2009-06-15 10:30:44402 }
403}
404
405} // namespace
406
407TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
408 // Tests that draining events using GLib works.
Wezfda077b2018-06-07 21:18:11409 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38410 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11411 FROM_HERE, BindOnce(&AddEventsAndDrainGLib, Unretained(injector()),
412 run_loop.QuitClosure()));
413 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44414
415 EXPECT_EQ(3, injector()->processed_events());
416}
417
[email protected]b44d5cc2009-06-15 10:30:44418namespace {
419
420// Helper class that lets us run the GLib message loop.
[email protected]59e69e742013-06-18 20:27:52421class GLibLoopRunner : public RefCounted<GLibLoopRunner> {
[email protected]b44d5cc2009-06-15 10:30:44422 public:
423 GLibLoopRunner() : quit_(false) { }
424
425 void RunGLib() {
426 while (!quit_) {
Ivan Kotenkova16212a52017-11-08 12:37:33427 g_main_context_iteration(nullptr, TRUE);
[email protected]b44d5cc2009-06-15 10:30:44428 }
429 }
430
[email protected]258dca42011-09-21 00:17:19431 void RunLoop() {
[email protected]258dca42011-09-21 00:17:19432 while (!quit_) {
Ivan Kotenkova16212a52017-11-08 12:37:33433 g_main_context_iteration(nullptr, TRUE);
[email protected]258dca42011-09-21 00:17:19434 }
[email protected]b44d5cc2009-06-15 10:30:44435 }
436
437 void Quit() {
438 quit_ = true;
439 }
440
441 void Reset() {
442 quit_ = false;
443 }
444
445 private:
[email protected]59e69e742013-06-18 20:27:52446 friend class RefCounted<GLibLoopRunner>;
[email protected]877d55d2009-11-05 21:53:08447
448 ~GLibLoopRunner() {}
449
[email protected]b44d5cc2009-06-15 10:30:44450 bool quit_;
451};
452
Wezfda077b2018-06-07 21:18:11453void TestGLibLoopInternal(EventInjector* injector, OnceClosure done) {
[email protected]b44d5cc2009-06-15 10:30:44454 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
455
456 int task_count = 0;
457 // Add a couple of dummy events
[email protected]763839e2011-12-09 23:06:02458 injector->AddDummyEvent(0);
459 injector->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44460 // Post a couple of dummy tasks
fdoray2df4a9e2016-07-18 23:47:16461 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44462 BindOnce(&IncrementInt, &task_count));
fdoray2df4a9e2016-07-18 23:47:16463 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44464 BindOnce(&IncrementInt, &task_count));
[email protected]b44d5cc2009-06-15 10:30:44465 // Delayed events
[email protected]763839e2011-12-09 23:06:02466 injector->AddDummyEvent(10);
467 injector->AddDummyEvent(10);
[email protected]b44d5cc2009-06-15 10:30:44468 // Delayed work
fdoray2df4a9e2016-07-18 23:47:16469 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48470 FROM_HERE, BindOnce(&IncrementInt, &task_count), Milliseconds(30));
fdoray2df4a9e2016-07-18 23:47:16471 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48472 FROM_HERE, BindOnce(&GLibLoopRunner::Quit, runner), Milliseconds(40));
[email protected]b44d5cc2009-06-15 10:30:44473
474 // Run a nested, straight GLib message loop.
Gabriel Charettebdbb58e72020-06-03 18:26:06475 {
Francois Doraya06ee172022-11-24 21:09:18476 CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
Gabriel Charettebdbb58e72020-06-03 18:26:06477 runner->RunGLib();
478 }
[email protected]b44d5cc2009-06-15 10:30:44479
480 ASSERT_EQ(3, task_count);
481 EXPECT_EQ(4, injector->processed_events());
Wezfda077b2018-06-07 21:18:11482 std::move(done).Run();
[email protected]b44d5cc2009-06-15 10:30:44483}
484
Wezfda077b2018-06-07 21:18:11485void TestGtkLoopInternal(EventInjector* injector, OnceClosure done) {
[email protected]b44d5cc2009-06-15 10:30:44486 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
487
488 int task_count = 0;
489 // Add a couple of dummy events
[email protected]763839e2011-12-09 23:06:02490 injector->AddDummyEvent(0);
491 injector->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44492 // Post a couple of dummy tasks
fdoray2df4a9e2016-07-18 23:47:16493 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44494 BindOnce(&IncrementInt, &task_count));
fdoray2df4a9e2016-07-18 23:47:16495 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44496 BindOnce(&IncrementInt, &task_count));
[email protected]b44d5cc2009-06-15 10:30:44497 // Delayed events
[email protected]763839e2011-12-09 23:06:02498 injector->AddDummyEvent(10);
499 injector->AddDummyEvent(10);
[email protected]b44d5cc2009-06-15 10:30:44500 // Delayed work
fdoray2df4a9e2016-07-18 23:47:16501 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48502 FROM_HERE, BindOnce(&IncrementInt, &task_count), Milliseconds(30));
fdoray2df4a9e2016-07-18 23:47:16503 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48504 FROM_HERE, BindOnce(&GLibLoopRunner::Quit, runner), Milliseconds(40));
[email protected]b44d5cc2009-06-15 10:30:44505
506 // Run a nested, straight Gtk message loop.
Gabriel Charettebdbb58e72020-06-03 18:26:06507 {
Francois Doraya06ee172022-11-24 21:09:18508 CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
Gabriel Charettebdbb58e72020-06-03 18:26:06509 runner->RunLoop();
510 }
[email protected]b44d5cc2009-06-15 10:30:44511
512 ASSERT_EQ(3, task_count);
513 EXPECT_EQ(4, injector->processed_events());
Wezfda077b2018-06-07 21:18:11514 std::move(done).Run();
[email protected]b44d5cc2009-06-15 10:30:44515}
516
517} // namespace
518
519TEST_F(MessagePumpGLibTest, TestGLibLoop) {
[email protected]8f5a7e492012-01-01 02:14:47520 // Tests that events and posted tasks are correctly executed if the message
[email protected]b44d5cc2009-06-15 10:30:44521 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
522 // Note that in this case we don't make strong guarantees about niceness
523 // between events and posted tasks.
Wezfda077b2018-06-07 21:18:11524 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38525 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11526 FROM_HERE, BindOnce(&TestGLibLoopInternal, Unretained(injector()),
527 run_loop.QuitClosure()));
528 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44529}
530
531TEST_F(MessagePumpGLibTest, TestGtkLoop) {
[email protected]8f5a7e492012-01-01 02:14:47532 // Tests that events and posted tasks are correctly executed if the message
[email protected]b44d5cc2009-06-15 10:30:44533 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
534 // Note that in this case we don't make strong guarantees about niceness
535 // between events and posted tasks.
Wezfda077b2018-06-07 21:18:11536 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38537 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11538 FROM_HERE, BindOnce(&TestGtkLoopInternal, Unretained(injector()),
539 run_loop.QuitClosure()));
540 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44541}
[email protected]7ff48ca2013-02-06 16:56:19542
Nick Diego Yamane58914192019-08-08 17:12:48543// Tests for WatchFileDescriptor API
544class MessagePumpGLibFdWatchTest : public testing::Test {
545 protected:
546 MessagePumpGLibFdWatchTest()
547 : io_thread_("MessagePumpGLibFdWatchTestIOThread") {}
548 ~MessagePumpGLibFdWatchTest() override = default;
549
550 void SetUp() override {
551 Thread::Options options(MessagePumpType::IO, 0);
Olivier Lid68d0792021-05-17 20:51:41552 ASSERT_TRUE(io_thread_.StartWithOptions(std::move(options)));
Nick Diego Yamane58914192019-08-08 17:12:48553 int ret = pipe(pipefds_);
554 ASSERT_EQ(0, ret);
555 }
556
557 void TearDown() override {
Reilly Grant6e56f8c2022-01-12 02:45:55558 // Wait for the IO thread to exit before closing FDs which may have been
559 // passed to it.
560 io_thread_.Stop();
Nick Diego Yamane58914192019-08-08 17:12:48561 if (IGNORE_EINTR(close(pipefds_[0])) < 0)
562 PLOG(ERROR) << "close";
563 if (IGNORE_EINTR(close(pipefds_[1])) < 0)
564 PLOG(ERROR) << "close";
565 }
566
567 void WaitUntilIoThreadStarted() {
568 ASSERT_TRUE(io_thread_.WaitUntilThreadStarted());
569 }
570
571 scoped_refptr<SingleThreadTaskRunner> io_runner() const {
572 return io_thread_.task_runner();
573 }
574
575 void SimulateEvent(MessagePumpGlib* pump,
576 MessagePumpGlib::FdWatchController* controller) {
577 controller->poll_fd_->revents = G_IO_IN | G_IO_OUT;
578 pump->HandleFdWatchDispatch(controller);
579 }
580
581 int pipefds_[2];
582
583 private:
584 Thread io_thread_;
585};
586
587namespace {
588
589class BaseWatcher : public MessagePumpGlib::FdWatcher {
590 public:
591 explicit BaseWatcher(MessagePumpGlib::FdWatchController* controller)
592 : controller_(controller) {
593 DCHECK(controller_);
594 }
595 ~BaseWatcher() override = default;
596
597 // base:MessagePumpGlib::FdWatcher interface
598 void OnFileCanReadWithoutBlocking(int /* fd */) override { NOTREACHED(); }
599 void OnFileCanWriteWithoutBlocking(int /* fd */) override { NOTREACHED(); }
600
601 protected:
Keishi Hattorif28f4f82022-06-21 11:32:15602 raw_ptr<MessagePumpGlib::FdWatchController> controller_;
Nick Diego Yamane58914192019-08-08 17:12:48603};
604
605class DeleteWatcher : public BaseWatcher {
606 public:
607 explicit DeleteWatcher(
608 std::unique_ptr<MessagePumpGlib::FdWatchController> controller)
609 : BaseWatcher(controller.get()),
610 owned_controller_(std::move(controller)) {}
611
612 ~DeleteWatcher() override { DCHECK(!controller_); }
613
614 void OnFileCanWriteWithoutBlocking(int /* fd */) override {
615 DCHECK(owned_controller_);
616 owned_controller_.reset();
617 controller_ = nullptr;
618 }
619
620 private:
621 std::unique_ptr<MessagePumpGlib::FdWatchController> owned_controller_;
622};
623
624class StopWatcher : public BaseWatcher {
625 public:
626 explicit StopWatcher(MessagePumpGlib::FdWatchController* controller)
627 : BaseWatcher(controller) {}
628
629 ~StopWatcher() override = default;
630
631 void OnFileCanWriteWithoutBlocking(int /* fd */) override {
632 controller_->StopWatchingFileDescriptor();
633 }
634};
635
636void QuitMessageLoopAndStart(OnceClosure quit_closure) {
637 std::move(quit_closure).Run();
638
639 RunLoop runloop(RunLoop::Type::kNestableTasksAllowed);
640 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, runloop.QuitClosure());
641 runloop.Run();
642}
643
644class NestedPumpWatcher : public MessagePumpGlib::FdWatcher {
645 public:
646 NestedPumpWatcher() = default;
647 ~NestedPumpWatcher() override = default;
648
649 void OnFileCanReadWithoutBlocking(int /* fd */) override {
650 RunLoop runloop;
651 ThreadTaskRunnerHandle::Get()->PostTask(
652 FROM_HERE, BindOnce(&QuitMessageLoopAndStart, runloop.QuitClosure()));
653 runloop.Run();
654 }
655
656 void OnFileCanWriteWithoutBlocking(int /* fd */) override {}
657};
658
659class QuitWatcher : public BaseWatcher {
660 public:
661 QuitWatcher(MessagePumpGlib::FdWatchController* controller,
662 base::OnceClosure quit_closure)
663 : BaseWatcher(controller), quit_closure_(std::move(quit_closure)) {}
664
665 void OnFileCanReadWithoutBlocking(int /* fd */) override {
666 if (quit_closure_)
667 std::move(quit_closure_).Run();
668 }
669
670 private:
671 base::OnceClosure quit_closure_;
672};
673
674void WriteFDWrapper(const int fd,
675 const char* buf,
676 int size,
677 WaitableEvent* event) {
Lei Zhangc9e8a162021-05-14 09:33:52678 ASSERT_TRUE(WriteFileDescriptor(fd, StringPiece(buf, size)));
Nick Diego Yamane58914192019-08-08 17:12:48679}
680
681} // namespace
682
683// Tests that MessagePumpGlib::FdWatcher::OnFileCanReadWithoutBlocking is not
684// called for a READ_WRITE event, when the controller is destroyed in
685// OnFileCanWriteWithoutBlocking callback.
686TEST_F(MessagePumpGLibFdWatchTest, DeleteWatcher) {
687 auto pump = std::make_unique<MessagePumpGlib>();
688 auto controller_ptr =
689 std::make_unique<MessagePumpGlib::FdWatchController>(FROM_HERE);
690 auto* controller = controller_ptr.get();
691
692 DeleteWatcher watcher(std::move(controller_ptr));
693 pump->WatchFileDescriptor(pipefds_[1], false,
694 MessagePumpGlib::WATCH_READ_WRITE, controller,
695 &watcher);
696
697 SimulateEvent(pump.get(), controller);
698}
699
700// Tests that MessagePumpGlib::FdWatcher::OnFileCanReadWithoutBlocking is not
701// called for a READ_WRITE event, when the watcher calls
702// StopWatchingFileDescriptor in OnFileCanWriteWithoutBlocking callback.
703TEST_F(MessagePumpGLibFdWatchTest, StopWatcher) {
704 std::unique_ptr<MessagePumpGlib> pump(new MessagePumpGlib);
705 MessagePumpGlib::FdWatchController controller(FROM_HERE);
706 StopWatcher watcher(&controller);
707 pump->WatchFileDescriptor(pipefds_[1], false,
708 MessagePumpGlib::WATCH_READ_WRITE, &controller,
709 &watcher);
710
711 SimulateEvent(pump.get(), &controller);
712}
713
714// Tests that FdWatcher works properly with nested loops.
715TEST_F(MessagePumpGLibFdWatchTest, NestedPumpWatcher) {
Carlos Caballerof5b6f91c2019-12-20 14:07:38716 test::SingleThreadTaskEnvironment task_environment(
717 test::SingleThreadTaskEnvironment::MainThreadType::UI);
Nick Diego Yamane58914192019-08-08 17:12:48718 std::unique_ptr<MessagePumpGlib> pump(new MessagePumpGlib);
719 MessagePumpGlib::FdWatchController controller(FROM_HERE);
720 NestedPumpWatcher watcher;
721 pump->WatchFileDescriptor(pipefds_[1], false, MessagePumpGlib::WATCH_READ,
722 &controller, &watcher);
723
724 SimulateEvent(pump.get(), &controller);
725}
726
727// Tests that MessagePumpGlib quits immediately when it is quit from
728// libevent's event_base_loop().
729TEST_F(MessagePumpGLibFdWatchTest, QuitWatcher) {
Carlos Caballerof5b6f91c2019-12-20 14:07:38730 MessagePumpGlib* pump = new MessagePumpGlib();
731 SingleThreadTaskExecutor executor(WrapUnique(pump));
Nick Diego Yamane58914192019-08-08 17:12:48732 RunLoop run_loop;
733 MessagePumpGlib::FdWatchController controller(FROM_HERE);
734 QuitWatcher delegate(&controller, run_loop.QuitClosure());
735 WaitableEvent event;
736 auto watcher = std::make_unique<WaitableEventWatcher>();
737
738 pump->WatchFileDescriptor(pipefds_[0], false, MessagePumpGlib::WATCH_READ,
739 &controller, &delegate);
740
741 // Make the IO thread wait for |event| before writing to pipefds[1].
742 const char buf = 0;
743 WaitableEventWatcher::EventCallback write_fd_task =
744 BindOnce(&WriteFDWrapper, pipefds_[1], &buf, 1);
745 io_runner()->PostTask(
746 FROM_HERE, BindOnce(IgnoreResult(&WaitableEventWatcher::StartWatching),
747 Unretained(watcher.get()), &event,
748 std::move(write_fd_task), io_runner()));
749
Carlos Caballerob25fe8472020-07-17 10:27:17750 // Queue |event| to signal on |CurrentUIThread::Get()|.
Nick Diego Yamane58914192019-08-08 17:12:48751 ThreadTaskRunnerHandle::Get()->PostTask(
752 FROM_HERE, BindOnce(&WaitableEvent::Signal, Unretained(&event)));
753
754 // Now run the MessageLoop.
755 run_loop.Run();
756
757 // StartWatching can move |watcher| to IO thread. Release on IO thread.
758 io_runner()->PostTask(FROM_HERE, BindOnce(&WaitableEventWatcher::StopWatching,
759 Owned(std::move(watcher))));
760}
761
[email protected]7ff48ca2013-02-06 16:56:19762} // namespace base