1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/message_loop/message_pump_glib.h"
6
7 #include <fcntl.h>
8 #include <glib.h>
9 #include <math.h>
10
11 #include "base/logging.h"
12 #include "base/memory/raw_ptr.h"
13 #include "base/notreached.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/posix/eintr_wrapper.h"
16 #include "base/synchronization/lock.h"
17 #include "base/threading/platform_thread.h"
18
19 namespace base {
20
21 namespace {
22
23 // Priorities of event sources are important to let everything be processed.
24 // In particular, GTK event source should have the highest priority (because
25 // UI events come from it), then Wayland events (the ones coming from the FD
26 // watcher), and the lowest priority is GLib events (our base message pump).
27 //
28 // The g_source API uses ints to denote priorities, and the lower is its value,
29 // the higher is the priority (i.e., they are ordered backwards).
30 constexpr int kPriorityWork = G_PRIORITY_DEFAULT_IDLE;
31 constexpr int kPriorityFdWatch = G_PRIORITY_DEFAULT_IDLE - 10;
32
33 // See the explanation above.
34 static_assert(G_PRIORITY_DEFAULT < kPriorityFdWatch &&
35 kPriorityFdWatch < kPriorityWork,
36 "Wrong priorities are set for event sources!");
37
38 // Return a timeout suitable for the glib loop according to |next_task_time|, -1
39 // to block forever, 0 to return right away, or a timeout in milliseconds from
40 // now.
GetTimeIntervalMilliseconds(TimeTicks next_task_time)41 int GetTimeIntervalMilliseconds(TimeTicks next_task_time) {
42 if (next_task_time.is_null())
43 return 0;
44 else if (next_task_time.is_max())
45 return -1;
46
47 auto timeout_ms =
48 (next_task_time - TimeTicks::Now()).InMillisecondsRoundedUp();
49
50 return timeout_ms < 0 ? 0 : saturated_cast<int>(timeout_ms);
51 }
52
RunningOnMainThread()53 bool RunningOnMainThread() {
54 auto pid = getpid();
55 auto tid = PlatformThread::CurrentId();
56 return pid > 0 && tid > 0 && pid == tid;
57 }
58
59 // A brief refresher on GLib:
60 // GLib sources have four callbacks: Prepare, Check, Dispatch and Finalize.
61 // On each iteration of the GLib pump, it calls each source's Prepare function.
62 // This function should return TRUE if it wants GLib to call its Dispatch, and
63 // FALSE otherwise. It can also set a timeout in this case for the next time
64 // Prepare should be called again (it may be called sooner).
65 // After the Prepare calls, GLib does a poll to check for events from the
66 // system. File descriptors can be attached to the sources. The poll may block
67 // if none of the Prepare calls returned TRUE. It will block indefinitely, or
68 // by the minimum time returned by a source in Prepare.
69 // After the poll, GLib calls Check for each source that returned FALSE
70 // from Prepare. The return value of Check has the same meaning as for Prepare,
71 // making Check a second chance to tell GLib we are ready for Dispatch.
72 // Finally, GLib calls Dispatch for each source that is ready. If Dispatch
73 // returns FALSE, GLib will destroy the source. Dispatch calls may be recursive
74 // (i.e., you can call Run from them), but Prepare and Check cannot.
75 // Finalize is called when the source is destroyed.
76 // NOTE: It is common for subsystems to want to process pending events while
77 // doing intensive work, for example the flash plugin. They usually use the
78 // following pattern (recommended by the GTK docs):
79 // while (gtk_events_pending()) {
80 // gtk_main_iteration();
81 // }
82 //
83 // gtk_events_pending just calls g_main_context_pending, which does the
84 // following:
85 // - Call prepare on all the sources.
86 // - Do the poll with a timeout of 0 (not blocking).
87 // - Call check on all the sources.
88 // - *Does not* call dispatch on the sources.
89 // - Return true if any of prepare() or check() returned true.
90 //
91 // gtk_main_iteration just calls g_main_context_iteration, which does the whole
92 // thing, respecting the timeout for the poll (and block, although it is to if
93 // gtk_events_pending returned true), and call dispatch.
94 //
95 // Thus it is important to only return true from prepare or check if we
96 // actually have events or work to do. We also need to make sure we keep
97 // internal state consistent so that if prepare/check return true when called
98 // from gtk_events_pending, they will still return true when called right
99 // after, from gtk_main_iteration.
100 //
101 // For the GLib pump we try to follow the Windows UI pump model:
102 // - Whenever we receive a wakeup event or the timer for delayed work expires,
103 // we run DoWork. That part will also run in the other event pumps.
104 // - We also run DoWork, and possibly DoIdleWork, in the main loop,
105 // around event handling.
106 //
107 // ---------------------------------------------------------------------------
108 //
109 // An overview on the way that we track work items:
110 //
111 // ScopedDoWorkItems are used by this pump to track native work. They are
112 // stored by value in |state_| and are set/cleared as the pump runs. Their
113 // setting and clearing is done in the functions
114 // {Set,Clear,EnsureSet,EnsureCleared}ScopedWorkItem. Control flow in GLib is
115 // quite non-obvious because chrome is not notified when a nested loop is
116 // entered/exited. To detect nested loops, MessagePumpGlib uses
117 // |state_->do_work_depth| which is incremented when DoWork is entered, and a
118 // GLib library function, g_main_depth(), which indicates the current number of
119 // Dispatch() calls on the stack. To react to them, two separate
120 // ScopedDoWorkItems are used (a standard one used for all native work, and a
121 // second one used exclusively for forcing nesting when there is a native loop
122 // spinning). Note that `ThreadController` flags all nesting as
123 // `Phase::kNested` so separating native and application work while nested isn't
124 // supported nor a goal.
125 //
126 // It should also be noted that a second GSource has been added to GLib,
127 // referred to as the "observer" source. It is used because in the case where
128 // native work occurs on wakeup that is higher priority than Chrome (all of
129 // GTK), chrome won't even get notified that the pump is awake.
130 //
131 // There are several cases to consider wrt. nesting level and order. In
132 // order, we have:
133 // A. [root] -> MessagePump::Run() -> native event -> g_main_context_iteration
134 // B. [root] -> MessagePump::Run() -> DoWork -> g_main_context_iteration
135 // C. [root] -> native -> DoWork -> MessagePump -> [...]
136 // The second two cases are identical for our purposes, and the last one turns
137 // out to be handled without any extra headache.
138 //
139 // Consider nesting case A, where native work is called from
140 // |g_main_context_iteration()| from the pump, and that native work spins up a
141 // loop. For our purposes, this is a nested loop, because control is not
142 // returned to the pump once one iteration of the pump is complete. In this
143 // case, the pump needs to enter nesting without DoWork being involved at
144 // all. This is accomplished using |MessagePumpGlib::NestIfRequired()|, which is
145 // called during the Prepare() phase of GLib. As the pump records state on entry
146 // and exit from GLib using |OnEntryToGlib| and |OnExitFromGlib|, we can compare
147 // |g_main_depth| at |HandlePrepare| with the one before we entered
148 // |g_main_context_iteration|. If it is higher, there is a native loop being
149 // spun, and |RegisterNesting| is called, forcing nesting by initializing two
150 // work items at once. These are destroyed after the exit from
151 // |g_main_context_iteration| using |OnExitFromGlib|.
152 //
153 // Then, considering nesting case B, |state_->do_work_depth| is incremented
154 // during any Chrome work, to allow the pump to detect re-entrancy during a
155 // chrome work item. This is required because `g_main_depth` is not incremented
156 // in any `DoWork` call not occuring during `Dispatch()` (i.e. during
157 // `MessagePumpGlib::Run()`). In this case, a nested loop is recorded, and the
158 // pump sets-and-clears scoped work items during Prepare, Check, and Dispatch. A
159 // work item can never be active when control flow returns to GLib (i.e. on
160 // return) during a nested loop, because the nested loop could exit at any
161 // point. This is fine because TimeKeeper is only concerned with the fact that a
162 // nested loop is in progress, as opposed to the various phases of the nested
163 // loop.
164 //
165 // Finally, consider nesting case C, where a native loop is spinning
166 // entirely outside of Chrome, such as inside a signal handler, the pump might
167 // create and destroy DoWorkItems during Prepare() and Check(), but these work
168 // items will always get cleared during Dispatch(), before the pump enters a
169 // DoWork(), leading to the pump showing non-nested native work without the
170 // thread controller being active, the correct situation (which won't occur
171 // outside of startup or shutdown). Once Dispatch() is called, the pump's
172 // nesting tracking works correctly, as state_->do_work_depth is increased, and
173 // upon re-entrancy we detect the nested loop, which is correct, as this is the
174 // only point at which the loop actually becomes "nested".
175 //
176 // -----------------------------------------------------------------------------
177 //
178 // As an overview of the steps taken by MessagePumpGLib to ensure that nested
179 // loops are detected adequately during each phase of the GLib loop:
180 //
181 // 0: Before entering GLib:
182 // 0.1: Record state about current state of GLib (g_main_depth()) for
183 // case 1.1.2.
184 //
185 // 1: Prepare.
186 // 1.1: Detection of nested loops
187
188 // 1.1.1: If |state_->do_work_depth| > 0, we are in nesting case B detailed
189 // above. A work item must be newly created during this function to
190 // trigger nesting, and is destroyed to ensure proper destruction order
191 // in the case where GLib quits after Prepare().
192 //
193 // 1.1.2: Otherwise, check if we are in nesting case A above. If yes, trigger
194 // nesting using ScopedDoWorkItems. The nesting will be cleared at exit
195 // from GLib.
196 //
197 // This check occurs only in |HandleObserverPrepare|, not in
198 // |HandlePrepare|.
199 //
200 // A third party is running a glib message loop. Since Chrome work is
201 // registered with GLib at |G_PRIORITY_DEFAULT_IDLE|, a relatively low
202 // priority, sources of default-or-higher priority will be Dispatch()ed
203 // first. Since only one source is Dispatched per loop iteration,
204 // |HandlePrepare| can get called several times in a row in the case that
205 // there are any other events in the queue. A ScopedDoWorkItem is created
206 // and destroyed to record this. That work item triggers nesting.
207 //
208 // 1.2: Other considerations
209 // 1.2.1: Sleep occurs between Prepare() and Check(). If Chrome will pass a
210 // nonzero poll time to GLib, the inner ScopedDoWorkItem is cleared and
211 // BeforeWait() is called. In nesting case A, the nesting work item will
212 // not be cleared. A nested loop will typically not block.
213 //
214 // Since Prepare() is called before Check() in all cases, the bulk of
215 // nesting detection is done in Prepare().
216 //
217 // 2: Check.
218 // 2.1: Detection of nested loops:
219 // 2.1.1: In nesting case B, |ClearScopedWorkItem()| on exit. A third party is
220 // running a glib message loop. It is possible that at any point the
221 // nested message loop will quit. In this case, we don't want to leave a
222 // nested DoWorkItem on the stack.
223 //
224 // 2.2: Other considerations
225 // 2.2.1: A ScopedDoWorkItem may be created (if it was not already present) at
226 // the entry to Check() to record a wakeup in the case that the pump
227 // slept. It is important to note that this occurs both in
228 // |HandleObserverCheck| and |HandleCheck| to ensure that at every point
229 // as the pump enters the Dispatch phase it is awake. In the case it is
230 // already awake, this is a very cheap operation.
231 //
232 // 3: Dispatch
233 // 3.1 Detection of nested loops
234 // 3.1.1: |state_->do_work_depth| is incremented on entry and decremented on
235 // exit. This is used to detect nesting case B.
236 //
237 // 3.1.2: Nested loops can be quit at any point, and so ScopedDoWorkItems can't
238 // be left on the stack for the same reasons as in 1.1.1/2.1.1.
239 //
240 // 3.2 Other considerations
241 // 3.2.1: Since DoWork creates its own work items, ScopedDoWorkItems are not
242 // used as this would trigger nesting in all cases.
243 //
244 // 4: Post GLib
245 // 4.1: Detection of nested loops
246 // 4.1.1: |state_->do_work_depth| is also increased during the DoWork in Run()
247 // as nesting in that case [calling glib from third party code] needs to
248 // clear all work items after return to avoid improper destruction order.
249 //
250 // 4.2: Other considerations:
251 // 4.2.1: DoWork uses its own work item, so no ScopedDoWorkItems are active in
252 // this case.
253
254 struct WorkSource : public GSource {
255 raw_ptr<MessagePumpGlib> pump;
256 };
257
WorkSourcePrepare(GSource * source,gint * timeout_ms)258 gboolean WorkSourcePrepare(GSource* source, gint* timeout_ms) {
259 *timeout_ms = static_cast<WorkSource*>(source)->pump->HandlePrepare();
260 // We always return FALSE, so that our timeout is honored. If we were
261 // to return TRUE, the timeout would be considered to be 0 and the poll
262 // would never block. Once the poll is finished, Check will be called.
263 return FALSE;
264 }
265
WorkSourceCheck(GSource * source)266 gboolean WorkSourceCheck(GSource* source) {
267 // Only return TRUE if Dispatch should be called.
268 return static_cast<WorkSource*>(source)->pump->HandleCheck();
269 }
270
WorkSourceDispatch(GSource * source,GSourceFunc unused_func,gpointer unused_data)271 gboolean WorkSourceDispatch(GSource* source,
272 GSourceFunc unused_func,
273 gpointer unused_data) {
274 static_cast<WorkSource*>(source)->pump->HandleDispatch();
275 // Always return TRUE so our source stays registered.
276 return TRUE;
277 }
278
279 // I wish these could be const, but g_source_new wants non-const.
280 GSourceFuncs g_work_source_funcs = {WorkSourcePrepare, WorkSourceCheck,
281 WorkSourceDispatch, nullptr};
282
283 struct ObserverSource : public GSource {
284 raw_ptr<MessagePumpGlib> pump;
285 };
286
ObserverPrepare(GSource * gsource,gint * timeout_ms)287 gboolean ObserverPrepare(GSource* gsource, gint* timeout_ms) {
288 auto* source = static_cast<ObserverSource*>(gsource);
289 source->pump->HandleObserverPrepare();
290 *timeout_ms = -1;
291 // We always want to poll.
292 return FALSE;
293 }
294
ObserverCheck(GSource * gsource)295 gboolean ObserverCheck(GSource* gsource) {
296 auto* source = static_cast<ObserverSource*>(gsource);
297 return source->pump->HandleObserverCheck();
298 }
299
300 GSourceFuncs g_observer_funcs = {ObserverPrepare, ObserverCheck, nullptr,
301 nullptr};
302
303 struct FdWatchSource : public GSource {
304 raw_ptr<MessagePumpGlib> pump;
305 raw_ptr<MessagePumpGlib::FdWatchController> controller;
306 };
307
FdWatchSourcePrepare(GSource * source,gint * timeout_ms)308 gboolean FdWatchSourcePrepare(GSource* source, gint* timeout_ms) {
309 *timeout_ms = -1;
310 return FALSE;
311 }
312
FdWatchSourceCheck(GSource * gsource)313 gboolean FdWatchSourceCheck(GSource* gsource) {
314 auto* source = static_cast<FdWatchSource*>(gsource);
315 return source->pump->HandleFdWatchCheck(source->controller) ? TRUE : FALSE;
316 }
317
FdWatchSourceDispatch(GSource * gsource,GSourceFunc unused_func,gpointer unused_data)318 gboolean FdWatchSourceDispatch(GSource* gsource,
319 GSourceFunc unused_func,
320 gpointer unused_data) {
321 auto* source = static_cast<FdWatchSource*>(gsource);
322 source->pump->HandleFdWatchDispatch(source->controller);
323 return TRUE;
324 }
325
326 GSourceFuncs g_fd_watch_source_funcs = {
327 FdWatchSourcePrepare, FdWatchSourceCheck, FdWatchSourceDispatch, nullptr};
328
329 } // namespace
330
331 struct MessagePumpGlib::RunState {
RunStatebase::MessagePumpGlib::RunState332 explicit RunState(Delegate* delegate) : delegate(delegate) {
333 CHECK(delegate);
334 }
335
336 const raw_ptr<Delegate> delegate;
337
338 // Used to flag that the current Run() invocation should return ASAP.
339 bool should_quit = false;
340
341 // Keeps track of the number of calls to DoWork() on the stack for the current
342 // Run() invocation. Used to detect reentrancy from DoWork in order to make
343 // decisions about tracking nested work.
344 int do_work_depth = 0;
345
346 // Value of g_main_depth() captured before the call to
347 // g_main_context_iteration() in Run(). nullopt if Run() is not calling
348 // g_main_context_iteration(). Used to track whether the pump has forced a
349 // nested state due to a native pump.
350 absl::optional<int> g_depth_on_iteration;
351
352 // Used to keep track of the native event work items processed by the message
353 // pump.
354 Delegate::ScopedDoWorkItem scoped_do_work_item;
355
356 // Used to force the pump into a nested state when a native runloop was
357 // dispatched from main.
358 Delegate::ScopedDoWorkItem native_loop_do_work_item;
359
360 // The information of the next task available at this run-level. Stored in
361 // RunState because different set of tasks can be accessible at various
362 // run-levels (e.g. non-nestable tasks).
363 Delegate::NextWorkInfo next_work_info;
364 };
365
MessagePumpGlib()366 MessagePumpGlib::MessagePumpGlib()
367 : state_(nullptr), wakeup_gpollfd_(std::make_unique<GPollFD>()) {
368 DCHECK(!g_main_context_get_thread_default());
369 if (RunningOnMainThread()) {
370 context_ = g_main_context_default();
371 } else {
372 owned_context_ = std::unique_ptr<GMainContext, GMainContextDeleter>(
373 g_main_context_new());
374 context_ = owned_context_.get();
375 g_main_context_push_thread_default(context_);
376 }
377
378 // Create our wakeup pipe, which is used to flag when work was scheduled.
379 int fds[2];
380 [[maybe_unused]] int ret = pipe2(fds, O_CLOEXEC);
381 DCHECK_EQ(ret, 0);
382
383 wakeup_pipe_read_ = fds[0];
384 wakeup_pipe_write_ = fds[1];
385 wakeup_gpollfd_->fd = wakeup_pipe_read_;
386 wakeup_gpollfd_->events = G_IO_IN;
387
388 observer_source_ = std::unique_ptr<GSource, GSourceDeleter>(
389 g_source_new(&g_observer_funcs, sizeof(ObserverSource)));
390 static_cast<ObserverSource*>(observer_source_.get())->pump = this;
391 g_source_attach(observer_source_.get(), context_);
392
393 work_source_ = std::unique_ptr<GSource, GSourceDeleter>(
394 g_source_new(&g_work_source_funcs, sizeof(WorkSource)));
395 static_cast<WorkSource*>(work_source_.get())->pump = this;
396 g_source_add_poll(work_source_.get(), wakeup_gpollfd_.get());
397 g_source_set_priority(work_source_.get(), kPriorityWork);
398 // This is needed to allow Run calls inside Dispatch.
399 g_source_set_can_recurse(work_source_.get(), TRUE);
400 g_source_attach(work_source_.get(), context_);
401 }
402
~MessagePumpGlib()403 MessagePumpGlib::~MessagePumpGlib() {
404 work_source_.reset();
405 close(wakeup_pipe_read_);
406 close(wakeup_pipe_write_);
407 context_ = nullptr;
408 owned_context_.reset();
409 }
410
FdWatchController(const Location & location)411 MessagePumpGlib::FdWatchController::FdWatchController(const Location& location)
412 : FdWatchControllerInterface(location) {}
413
~FdWatchController()414 MessagePumpGlib::FdWatchController::~FdWatchController() {
415 if (IsInitialized()) {
416 CHECK(StopWatchingFileDescriptor());
417 }
418 if (was_destroyed_) {
419 DCHECK(!*was_destroyed_);
420 *was_destroyed_ = true;
421 }
422 }
423
StopWatchingFileDescriptor()424 bool MessagePumpGlib::FdWatchController::StopWatchingFileDescriptor() {
425 if (!IsInitialized())
426 return false;
427
428 g_source_destroy(source_);
429 g_source_unref(source_.ExtractAsDangling());
430 watcher_ = nullptr;
431 return true;
432 }
433
IsInitialized() const434 bool MessagePumpGlib::FdWatchController::IsInitialized() const {
435 return !!source_;
436 }
437
InitOrUpdate(int fd,int mode,FdWatcher * watcher)438 bool MessagePumpGlib::FdWatchController::InitOrUpdate(int fd,
439 int mode,
440 FdWatcher* watcher) {
441 gushort event_flags = 0;
442 if (mode & WATCH_READ) {
443 event_flags |= G_IO_IN;
444 }
445 if (mode & WATCH_WRITE) {
446 event_flags |= G_IO_OUT;
447 }
448
449 if (!IsInitialized()) {
450 poll_fd_ = std::make_unique<GPollFD>();
451 poll_fd_->fd = fd;
452 } else {
453 if (poll_fd_->fd != fd)
454 return false;
455 // Combine old/new event masks.
456 event_flags |= poll_fd_->events;
457 // Destroy previous source
458 bool stopped = StopWatchingFileDescriptor();
459 DCHECK(stopped);
460 }
461 poll_fd_->events = event_flags;
462 poll_fd_->revents = 0;
463
464 source_ = g_source_new(&g_fd_watch_source_funcs, sizeof(FdWatchSource));
465 DCHECK(source_);
466 g_source_add_poll(source_, poll_fd_.get());
467 g_source_set_can_recurse(source_, TRUE);
468 g_source_set_callback(source_, nullptr, nullptr, nullptr);
469 g_source_set_priority(source_, kPriorityFdWatch);
470
471 watcher_ = watcher;
472 return true;
473 }
474
Attach(MessagePumpGlib * pump)475 bool MessagePumpGlib::FdWatchController::Attach(MessagePumpGlib* pump) {
476 DCHECK(pump);
477 if (!IsInitialized()) {
478 return false;
479 }
480 auto* source = static_cast<FdWatchSource*>(source_);
481 source->controller = this;
482 source->pump = pump;
483 g_source_attach(source_, pump->context_);
484 return true;
485 }
486
NotifyCanRead()487 void MessagePumpGlib::FdWatchController::NotifyCanRead() {
488 if (!watcher_)
489 return;
490 DCHECK(poll_fd_);
491 watcher_->OnFileCanReadWithoutBlocking(poll_fd_->fd);
492 }
493
NotifyCanWrite()494 void MessagePumpGlib::FdWatchController::NotifyCanWrite() {
495 if (!watcher_)
496 return;
497 DCHECK(poll_fd_);
498 watcher_->OnFileCanWriteWithoutBlocking(poll_fd_->fd);
499 }
500
WatchFileDescriptor(int fd,bool persistent,int mode,FdWatchController * controller,FdWatcher * watcher)501 bool MessagePumpGlib::WatchFileDescriptor(int fd,
502 bool persistent,
503 int mode,
504 FdWatchController* controller,
505 FdWatcher* watcher) {
506 DCHECK_GE(fd, 0);
507 DCHECK(controller);
508 DCHECK(watcher);
509 DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
510 // WatchFileDescriptor should be called on the pump thread. It is not
511 // threadsafe, so the watcher may never be registered.
512 DCHECK_CALLED_ON_VALID_THREAD(watch_fd_caller_checker_);
513
514 if (!controller->InitOrUpdate(fd, mode, watcher)) {
515 DPLOG(ERROR) << "FdWatchController init failed (fd=" << fd << ")";
516 return false;
517 }
518 return controller->Attach(this);
519 }
520
HandleObserverPrepare()521 void MessagePumpGlib::HandleObserverPrepare() {
522 // |state_| may be null during tests.
523 if (!state_) {
524 return;
525 }
526
527 if (state_->do_work_depth > 0) {
528 // Contingency 1.1.1 detailed above
529 SetScopedWorkItem();
530 ClearScopedWorkItem();
531 } else {
532 // Contingency 1.1.2 detailed above
533 NestIfRequired();
534 }
535
536 return;
537 }
538
HandleObserverCheck()539 bool MessagePumpGlib::HandleObserverCheck() {
540 // |state_| may be null in tests.
541 if (!state_) {
542 return FALSE;
543 }
544
545 // Make sure we record the fact that we're awake. Chrome won't get Check()ed
546 // if a higher priority work item returns TRUE from Check().
547 EnsureSetScopedWorkItem();
548 if (state_->do_work_depth > 0) {
549 // Contingency 2.1.1
550 ClearScopedWorkItem();
551 }
552
553 // The observer never needs to run anything.
554 return FALSE;
555 }
556
557 // Return the timeout we want passed to poll.
HandlePrepare()558 int MessagePumpGlib::HandlePrepare() {
559 // |state_| may be null during tests.
560 if (!state_)
561 return 0;
562
563 const int next_wakeup_millis =
564 GetTimeIntervalMilliseconds(state_->next_work_info.delayed_run_time);
565 if (next_wakeup_millis != 0) {
566 // When this is called, it is not possible to know for sure if a
567 // ScopedWorkItem is on the stack, because HandleObserverCheck may have set
568 // it during an iteration of the pump where a high priority native work item
569 // executed.
570 EnsureClearedScopedWorkItem();
571 state_->delegate->BeforeWait();
572 }
573
574 return next_wakeup_millis;
575 }
576
HandleCheck()577 bool MessagePumpGlib::HandleCheck() {
578 if (!state_) // state_ may be null during tests.
579 return false;
580
581 // Ensure pump is awake.
582 EnsureSetScopedWorkItem();
583
584 if (state_->do_work_depth > 0) {
585 // Contingency 2.1.1
586 ClearScopedWorkItem();
587 }
588
589 // We usually have a single message on the wakeup pipe, since we are only
590 // signaled when the queue went from empty to non-empty, but there can be
591 // two messages if a task posted a task, hence we read at most two bytes.
592 // The glib poll will tell us whether there was data, so this read
593 // shouldn't block.
594 if (wakeup_gpollfd_->revents & G_IO_IN) {
595 char msg[2];
596 const long num_bytes = HANDLE_EINTR(read(wakeup_pipe_read_, msg, 2));
597 if (num_bytes < 1) {
598 NOTREACHED() << "Error reading from the wakeup pipe.";
599 }
600 DCHECK((num_bytes == 1 && msg[0] == '!') ||
601 (num_bytes == 2 && msg[0] == '!' && msg[1] == '!'));
602 // Since we ate the message, we need to record that we have immediate work,
603 // because HandleCheck() may be called without HandleDispatch being called
604 // afterwards.
605 state_->next_work_info = {TimeTicks()};
606 return true;
607 }
608
609 // As described in the summary at the top : Check is a second-chance to
610 // Prepare, verify whether we have work ready again.
611 if (GetTimeIntervalMilliseconds(state_->next_work_info.delayed_run_time) ==
612 0) {
613 return true;
614 }
615
616 return false;
617 }
618
HandleDispatch()619 void MessagePumpGlib::HandleDispatch() {
620 // Contingency 3.2.1
621 EnsureClearedScopedWorkItem();
622
623 // Contingency 3.1.1
624 ++state_->do_work_depth;
625 state_->next_work_info = state_->delegate->DoWork();
626 --state_->do_work_depth;
627
628 if (state_ && state_->do_work_depth > 0) {
629 // Contingency 3.1.2
630 EnsureClearedScopedWorkItem();
631 }
632 }
633
Run(Delegate * delegate)634 void MessagePumpGlib::Run(Delegate* delegate) {
635 RunState state(delegate);
636
637 RunState* previous_state = state_;
638 state_ = &state;
639
640 // We really only do a single task for each iteration of the loop. If we
641 // have done something, assume there is likely something more to do. This
642 // will mean that we don't block on the message pump until there was nothing
643 // more to do. We also set this to true to make sure not to block on the
644 // first iteration of the loop, so RunUntilIdle() works correctly.
645 bool more_work_is_plausible = true;
646
647 // We run our own loop instead of using g_main_loop_quit in one of the
648 // callbacks. This is so we only quit our own loops, and we don't quit
649 // nested loops run by others. TODO(deanm): Is this what we want?
650 for (;;) {
651 // ScopedWorkItem to account for any native work until the runloop starts
652 // running chrome work.
653 SetScopedWorkItem();
654
655 // Don't block if we think we have more work to do.
656 bool block = !more_work_is_plausible;
657
658 OnEntryToGlib();
659 more_work_is_plausible = g_main_context_iteration(context_, block);
660 OnExitFromGlib();
661
662 if (state_->should_quit)
663 break;
664
665 // Contingency 4.2.1
666 EnsureClearedScopedWorkItem();
667
668 // Contingency 4.1.1
669 ++state_->do_work_depth;
670 state_->next_work_info = state_->delegate->DoWork();
671 --state_->do_work_depth;
672
673 more_work_is_plausible |= state_->next_work_info.is_immediate();
674 if (state_->should_quit)
675 break;
676
677 if (more_work_is_plausible)
678 continue;
679
680 more_work_is_plausible = state_->delegate->DoIdleWork();
681 if (state_->should_quit)
682 break;
683 }
684
685 state_ = previous_state;
686 }
687
Quit()688 void MessagePumpGlib::Quit() {
689 if (state_) {
690 state_->should_quit = true;
691 } else {
692 NOTREACHED() << "Quit called outside Run!";
693 }
694 }
695
ScheduleWork()696 void MessagePumpGlib::ScheduleWork() {
697 // This can be called on any thread, so we don't want to touch any state
698 // variables as we would then need locks all over. This ensures that if
699 // we are sleeping in a poll that we will wake up.
700 char msg = '!';
701 if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) {
702 NOTREACHED() << "Could not write to the UI message loop wakeup pipe!";
703 }
704 }
705
ScheduleDelayedWork(const Delegate::NextWorkInfo & next_work_info)706 void MessagePumpGlib::ScheduleDelayedWork(
707 const Delegate::NextWorkInfo& next_work_info) {
708 // We need to wake up the loop in case the poll timeout needs to be
709 // adjusted. This will cause us to try to do work, but that's OK.
710 ScheduleWork();
711 }
712
HandleFdWatchCheck(FdWatchController * controller)713 bool MessagePumpGlib::HandleFdWatchCheck(FdWatchController* controller) {
714 DCHECK(controller);
715 gushort flags = controller->poll_fd_->revents;
716 return (flags & G_IO_IN) || (flags & G_IO_OUT);
717 }
718
HandleFdWatchDispatch(FdWatchController * controller)719 void MessagePumpGlib::HandleFdWatchDispatch(FdWatchController* controller) {
720 DCHECK(controller);
721 DCHECK(controller->poll_fd_);
722 gushort flags = controller->poll_fd_->revents;
723 if ((flags & G_IO_IN) && (flags & G_IO_OUT)) {
724 // Both callbacks will be called. It is necessary to check that
725 // |controller| is not destroyed.
726 bool controller_was_destroyed = false;
727 controller->was_destroyed_ = &controller_was_destroyed;
728 controller->NotifyCanWrite();
729 if (!controller_was_destroyed)
730 controller->NotifyCanRead();
731 if (!controller_was_destroyed)
732 controller->was_destroyed_ = nullptr;
733 } else if (flags & G_IO_IN) {
734 controller->NotifyCanRead();
735 } else if (flags & G_IO_OUT) {
736 controller->NotifyCanWrite();
737 }
738 }
739
ShouldQuit() const740 bool MessagePumpGlib::ShouldQuit() const {
741 CHECK(state_);
742 return state_->should_quit;
743 }
744
SetScopedWorkItem()745 void MessagePumpGlib::SetScopedWorkItem() {
746 // |state_| can be null during tests
747 if (!state_) {
748 return;
749 }
750 // If there exists a ScopedDoWorkItem in the current RunState, it cannot be
751 // overwritten.
752 CHECK(state_->scoped_do_work_item.IsNull());
753
754 // In the case that we're more than two work items deep, don't bother tracking
755 // individual native events anymore. Note that this won't cause out-of-order
756 // end work items, because the work item is cleared before entering the second
757 // DoWork().
758 if (state_->do_work_depth < 2) {
759 state_->scoped_do_work_item = state_->delegate->BeginWorkItem();
760 }
761 }
762
ClearScopedWorkItem()763 void MessagePumpGlib::ClearScopedWorkItem() {
764 // |state_| can be null during tests
765 if (!state_) {
766 return;
767 }
768
769 CHECK(!state_->scoped_do_work_item.IsNull());
770 // See identical check in SetScopedWorkItem
771 if (state_->do_work_depth < 2) {
772 state_->scoped_do_work_item = Delegate::ScopedDoWorkItem();
773 }
774 }
775
EnsureSetScopedWorkItem()776 void MessagePumpGlib::EnsureSetScopedWorkItem() {
777 // |state_| can be null during tests
778 if (!state_) {
779 return;
780 }
781 if (state_->scoped_do_work_item.IsNull()) {
782 SetScopedWorkItem();
783 }
784 }
785
EnsureClearedScopedWorkItem()786 void MessagePumpGlib::EnsureClearedScopedWorkItem() {
787 // |state_| can be null during tests
788 if (!state_) {
789 return;
790 }
791 if (!state_->scoped_do_work_item.IsNull()) {
792 ClearScopedWorkItem();
793 }
794 }
795
RegisterNested()796 void MessagePumpGlib::RegisterNested() {
797 // |state_| can be null during tests
798 if (!state_) {
799 return;
800 }
801 CHECK(state_->native_loop_do_work_item.IsNull());
802
803 // Transfer `scoped_do_work_item` to `native_do_work_item`, and so the
804 // ephemeral `scoped_do_work_item` will be coming in and out of existence on
805 // top of `native_do_work_item`, whose state hasn't been deleted.
806
807 if (state_->scoped_do_work_item.IsNull()) {
808 state_->native_loop_do_work_item = state_->delegate->BeginWorkItem();
809 } else {
810 // This clears state_->scoped_do_work_item.
811 state_->native_loop_do_work_item = std::move(state_->scoped_do_work_item);
812 }
813 SetScopedWorkItem();
814 ClearScopedWorkItem();
815 }
816
UnregisterNested()817 void MessagePumpGlib::UnregisterNested() {
818 // |state_| can be null during tests
819 if (!state_) {
820 return;
821 }
822 CHECK(!state_->native_loop_do_work_item.IsNull());
823
824 EnsureClearedScopedWorkItem();
825 // Nesting exits here.
826 state_->native_loop_do_work_item = Delegate::ScopedDoWorkItem();
827 }
828
NestIfRequired()829 void MessagePumpGlib::NestIfRequired() {
830 // |state_| can be null during tests
831 if (!state_) {
832 return;
833 }
834 if (state_->native_loop_do_work_item.IsNull() &&
835 state_->g_depth_on_iteration.has_value() &&
836 g_main_depth() != state_->g_depth_on_iteration.value()) {
837 RegisterNested();
838 }
839 }
840
UnnestIfRequired()841 void MessagePumpGlib::UnnestIfRequired() {
842 // |state_| can be null during tests
843 if (!state_) {
844 return;
845 }
846 if (!state_->native_loop_do_work_item.IsNull()) {
847 UnregisterNested();
848 }
849 }
850
OnEntryToGlib()851 void MessagePumpGlib::OnEntryToGlib() {
852 // |state_| can be null during tests
853 if (!state_) {
854 return;
855 }
856 CHECK(!state_->g_depth_on_iteration.has_value());
857 state_->g_depth_on_iteration.emplace(g_main_depth());
858 }
859
OnExitFromGlib()860 void MessagePumpGlib::OnExitFromGlib() {
861 // |state_| can be null during tests
862 if (!state_) {
863 return;
864 }
865 state_->g_depth_on_iteration.reset();
866 UnnestIfRequired();
867 }
868
869 } // namespace base
870