blob: 78224946ce4d531835d4955720165c99180c37e0 [file] [log] [blame]
[email protected]ac4c6682012-01-04 00:57:391// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[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"
avi9b6f42932015-12-26 22:15:1418#include "base/macros.h"
Carlos Caballerof5b6f91c2019-12-20 14:07:3819#include "base/memory/ptr_util.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"
fdoray6ef45cf2016-08-25 15:36:3724#include "base/single_thread_task_runner.h"
Nick Diego Yamane58914192019-08-08 17:12:4825#include "base/synchronization/waitable_event.h"
26#include "base/synchronization/waitable_event_watcher.h"
Carlos Caballerob25fe8472020-07-17 10:27:1727#include "base/task/current_thread.h"
Carlos Caballerof5b6f91c2019-12-20 14:07:3828#include "base/task/single_thread_task_executor.h"
29#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 {
112 EventInjector* injector;
113 };
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
[email protected]59e69e742013-06-18 20:27:52122 Time future = last_time + TimeDelta::FromMilliseconds(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
143 Source* source_;
144 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;
171 EventInjector* injector() { return &injector_; }
[email protected]b44d5cc2009-06-15 10:30:44172
173 private:
Carlos Caballerof5b6f91c2019-12-20 14:07:38174 test::SingleThreadTaskEnvironment task_environment_{
175 test::SingleThreadTaskEnvironment::MainThreadType::UI};
176 EventInjector injector_;
177
[email protected]b44d5cc2009-06-15 10:30:44178 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest);
179};
180
181} // namespace
182
[email protected]b44d5cc2009-06-15 10:30:44183TEST_F(MessagePumpGLibTest, TestQuit) {
184 // Checks that Quit works and that the basic infrastructure is working.
185
186 // Quit from a task
[email protected]7ff48ca2013-02-06 16:56:19187 RunLoop().RunUntilIdle();
[email protected]b44d5cc2009-06-15 10:30:44188 EXPECT_EQ(0, injector()->processed_events());
189
190 injector()->Reset();
191 // Quit from an event
Wezfda077b2018-06-07 21:18:11192 RunLoop run_loop;
193 injector()->AddEvent(0, run_loop.QuitClosure());
194 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44195 EXPECT_EQ(1, injector()->processed_events());
196}
197
198TEST_F(MessagePumpGLibTest, TestEventTaskInterleave) {
199 // Checks that tasks posted by events are executed before the next event if
200 // the posted task queue is empty.
201 // MessageLoop doesn't make strong guarantees that it is the case, but the
202 // current implementation ensures it and the tests below rely on it.
203 // If changes cause this test to fail, it is reasonable to change it, but
204 // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
205 // changed accordingly, otherwise they can become flaky.
Peter Kasting341e1fb2018-02-24 00:03:01206 injector()->AddEventAsTask(0, DoNothing());
tzika8cc2202017-04-18 07:01:15207 OnceClosure check_task =
208 BindOnce(&ExpectProcessedEvents, Unretained(injector()), 2);
209 OnceClosure posted_task =
210 BindOnce(&PostMessageLoopTask, FROM_HERE, std::move(check_task));
211 injector()->AddEventAsTask(0, std::move(posted_task));
Peter Kasting341e1fb2018-02-24 00:03:01212 injector()->AddEventAsTask(0, DoNothing());
Wezfda077b2018-06-07 21:18:11213 {
214 RunLoop run_loop;
215 injector()->AddEvent(0, run_loop.QuitClosure());
216 run_loop.Run();
217 }
[email protected]b44d5cc2009-06-15 10:30:44218 EXPECT_EQ(4, injector()->processed_events());
219
220 injector()->Reset();
Peter Kasting341e1fb2018-02-24 00:03:01221 injector()->AddEventAsTask(0, DoNothing());
tzika8cc2202017-04-18 07:01:15222 check_task = BindOnce(&ExpectProcessedEvents, Unretained(injector()), 2);
223 posted_task =
224 BindOnce(&PostMessageLoopTask, FROM_HERE, std::move(check_task));
225 injector()->AddEventAsTask(0, std::move(posted_task));
Peter Kasting341e1fb2018-02-24 00:03:01226 injector()->AddEventAsTask(10, DoNothing());
Wezfda077b2018-06-07 21:18:11227 {
228 RunLoop run_loop;
229 injector()->AddEvent(0, run_loop.QuitClosure());
230 run_loop.Run();
231 }
[email protected]b44d5cc2009-06-15 10:30:44232 EXPECT_EQ(4, injector()->processed_events());
233}
234
235TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
236 int task_count = 0;
237 // Tests that we process tasks while waiting for new events.
238 // The event queue is empty at first.
239 for (int i = 0; i < 10; ++i) {
Carlos Caballerof5b6f91c2019-12-20 14:07:38240 ThreadTaskRunnerHandle::Get()->PostTask(
241 FROM_HERE, BindOnce(&IncrementInt, &task_count));
[email protected]b44d5cc2009-06-15 10:30:44242 }
243 // After all the previous tasks have executed, enqueue an event that will
244 // quit.
Wezfda077b2018-06-07 21:18:11245 {
246 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38247 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11248 FROM_HERE, BindOnce(&EventInjector::AddEvent, Unretained(injector()), 0,
249 run_loop.QuitClosure()));
250 run_loop.Run();
251 }
[email protected]b44d5cc2009-06-15 10:30:44252 ASSERT_EQ(10, task_count);
253 EXPECT_EQ(1, injector()->processed_events());
254
255 // Tests that we process delayed tasks while waiting for new events.
256 injector()->Reset();
257 task_count = 0;
258 for (int i = 0; i < 10; ++i) {
Carlos Caballerof5b6f91c2019-12-20 14:07:38259 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
260 FROM_HERE, BindOnce(&IncrementInt, &task_count),
261 TimeDelta::FromMilliseconds(10 * i));
[email protected]b44d5cc2009-06-15 10:30:44262 }
263 // After all the previous tasks have executed, enqueue an event that will
264 // quit.
265 // This relies on the fact that delayed tasks are executed in delay order.
266 // That is verified in message_loop_unittest.cc.
Wezfda077b2018-06-07 21:18:11267 {
268 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38269 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Wezfda077b2018-06-07 21:18:11270 FROM_HERE,
271 BindOnce(&EventInjector::AddEvent, Unretained(injector()), 0,
272 run_loop.QuitClosure()),
273 TimeDelta::FromMilliseconds(150));
274 run_loop.Run();
275 }
[email protected]b44d5cc2009-06-15 10:30:44276 ASSERT_EQ(10, task_count);
277 EXPECT_EQ(1, injector()->processed_events());
278}
279
280TEST_F(MessagePumpGLibTest, TestEventsWhileWaitingForWork) {
281 // Tests that we process events while waiting for work.
282 // The event queue is empty at first.
283 for (int i = 0; i < 10; ++i) {
[email protected]763839e2011-12-09 23:06:02284 injector()->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44285 }
286 // After all the events have been processed, post a task that will check that
287 // the events have been processed (note: the task executes after the event
288 // that posted it has been handled, so we expect 11 at that point).
tzika8cc2202017-04-18 07:01:15289 OnceClosure check_task =
290 BindOnce(&ExpectProcessedEvents, Unretained(injector()), 11);
291 OnceClosure posted_task =
292 BindOnce(&PostMessageLoopTask, FROM_HERE, std::move(check_task));
293 injector()->AddEventAsTask(10, std::move(posted_task));
[email protected]b44d5cc2009-06-15 10:30:44294
295 // And then quit (relies on the condition tested by TestEventTaskInterleave).
Wezfda077b2018-06-07 21:18:11296 RunLoop run_loop;
297 injector()->AddEvent(10, run_loop.QuitClosure());
298 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44299
300 EXPECT_EQ(12, injector()->processed_events());
301}
302
303namespace {
304
305// This class is a helper for the concurrent events / posted tasks test below.
306// It will quit the main loop once enough tasks and events have been processed,
307// while making sure there is always work to do and events in the queue.
[email protected]59e69e742013-06-18 20:27:52308class ConcurrentHelper : public RefCounted<ConcurrentHelper> {
[email protected]b44d5cc2009-06-15 10:30:44309 public:
Wezfda077b2018-06-07 21:18:11310 ConcurrentHelper(EventInjector* injector, OnceClosure done_closure)
[email protected]b44d5cc2009-06-15 10:30:44311 : injector_(injector),
Wezfda077b2018-06-07 21:18:11312 done_closure_(std::move(done_closure)),
[email protected]b44d5cc2009-06-15 10:30:44313 event_count_(kStartingEventCount),
Wezfda077b2018-06-07 21:18:11314 task_count_(kStartingTaskCount) {}
[email protected]b44d5cc2009-06-15 10:30:44315
316 void FromTask() {
317 if (task_count_ > 0) {
318 --task_count_;
319 }
320 if (task_count_ == 0 && event_count_ == 0) {
Wezfda077b2018-06-07 21:18:11321 std::move(done_closure_).Run();
[email protected]b44d5cc2009-06-15 10:30:44322 } else {
fdoray2df4a9e2016-07-18 23:47:16323 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44324 FROM_HERE, BindOnce(&ConcurrentHelper::FromTask, this));
[email protected]b44d5cc2009-06-15 10:30:44325 }
326 }
327
328 void FromEvent() {
329 if (event_count_ > 0) {
330 --event_count_;
331 }
332 if (task_count_ == 0 && event_count_ == 0) {
Wezfda077b2018-06-07 21:18:11333 std::move(done_closure_).Run();
[email protected]b44d5cc2009-06-15 10:30:44334 } else {
tzika8cc2202017-04-18 07:01:15335 injector_->AddEventAsTask(0,
336 BindOnce(&ConcurrentHelper::FromEvent, this));
[email protected]b44d5cc2009-06-15 10:30:44337 }
338 }
339
340 int event_count() const { return event_count_; }
341 int task_count() const { return task_count_; }
342
343 private:
[email protected]59e69e742013-06-18 20:27:52344 friend class RefCounted<ConcurrentHelper>;
[email protected]877d55d2009-11-05 21:53:08345
346 ~ConcurrentHelper() {}
347
[email protected]b44d5cc2009-06-15 10:30:44348 static const int kStartingEventCount = 20;
349 static const int kStartingTaskCount = 20;
350
351 EventInjector* injector_;
Wezfda077b2018-06-07 21:18:11352 OnceClosure done_closure_;
[email protected]b44d5cc2009-06-15 10:30:44353 int event_count_;
354 int task_count_;
355};
356
357} // namespace
358
359TEST_F(MessagePumpGLibTest, TestConcurrentEventPostedTask) {
360 // Tests that posted tasks don't starve events, nor the opposite.
361 // We use the helper class above. We keep both event and posted task queues
362 // full, the helper verifies that both tasks and events get processed.
363 // If that is not the case, either event_count_ or task_count_ will not get
[email protected]91cae2592013-01-10 14:56:17364 // to 0, and MessageLoop::QuitWhenIdle() will never be called.
Wezfda077b2018-06-07 21:18:11365 RunLoop run_loop;
366 scoped_refptr<ConcurrentHelper> helper =
367 new ConcurrentHelper(injector(), run_loop.QuitClosure());
[email protected]b44d5cc2009-06-15 10:30:44368
369 // Add 2 events to the queue to make sure it is always full (when we remove
370 // the event before processing it).
tzika8cc2202017-04-18 07:01:15371 injector()->AddEventAsTask(0, BindOnce(&ConcurrentHelper::FromEvent, helper));
372 injector()->AddEventAsTask(0, BindOnce(&ConcurrentHelper::FromEvent, helper));
[email protected]b44d5cc2009-06-15 10:30:44373
374 // Similarly post 2 tasks.
Carlos Caballerof5b6f91c2019-12-20 14:07:38375 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44376 FROM_HERE, BindOnce(&ConcurrentHelper::FromTask, helper));
Carlos Caballerof5b6f91c2019-12-20 14:07:38377 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44378 FROM_HERE, BindOnce(&ConcurrentHelper::FromTask, helper));
[email protected]b44d5cc2009-06-15 10:30:44379
Wezfda077b2018-06-07 21:18:11380 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44381 EXPECT_EQ(0, helper->event_count());
382 EXPECT_EQ(0, helper->task_count());
383}
384
385namespace {
386
Wezfda077b2018-06-07 21:18:11387void AddEventsAndDrainGLib(EventInjector* injector, OnceClosure on_drained) {
[email protected]b44d5cc2009-06-15 10:30:44388 // Add a couple of dummy events
[email protected]763839e2011-12-09 23:06:02389 injector->AddDummyEvent(0);
390 injector->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44391 // Then add an event that will quit the main loop.
Wezfda077b2018-06-07 21:18:11392 injector->AddEvent(0, std::move(on_drained));
[email protected]b44d5cc2009-06-15 10:30:44393
394 // Post a couple of dummy tasks
Peter Kasting341e1fb2018-02-24 00:03:01395 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
396 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
[email protected]b44d5cc2009-06-15 10:30:44397
398 // Drain the events
Ivan Kotenkova16212a52017-11-08 12:37:33399 while (g_main_context_pending(nullptr)) {
400 g_main_context_iteration(nullptr, FALSE);
[email protected]b44d5cc2009-06-15 10:30:44401 }
402}
403
404} // namespace
405
406TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
407 // Tests that draining events using GLib works.
Wezfda077b2018-06-07 21:18:11408 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38409 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11410 FROM_HERE, BindOnce(&AddEventsAndDrainGLib, Unretained(injector()),
411 run_loop.QuitClosure()));
412 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44413
414 EXPECT_EQ(3, injector()->processed_events());
415}
416
[email protected]b44d5cc2009-06-15 10:30:44417namespace {
418
419// Helper class that lets us run the GLib message loop.
[email protected]59e69e742013-06-18 20:27:52420class GLibLoopRunner : public RefCounted<GLibLoopRunner> {
[email protected]b44d5cc2009-06-15 10:30:44421 public:
422 GLibLoopRunner() : quit_(false) { }
423
424 void RunGLib() {
425 while (!quit_) {
Ivan Kotenkova16212a52017-11-08 12:37:33426 g_main_context_iteration(nullptr, TRUE);
[email protected]b44d5cc2009-06-15 10:30:44427 }
428 }
429
[email protected]258dca42011-09-21 00:17:19430 void RunLoop() {
[email protected]258dca42011-09-21 00:17:19431 while (!quit_) {
Ivan Kotenkova16212a52017-11-08 12:37:33432 g_main_context_iteration(nullptr, TRUE);
[email protected]258dca42011-09-21 00:17:19433 }
[email protected]b44d5cc2009-06-15 10:30:44434 }
435
436 void Quit() {
437 quit_ = true;
438 }
439
440 void Reset() {
441 quit_ = false;
442 }
443
444 private:
[email protected]59e69e742013-06-18 20:27:52445 friend class RefCounted<GLibLoopRunner>;
[email protected]877d55d2009-11-05 21:53:08446
447 ~GLibLoopRunner() {}
448
[email protected]b44d5cc2009-06-15 10:30:44449 bool quit_;
450};
451
Wezfda077b2018-06-07 21:18:11452void TestGLibLoopInternal(EventInjector* injector, OnceClosure done) {
[email protected]b44d5cc2009-06-15 10:30:44453 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
454
455 int task_count = 0;
456 // Add a couple of dummy events
[email protected]763839e2011-12-09 23:06:02457 injector->AddDummyEvent(0);
458 injector->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44459 // Post a couple of dummy tasks
fdoray2df4a9e2016-07-18 23:47:16460 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44461 BindOnce(&IncrementInt, &task_count));
fdoray2df4a9e2016-07-18 23:47:16462 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44463 BindOnce(&IncrementInt, &task_count));
[email protected]b44d5cc2009-06-15 10:30:44464 // Delayed events
[email protected]763839e2011-12-09 23:06:02465 injector->AddDummyEvent(10);
466 injector->AddDummyEvent(10);
[email protected]b44d5cc2009-06-15 10:30:44467 // Delayed work
fdoray2df4a9e2016-07-18 23:47:16468 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzik92b7a422017-04-11 15:00:44469 FROM_HERE, BindOnce(&IncrementInt, &task_count),
[email protected]59e69e742013-06-18 20:27:52470 TimeDelta::FromMilliseconds(30));
fdoray2df4a9e2016-07-18 23:47:16471 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzik92b7a422017-04-11 15:00:44472 FROM_HERE, BindOnce(&GLibLoopRunner::Quit, runner),
[email protected]59e69e742013-06-18 20:27:52473 TimeDelta::FromMilliseconds(40));
[email protected]b44d5cc2009-06-15 10:30:44474
475 // Run a nested, straight GLib message loop.
Gabriel Charettebdbb58e72020-06-03 18:26:06476 {
Carlos Caballerob25fe8472020-07-17 10:27:17477 CurrentThread::ScopedNestableTaskAllower allow_nestable_tasks;
Gabriel Charettebdbb58e72020-06-03 18:26:06478 runner->RunGLib();
479 }
[email protected]b44d5cc2009-06-15 10:30:44480
481 ASSERT_EQ(3, task_count);
482 EXPECT_EQ(4, injector->processed_events());
Wezfda077b2018-06-07 21:18:11483 std::move(done).Run();
[email protected]b44d5cc2009-06-15 10:30:44484}
485
Wezfda077b2018-06-07 21:18:11486void TestGtkLoopInternal(EventInjector* injector, OnceClosure done) {
[email protected]b44d5cc2009-06-15 10:30:44487 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
488
489 int task_count = 0;
490 // Add a couple of dummy events
[email protected]763839e2011-12-09 23:06:02491 injector->AddDummyEvent(0);
492 injector->AddDummyEvent(0);
[email protected]b44d5cc2009-06-15 10:30:44493 // Post a couple of dummy tasks
fdoray2df4a9e2016-07-18 23:47:16494 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44495 BindOnce(&IncrementInt, &task_count));
fdoray2df4a9e2016-07-18 23:47:16496 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
tzik92b7a422017-04-11 15:00:44497 BindOnce(&IncrementInt, &task_count));
[email protected]b44d5cc2009-06-15 10:30:44498 // Delayed events
[email protected]763839e2011-12-09 23:06:02499 injector->AddDummyEvent(10);
500 injector->AddDummyEvent(10);
[email protected]b44d5cc2009-06-15 10:30:44501 // Delayed work
fdoray2df4a9e2016-07-18 23:47:16502 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzik92b7a422017-04-11 15:00:44503 FROM_HERE, BindOnce(&IncrementInt, &task_count),
[email protected]59e69e742013-06-18 20:27:52504 TimeDelta::FromMilliseconds(30));
fdoray2df4a9e2016-07-18 23:47:16505 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzik92b7a422017-04-11 15:00:44506 FROM_HERE, BindOnce(&GLibLoopRunner::Quit, runner),
[email protected]59e69e742013-06-18 20:27:52507 TimeDelta::FromMilliseconds(40));
[email protected]b44d5cc2009-06-15 10:30:44508
509 // Run a nested, straight Gtk message loop.
Gabriel Charettebdbb58e72020-06-03 18:26:06510 {
Carlos Caballerob25fe8472020-07-17 10:27:17511 CurrentThread::ScopedNestableTaskAllower allow_nestable_tasks;
Gabriel Charettebdbb58e72020-06-03 18:26:06512 runner->RunLoop();
513 }
[email protected]b44d5cc2009-06-15 10:30:44514
515 ASSERT_EQ(3, task_count);
516 EXPECT_EQ(4, injector->processed_events());
Wezfda077b2018-06-07 21:18:11517 std::move(done).Run();
[email protected]b44d5cc2009-06-15 10:30:44518}
519
520} // namespace
521
522TEST_F(MessagePumpGLibTest, TestGLibLoop) {
[email protected]8f5a7e492012-01-01 02:14:47523 // Tests that events and posted tasks are correctly executed if the message
[email protected]b44d5cc2009-06-15 10:30:44524 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
525 // Note that in this case we don't make strong guarantees about niceness
526 // between events and posted tasks.
Wezfda077b2018-06-07 21:18:11527 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38528 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11529 FROM_HERE, BindOnce(&TestGLibLoopInternal, Unretained(injector()),
530 run_loop.QuitClosure()));
531 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44532}
533
534TEST_F(MessagePumpGLibTest, TestGtkLoop) {
[email protected]8f5a7e492012-01-01 02:14:47535 // Tests that events and posted tasks are correctly executed if the message
[email protected]b44d5cc2009-06-15 10:30:44536 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
537 // Note that in this case we don't make strong guarantees about niceness
538 // between events and posted tasks.
Wezfda077b2018-06-07 21:18:11539 RunLoop run_loop;
Carlos Caballerof5b6f91c2019-12-20 14:07:38540 ThreadTaskRunnerHandle::Get()->PostTask(
Wezfda077b2018-06-07 21:18:11541 FROM_HERE, BindOnce(&TestGtkLoopInternal, Unretained(injector()),
542 run_loop.QuitClosure()));
543 run_loop.Run();
[email protected]b44d5cc2009-06-15 10:30:44544}
[email protected]7ff48ca2013-02-06 16:56:19545
Nick Diego Yamane58914192019-08-08 17:12:48546// Tests for WatchFileDescriptor API
547class MessagePumpGLibFdWatchTest : public testing::Test {
548 protected:
549 MessagePumpGLibFdWatchTest()
550 : io_thread_("MessagePumpGLibFdWatchTestIOThread") {}
551 ~MessagePumpGLibFdWatchTest() override = default;
552
553 void SetUp() override {
554 Thread::Options options(MessagePumpType::IO, 0);
Olivier Lid68d0792021-05-17 20:51:41555 ASSERT_TRUE(io_thread_.StartWithOptions(std::move(options)));
Nick Diego Yamane58914192019-08-08 17:12:48556 int ret = pipe(pipefds_);
557 ASSERT_EQ(0, ret);
558 }
559
560 void TearDown() override {
561 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:
602 MessagePumpGlib::FdWatchController* controller_;
603};
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