1 // Copyright 2013 The Chromium Authors. All rights reserved.
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_loop.h"
6
7 #include <algorithm>
8 #include <utility>
9
10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
12 #include "base/debug/task_annotator.h"
13 #include "base/logging.h"
14 #include "base/memory/ptr_util.h"
15 #include "base/message_loop/message_pump_default.h"
16 #include "base/message_loop/message_pump_for_io.h"
17 #include "base/message_loop/message_pump_for_ui.h"
18 #include "base/metrics/histogram_macros.h"
19 #include "base/run_loop.h"
20 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
21 #include "base/threading/thread_id_name_manager.h"
22 #include "base/threading/thread_task_runner_handle.h"
23 #include "base/trace_event/trace_event.h"
24
25 #if defined(OS_MACOSX)
26 #include "base/message_loop/message_pump_mac.h"
27 #endif
28
29 namespace base {
30
31 namespace {
32
33 MessageLoop::MessagePumpFactory* message_pump_for_ui_factory_ = nullptr;
34
ReturnPump(std::unique_ptr<MessagePump> pump)35 std::unique_ptr<MessagePump> ReturnPump(std::unique_ptr<MessagePump> pump) {
36 return pump;
37 }
38
39 enum class ScheduledWakeupResult {
40 // The MessageLoop went to sleep with a timeout and woke up because of that
41 // timeout.
42 kCompleted,
43 // The MessageLoop went to sleep with a timeout but was woken up before it
44 // fired.
45 kInterrupted,
46 };
47
48 // Reports a ScheduledWakeup's result when waking up from a non-infinite sleep.
49 // Reports are using a 14 day spread (maximum examined delay for
50 // https://crbug.com/850450#c3), with 50 buckets that still yields 7 buckets
51 // under 16ms and hence plenty of resolution.
ReportScheduledWakeupResult(ScheduledWakeupResult result,TimeDelta intended_sleep)52 void ReportScheduledWakeupResult(ScheduledWakeupResult result,
53 TimeDelta intended_sleep) {
54 switch (result) {
55 case ScheduledWakeupResult::kCompleted:
56 UMA_HISTOGRAM_CUSTOM_TIMES("MessageLoop.ScheduledSleep.Completed",
57 intended_sleep,
58 base::TimeDelta::FromMilliseconds(1),
59 base::TimeDelta::FromDays(14), 50);
60 break;
61 case ScheduledWakeupResult::kInterrupted:
62 UMA_HISTOGRAM_CUSTOM_TIMES("MessageLoop.ScheduledSleep.Interrupted",
63 intended_sleep,
64 base::TimeDelta::FromMilliseconds(1),
65 base::TimeDelta::FromDays(14), 50);
66 break;
67 }
68 }
69
70 } // namespace
71
72 class MessageLoop::Controller : public internal::IncomingTaskQueue::Observer {
73 public:
74 // Constructs a MessageLoopController which controls |message_loop|, notifying
75 // |task_annotator_| when tasks are queued scheduling work on |message_loop|
76 // as fits. |message_loop| and |task_annotator_| will not be used after
77 // DisconnectFromParent() returns.
78 Controller(MessageLoop* message_loop);
79
80 ~Controller() override;
81
82 // IncomingTaskQueue::Observer:
83 void WillQueueTask(PendingTask* task) final;
84 void DidQueueTask(bool was_empty) final;
85
86 void StartScheduling();
87
88 // Disconnects |message_loop_| from this Controller instance (DidQueueTask()
89 // will no-op from this point forward).
90 void DisconnectFromParent();
91
92 // Shares this Controller's TaskAnnotator with MessageLoop as TaskAnnotator
93 // requires DidQueueTask(x)/RunTask(x) to be invoked on the same TaskAnnotator
94 // instance.
task_annotator()95 debug::TaskAnnotator& task_annotator() { return task_annotator_; }
96
97 private:
98 // A TaskAnnotator which is owned by this Controller to be able to use it
99 // without locking |message_loop_lock_|. It cannot be owned by MessageLoop
100 // because this Controller cannot access |message_loop_| safely without the
101 // lock. Note: the TaskAnnotator API itself is thread-safe.
102 debug::TaskAnnotator task_annotator_;
103
104 // Lock that serializes |message_loop_->ScheduleWork()| and access to all
105 // members below.
106 base::Lock message_loop_lock_;
107
108 // Points to this Controller's outer MessageLoop instance. Null after
109 // DisconnectFromParent().
110 MessageLoop* message_loop_;
111
112 // False until StartScheduling() is called.
113 bool is_ready_for_scheduling_ = false;
114
115 // True if DidQueueTask() has been called before StartScheduling(); letting it
116 // know whether it needs to ScheduleWork() right away or not.
117 bool pending_schedule_work_ = false;
118
119 DISALLOW_COPY_AND_ASSIGN(Controller);
120 };
121
Controller(MessageLoop * message_loop)122 MessageLoop::Controller::Controller(MessageLoop* message_loop)
123 : message_loop_(message_loop) {}
124
~Controller()125 MessageLoop::Controller::~Controller() {
126 DCHECK(!message_loop_)
127 << "DisconnectFromParent() needs to be invoked before destruction.";
128 }
129
WillQueueTask(PendingTask * task)130 void MessageLoop::Controller::WillQueueTask(PendingTask* task) {
131 task_annotator_.WillQueueTask("MessageLoop::PostTask", task);
132 }
133
DidQueueTask(bool was_empty)134 void MessageLoop::Controller::DidQueueTask(bool was_empty) {
135 // Avoid locking if we don't need to schedule.
136 if (!was_empty)
137 return;
138
139 AutoLock auto_lock(message_loop_lock_);
140
141 if (message_loop_ && is_ready_for_scheduling_)
142 message_loop_->ScheduleWork();
143 else
144 pending_schedule_work_ = true;
145 }
146
StartScheduling()147 void MessageLoop::Controller::StartScheduling() {
148 AutoLock lock(message_loop_lock_);
149 DCHECK(message_loop_);
150 DCHECK(!is_ready_for_scheduling_);
151 is_ready_for_scheduling_ = true;
152 if (pending_schedule_work_)
153 message_loop_->ScheduleWork();
154 }
155
DisconnectFromParent()156 void MessageLoop::Controller::DisconnectFromParent() {
157 AutoLock lock(message_loop_lock_);
158 message_loop_ = nullptr;
159 }
160
161 //------------------------------------------------------------------------------
162
MessageLoop(Type type)163 MessageLoop::MessageLoop(Type type)
164 : MessageLoop(type, MessagePumpFactoryCallback()) {
165 BindToCurrentThread();
166 }
167
MessageLoop(std::unique_ptr<MessagePump> pump)168 MessageLoop::MessageLoop(std::unique_ptr<MessagePump> pump)
169 : MessageLoop(TYPE_CUSTOM, BindOnce(&ReturnPump, std::move(pump))) {
170 BindToCurrentThread();
171 }
172
~MessageLoop()173 MessageLoop::~MessageLoop() {
174 // If |pump_| is non-null, this message loop has been bound and should be the
175 // current one on this thread. Otherwise, this loop is being destructed before
176 // it was bound to a thread, so a different message loop (or no loop at all)
177 // may be current.
178 DCHECK((pump_ && MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)) ||
179 (!pump_ && !MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)));
180
181 // iOS just attaches to the loop, it doesn't Run it.
182 // TODO(stuartmorgan): Consider wiring up a Detach().
183 #if !defined(OS_IOS)
184 // There should be no active RunLoops on this thread, unless this MessageLoop
185 // isn't bound to the current thread (see other condition at the top of this
186 // method).
187 DCHECK(
188 (!pump_ && !MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)) ||
189 !RunLoop::IsRunningOnCurrentThread());
190 #endif // !defined(OS_IOS)
191
192 #if defined(OS_WIN)
193 if (in_high_res_mode_)
194 Time::ActivateHighResolutionTimer(false);
195 #endif
196 // Clean up any unprocessed tasks, but take care: deleting a task could
197 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
198 // limit on the number of times we will allow a deleted task to generate more
199 // tasks. Normally, we should only pass through this loop once or twice. If
200 // we end up hitting the loop limit, then it is probably due to one task that
201 // is being stubborn. Inspect the queues to see who is left.
202 bool tasks_remain;
203 for (int i = 0; i < 100; ++i) {
204 DeletePendingTasks();
205 // If we end up with empty queues, then break out of the loop.
206 tasks_remain = incoming_task_queue_->triage_tasks().HasTasks();
207 if (!tasks_remain)
208 break;
209 }
210 DCHECK(!tasks_remain);
211
212 // Let interested parties have one last shot at accessing this.
213 for (auto& observer : destruction_observers_)
214 observer.WillDestroyCurrentMessageLoop();
215
216 thread_task_runner_handle_.reset();
217
218 // Tell the incoming queue that we are dying.
219 message_loop_controller_->DisconnectFromParent();
220 incoming_task_queue_->Shutdown();
221 incoming_task_queue_ = nullptr;
222 unbound_task_runner_ = nullptr;
223 task_runner_ = nullptr;
224
225 // OK, now make it so that no one can find us.
226 if (MessageLoopCurrent::IsBoundToCurrentThreadInternal(this))
227 MessageLoopCurrent::UnbindFromCurrentThreadInternal(this);
228 }
229
230 // static
current()231 MessageLoopCurrent MessageLoop::current() {
232 return MessageLoopCurrent::Get();
233 }
234
235 // static
InitMessagePumpForUIFactory(MessagePumpFactory * factory)236 bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory* factory) {
237 if (message_pump_for_ui_factory_)
238 return false;
239
240 message_pump_for_ui_factory_ = factory;
241 return true;
242 }
243
244 // static
CreateMessagePumpForType(Type type)245 std::unique_ptr<MessagePump> MessageLoop::CreateMessagePumpForType(Type type) {
246 #if !defined(OS_ANDROID)
247 if (type == MessageLoop::TYPE_UI) {
248 if (message_pump_for_ui_factory_)
249 return message_pump_for_ui_factory_();
250 #if defined(OS_IOS) || defined(OS_MACOSX)
251 return MessagePumpMac::Create();
252 #elif defined(OS_NACL) || defined(OS_AIX)
253 // Currently NaCl and AIX don't have a UI MessageLoop.
254 // TODO(abarth): Figure out if we need this.
255 NOTREACHED();
256 return nullptr;
257 #else
258 return std::make_unique<MessagePumpForUI>();
259 #endif
260 }
261 #endif
262
263 if (type == MessageLoop::TYPE_IO)
264 return std::unique_ptr<MessagePump>(new MessagePumpForIO());
265
266 #if defined(OS_ANDROID) && 0
267 if (type == MessageLoop::TYPE_JAVA)
268 return std::unique_ptr<MessagePump>(new MessagePumpForUI());
269 #endif
270
271 DCHECK_EQ(MessageLoop::TYPE_DEFAULT, type);
272 #if defined(OS_IOS)
273 // On iOS, a native runloop is always required to pump system work.
274 return std::make_unique<MessagePumpCFRunLoop>();
275 #else
276 return std::make_unique<MessagePumpDefault>();
277 #endif
278 }
279
IsType(Type type) const280 bool MessageLoop::IsType(Type type) const {
281 return type_ == type;
282 }
283
284 // TODO(gab): Migrate TaskObservers to RunLoop as part of separating concerns
285 // between MessageLoop and RunLoop and making MessageLoop a swappable
286 // implementation detail. http://crbug.com/703346
AddTaskObserver(TaskObserver * task_observer)287 void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
288 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
289 task_observers_.AddObserver(task_observer);
290 }
291
RemoveTaskObserver(TaskObserver * task_observer)292 void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
293 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
294 task_observers_.RemoveObserver(task_observer);
295 }
296
IsIdleForTesting()297 bool MessageLoop::IsIdleForTesting() {
298 // Have unprocessed tasks? (this reloads the work queue if necessary)
299 if (incoming_task_queue_->triage_tasks().HasTasks())
300 return false;
301
302 // Have unprocessed deferred tasks which can be processed at this run-level?
303 if (incoming_task_queue_->deferred_tasks().HasTasks() &&
304 !RunLoop::IsNestedOnCurrentThread()) {
305 return false;
306 }
307
308 return true;
309 }
310
311 //------------------------------------------------------------------------------
312
313 // static
CreateUnbound(Type type,MessagePumpFactoryCallback pump_factory)314 std::unique_ptr<MessageLoop> MessageLoop::CreateUnbound(
315 Type type,
316 MessagePumpFactoryCallback pump_factory) {
317 return WrapUnique(new MessageLoop(type, std::move(pump_factory)));
318 }
319
320 // TODO(gab): Avoid bare new + WrapUnique below when introducing
321 // SequencedTaskSource in follow-up @
322 // https://chromium-review.googlesource.com/c/chromium/src/+/1088762.
MessageLoop(Type type,MessagePumpFactoryCallback pump_factory)323 MessageLoop::MessageLoop(Type type, MessagePumpFactoryCallback pump_factory)
324 : MessageLoopCurrent(this),
325 type_(type),
326 pump_factory_(std::move(pump_factory)),
327 message_loop_controller_(new Controller(this)),
328 incoming_task_queue_(MakeRefCounted<internal::IncomingTaskQueue>(
329 WrapUnique(message_loop_controller_))),
330 unbound_task_runner_(MakeRefCounted<internal::MessageLoopTaskRunner>(
331 incoming_task_queue_)),
332 task_runner_(unbound_task_runner_) {
333 // If type is TYPE_CUSTOM non-null pump_factory must be given.
334 DCHECK(type_ != TYPE_CUSTOM || !pump_factory_.is_null());
335
336 // Bound in BindToCurrentThread();
337 DETACH_FROM_THREAD(bound_thread_checker_);
338 }
339
BindToCurrentThread()340 void MessageLoop::BindToCurrentThread() {
341 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
342
343 DCHECK(!pump_);
344 if (!pump_factory_.is_null())
345 pump_ = std::move(pump_factory_).Run();
346 else
347 pump_ = CreateMessagePumpForType(type_);
348
349 DCHECK(!MessageLoopCurrent::IsSet())
350 << "should only have one message loop per thread";
351 MessageLoopCurrent::BindToCurrentThreadInternal(this);
352
353 message_loop_controller_->StartScheduling();
354 unbound_task_runner_->BindToCurrentThread();
355 unbound_task_runner_ = nullptr;
356 SetThreadTaskRunnerHandle();
357 thread_id_ = PlatformThread::CurrentId();
358
359 scoped_set_sequence_local_storage_map_for_current_thread_ = std::make_unique<
360 internal::ScopedSetSequenceLocalStorageMapForCurrentThread>(
361 &sequence_local_storage_map_);
362
363 RunLoop::RegisterDelegateForCurrentThread(this);
364
365 #if defined(OS_ANDROID) && 0
366 // On Android, attach to the native loop when there is one.
367 if (type_ == TYPE_UI || type_ == TYPE_JAVA)
368 static_cast<MessagePumpForUI*>(pump_.get())->Attach(this);
369 #endif
370 }
371
GetThreadName() const372 std::string MessageLoop::GetThreadName() const {
373 DCHECK_NE(kInvalidThreadId, thread_id_)
374 << "GetThreadName() must only be called after BindToCurrentThread()'s "
375 << "side-effects have been synchronized with this thread.";
376 return ThreadIdNameManager::GetInstance()->GetName(thread_id_);
377 }
378
SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner)379 void MessageLoop::SetTaskRunner(
380 scoped_refptr<SingleThreadTaskRunner> task_runner) {
381 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
382
383 DCHECK(task_runner);
384 DCHECK(task_runner->BelongsToCurrentThread());
385 DCHECK(!unbound_task_runner_);
386 task_runner_ = std::move(task_runner);
387 SetThreadTaskRunnerHandle();
388 }
389
ClearTaskRunnerForTesting()390 void MessageLoop::ClearTaskRunnerForTesting() {
391 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
392
393 DCHECK(!unbound_task_runner_);
394 task_runner_ = nullptr;
395 thread_task_runner_handle_.reset();
396 }
397
Run(bool application_tasks_allowed)398 void MessageLoop::Run(bool application_tasks_allowed) {
399 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
400 if (application_tasks_allowed && !task_execution_allowed_) {
401 // Allow nested task execution as explicitly requested.
402 DCHECK(RunLoop::IsNestedOnCurrentThread());
403 task_execution_allowed_ = true;
404 pump_->Run(this);
405 task_execution_allowed_ = false;
406 } else {
407 pump_->Run(this);
408 }
409 }
410
Quit()411 void MessageLoop::Quit() {
412 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
413 pump_->Quit();
414 }
415
EnsureWorkScheduled()416 void MessageLoop::EnsureWorkScheduled() {
417 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
418 if (incoming_task_queue_->triage_tasks().HasTasks())
419 pump_->ScheduleWork();
420 }
421
SetThreadTaskRunnerHandle()422 void MessageLoop::SetThreadTaskRunnerHandle() {
423 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
424 // Clear the previous thread task runner first, because only one can exist at
425 // a time.
426 thread_task_runner_handle_.reset();
427 thread_task_runner_handle_.reset(new ThreadTaskRunnerHandle(task_runner_));
428 }
429
ProcessNextDelayedNonNestableTask()430 bool MessageLoop::ProcessNextDelayedNonNestableTask() {
431 if (RunLoop::IsNestedOnCurrentThread())
432 return false;
433
434 while (incoming_task_queue_->deferred_tasks().HasTasks()) {
435 PendingTask pending_task = incoming_task_queue_->deferred_tasks().Pop();
436 if (!pending_task.task.IsCancelled()) {
437 RunTask(&pending_task);
438 return true;
439 }
440 }
441
442 return false;
443 }
444
RunTask(PendingTask * pending_task)445 void MessageLoop::RunTask(PendingTask* pending_task) {
446 DCHECK(task_execution_allowed_);
447
448 // Execute the task and assume the worst: It is probably not reentrant.
449 task_execution_allowed_ = false;
450
451 TRACE_TASK_EXECUTION("MessageLoop::RunTask", *pending_task);
452
453 for (auto& observer : task_observers_)
454 observer.WillProcessTask(*pending_task);
455 message_loop_controller_->task_annotator().RunTask("MessageLoop::PostTask",
456 pending_task);
457 for (auto& observer : task_observers_)
458 observer.DidProcessTask(*pending_task);
459
460 task_execution_allowed_ = true;
461 }
462
DeferOrRunPendingTask(PendingTask pending_task)463 bool MessageLoop::DeferOrRunPendingTask(PendingTask pending_task) {
464 if (pending_task.nestable == Nestable::kNestable ||
465 !RunLoop::IsNestedOnCurrentThread()) {
466 RunTask(&pending_task);
467 // Show that we ran a task (Note: a new one might arrive as a
468 // consequence!).
469 return true;
470 }
471
472 // We couldn't run the task now because we're in a nested run loop
473 // and the task isn't nestable.
474 incoming_task_queue_->deferred_tasks().Push(std::move(pending_task));
475 return false;
476 }
477
DeletePendingTasks()478 void MessageLoop::DeletePendingTasks() {
479 incoming_task_queue_->triage_tasks().Clear();
480 incoming_task_queue_->deferred_tasks().Clear();
481 // TODO(robliao): Determine if we can move delayed task destruction before
482 // deferred tasks to maintain the MessagePump DoWork, DoDelayedWork, and
483 // DoIdleWork processing order.
484 incoming_task_queue_->delayed_tasks().Clear();
485 }
486
ScheduleWork()487 void MessageLoop::ScheduleWork() {
488 pump_->ScheduleWork();
489 }
490
DoWork()491 bool MessageLoop::DoWork() {
492 if (!task_execution_allowed_)
493 return false;
494
495 // Execute oldest task.
496 while (incoming_task_queue_->triage_tasks().HasTasks()) {
497 if (!scheduled_wakeup_.next_run_time.is_null()) {
498 // While the frontmost task may racily be ripe. The MessageLoop was awaken
499 // without needing the timeout anyways. Since this metric is about
500 // determining whether sleeping for long periods ever succeeds: it's
501 // easier to just consider any untriaged task as an interrupt (this also
502 // makes the logic simpler for untriaged delayed tasks which may alter the
503 // top of the task queue prior to DoDelayedWork() but did cause a wakeup
504 // regardless -- per currently requiring this immediate triage step even
505 // for long delays).
506 ReportScheduledWakeupResult(ScheduledWakeupResult::kInterrupted,
507 scheduled_wakeup_.intended_sleep);
508 scheduled_wakeup_ = ScheduledWakeup();
509 }
510
511 PendingTask pending_task = incoming_task_queue_->triage_tasks().Pop();
512 if (pending_task.task.IsCancelled())
513 continue;
514
515 if (!pending_task.delayed_run_time.is_null()) {
516 int sequence_num = pending_task.sequence_num;
517 TimeTicks delayed_run_time = pending_task.delayed_run_time;
518 incoming_task_queue_->delayed_tasks().Push(std::move(pending_task));
519 // If we changed the topmost task, then it is time to reschedule.
520 if (incoming_task_queue_->delayed_tasks().Peek().sequence_num ==
521 sequence_num) {
522 pump_->ScheduleDelayedWork(delayed_run_time);
523 }
524 } else if (DeferOrRunPendingTask(std::move(pending_task))) {
525 return true;
526 }
527 }
528
529 // Nothing happened.
530 return false;
531 }
532
DoDelayedWork(TimeTicks * next_delayed_work_time)533 bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
534 if (!task_execution_allowed_) {
535 *next_delayed_work_time = TimeTicks();
536 // |scheduled_wakeup_| isn't used in nested loops that don't process
537 // application tasks.
538 DCHECK(scheduled_wakeup_.next_run_time.is_null());
539 return false;
540 }
541
542 if (!incoming_task_queue_->delayed_tasks().HasTasks()) {
543 *next_delayed_work_time = TimeTicks();
544
545 // It's possible to be woken up by a system event and have it cancel the
546 // upcoming delayed task from under us before DoDelayedWork() -- see comment
547 // under |next_run_time > recent_time_|. This condition covers the special
548 // case where such a system event cancelled *all* pending delayed tasks.
549 if (!scheduled_wakeup_.next_run_time.is_null()) {
550 ReportScheduledWakeupResult(ScheduledWakeupResult::kInterrupted,
551 scheduled_wakeup_.intended_sleep);
552 scheduled_wakeup_ = ScheduledWakeup();
553 }
554
555 return false;
556 }
557
558 // When we "fall behind", there will be a lot of tasks in the delayed work
559 // queue that are ready to run. To increase efficiency when we fall behind,
560 // we will only call Time::Now() intermittently, and then process all tasks
561 // that are ready to run before calling it again. As a result, the more we
562 // fall behind (and have a lot of ready-to-run delayed tasks), the more
563 // efficient we'll be at handling the tasks.
564
565 TimeTicks next_run_time =
566 incoming_task_queue_->delayed_tasks().Peek().delayed_run_time;
567
568 if (next_run_time > recent_time_) {
569 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
570 if (next_run_time > recent_time_) {
571 *next_delayed_work_time = next_run_time;
572
573 // If the loop was woken up early by an untriaged task:
574 // |scheduled_wakeup_| will have been handled already in DoWork(). If it
575 // wasn't, it means the early wake up was caused by a system event (e.g.
576 // MessageLoopForUI or IO).
577 if (!scheduled_wakeup_.next_run_time.is_null()) {
578 // Handling the system event may have resulted in cancelling the
579 // upcoming delayed task (and then it being pruned by
580 // DelayedTaskQueue::HasTasks()); hence, we cannot check for strict
581 // equality here. We can however check that the pending task is either
582 // still there or that a later delay replaced it in front of the queue.
583 // There shouldn't have been new tasks added in |delayed_tasks()| per
584 // DoWork() not having triaged new tasks since the last DoIdleWork().
585 DCHECK_GE(next_run_time, scheduled_wakeup_.next_run_time);
586
587 ReportScheduledWakeupResult(ScheduledWakeupResult::kInterrupted,
588 scheduled_wakeup_.intended_sleep);
589 scheduled_wakeup_ = ScheduledWakeup();
590 }
591
592 return false;
593 }
594 }
595
596 if (next_run_time == scheduled_wakeup_.next_run_time) {
597 ReportScheduledWakeupResult(ScheduledWakeupResult::kCompleted,
598 scheduled_wakeup_.intended_sleep);
599 scheduled_wakeup_ = ScheduledWakeup();
600 }
601
602 PendingTask pending_task = incoming_task_queue_->delayed_tasks().Pop();
603
604 if (incoming_task_queue_->delayed_tasks().HasTasks()) {
605 *next_delayed_work_time =
606 incoming_task_queue_->delayed_tasks().Peek().delayed_run_time;
607 }
608
609 return DeferOrRunPendingTask(std::move(pending_task));
610 }
611
DoIdleWork()612 bool MessageLoop::DoIdleWork() {
613 if (ProcessNextDelayedNonNestableTask())
614 return true;
615
616 #if defined(OS_WIN)
617 bool need_high_res_timers = false;
618 #endif
619
620 // Do not report idle metrics nor do any logic related to delayed tasks if
621 // about to quit the loop and/or in a nested loop where
622 // |!task_execution_allowed_|. In the former case, the loop isn't going to
623 // sleep and in the latter case DoDelayedWork() will not actually do the work
624 // this is prepping for.
625 if (ShouldQuitWhenIdle()) {
626 pump_->Quit();
627 } else if (task_execution_allowed_) {
628 incoming_task_queue_->ReportMetricsOnIdle();
629
630 if (incoming_task_queue_->delayed_tasks().HasTasks()) {
631 TimeTicks scheduled_wakeup_time =
632 incoming_task_queue_->delayed_tasks().Peek().delayed_run_time;
633
634 if (!scheduled_wakeup_.next_run_time.is_null()) {
635 // It's possible for DoIdleWork() to be invoked twice in a row (e.g. if
636 // the MessagePump processed system work and became idle twice in a row
637 // without application tasks in between -- some pumps with a native
638 // message loop do not invoke DoWork() / DoDelayedWork() when awaken for
639 // system work only). As in DoDelayedWork(), we cannot check for strict
640 // equality below as the system work may have cancelled the frontmost
641 // task.
642 DCHECK_GE(scheduled_wakeup_time, scheduled_wakeup_.next_run_time);
643
644 ReportScheduledWakeupResult(ScheduledWakeupResult::kInterrupted,
645 scheduled_wakeup_.intended_sleep);
646 scheduled_wakeup_ = ScheduledWakeup();
647 }
648
649 // Store the remaining delay as well as the programmed wakeup time in
650 // order to know next time this MessageLoop wakes up whether it woke up
651 // because of this pending task (is it still the frontmost task in the
652 // queue?) and be able to report the slept delta (which is lost if not
653 // saved here).
654 scheduled_wakeup_ = ScheduledWakeup{
655 scheduled_wakeup_time, scheduled_wakeup_time - TimeTicks::Now()};
656 }
657
658 #if defined(OS_WIN)
659 // On Windows we activate the high resolution timer so that the wait
660 // _if_ triggered by the timer happens with good resolution. If we don't
661 // do this the default resolution is 15ms which might not be acceptable
662 // for some tasks.
663 need_high_res_timers =
664 incoming_task_queue_->HasPendingHighResolutionTasks();
665 #endif
666 }
667
668 #if defined(OS_WIN)
669 if (in_high_res_mode_ != need_high_res_timers) {
670 in_high_res_mode_ = need_high_res_timers;
671 Time::ActivateHighResolutionTimer(in_high_res_mode_);
672 }
673 #endif
674
675 // When we return we will do a kernel wait for more tasks.
676 return false;
677 }
678
679 #if !defined(OS_NACL) && !defined(OS_ANDROID)
680
681 //------------------------------------------------------------------------------
682 // MessageLoopForUI
683
MessageLoopForUI(Type type)684 MessageLoopForUI::MessageLoopForUI(Type type) : MessageLoop(type) {
685 #if defined(OS_ANDROID)
686 DCHECK(type == TYPE_UI || type == TYPE_JAVA);
687 #else
688 DCHECK_EQ(type, TYPE_UI);
689 #endif
690 }
691
692 // static
current()693 MessageLoopCurrentForUI MessageLoopForUI::current() {
694 return MessageLoopCurrentForUI::Get();
695 }
696
697 // static
IsCurrent()698 bool MessageLoopForUI::IsCurrent() {
699 return MessageLoopCurrentForUI::IsSet();
700 }
701
702 #if defined(OS_IOS)
Attach()703 void MessageLoopForUI::Attach() {
704 static_cast<MessagePumpUIApplication*>(pump_.get())->Attach(this);
705 }
706 #endif // defined(OS_IOS)
707
708 #if defined(OS_ANDROID)
Abort()709 void MessageLoopForUI::Abort() {
710 static_cast<MessagePumpForUI*>(pump_.get())->Abort();
711 }
712
IsAborted()713 bool MessageLoopForUI::IsAborted() {
714 return static_cast<MessagePumpForUI*>(pump_.get())->IsAborted();
715 }
716
QuitWhenIdle(base::OnceClosure callback)717 void MessageLoopForUI::QuitWhenIdle(base::OnceClosure callback) {
718 static_cast<MessagePumpForUI*>(pump_.get())
719 ->QuitWhenIdle(std::move(callback));
720 }
721 #endif // defined(OS_ANDROID)
722
723 #if defined(OS_WIN)
EnableWmQuit()724 void MessageLoopForUI::EnableWmQuit() {
725 static_cast<MessagePumpForUI*>(pump_.get())->EnableWmQuit();
726 }
727 #endif // defined(OS_WIN)
728
729 #endif // !defined(OS_NACL) && !defined(OS_ANDROID)
730
731 //------------------------------------------------------------------------------
732 // MessageLoopForIO
733
734 // static
current()735 MessageLoopCurrentForIO MessageLoopForIO::current() {
736 return MessageLoopCurrentForIO::Get();
737 }
738
739 // static
IsCurrent()740 bool MessageLoopForIO::IsCurrent() {
741 return MessageLoopCurrentForIO::IsSet();
742 }
743
744 } // namespace base
745