blob: bf0d25da975981b361ab576ddb6eeb6b26cc7021 [file] [log] [blame]
jar@chromium.org34571142011-04-05 13:48:53 +09001// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
darin@google.com6ddeb842008-08-15 16:31:20 +09005#include "base/message_loop.h"
6
darin@google.com981f3552008-08-16 12:09:05 +09007#include <algorithm>
8
ajwong@chromium.org94d2a582011-04-21 01:02:23 +09009#include "base/bind.h"
mmentovai@google.comfa5f9932008-08-22 07:26:06 +090010#include "base/compiler_specific.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090011#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090012#include "base/logging.h"
darin@google.com12d40bb2008-08-20 03:36:23 +090013#include "base/message_pump_default.h"
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090014#include "base/metrics/histogram.h"
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090015#include "base/scoped_ptr.h"
timurrrr@chromium.org490200b2011-01-05 04:06:51 +090016#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
brettw@chromium.org63965582010-12-31 07:18:56 +090017#include "base/threading/thread_local.h"
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090018#include "base/tracked_objects.h"
initial.commit3f4a7322008-07-27 06:49:38 +090019
mark@chromium.org059d0492008-09-24 06:08:28 +090020#if defined(OS_MACOSX)
21#include "base/message_pump_mac.h"
22#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090023#if defined(OS_POSIX)
24#include "base/message_pump_libevent.h"
25#endif
evan@chromium.org875bb6e2009-12-29 09:32:52 +090026#if defined(OS_POSIX) && !defined(OS_MACOSX)
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090027#include <gdk/gdk.h>
28#include <gdk/gdkx.h>
dsh@google.com119a2522008-10-04 01:52:59 +090029#include "base/message_pump_glib.h"
30#endif
rjkroege@google.com3080f442010-10-23 01:17:47 +090031#if defined(TOUCH_UI)
32#include "base/message_pump_glib_x.h"
33#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090034
dsh@google.com0f8dd262008-10-28 05:43:33 +090035using base::TimeDelta;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090036using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090037
erg@chromium.orga7528522010-07-16 02:23:23 +090038namespace {
39
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090040// A lazily created thread local storage for quick access to a thread's message
41// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090042base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090043 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090044
initial.commit3f4a7322008-07-27 06:49:38 +090045// Logical events for Histogram profiling. Run with -message-loop-histogrammer
46// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090047const int kTaskRunEvent = 0x1;
48const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090049
50// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090051const int kLeastNonZeroMessageId = 1;
52const int kMaxMessageId = 1099;
53const int kNumberOfDistinctMessagesDisplayed = 1100;
54
55// Provide a macro that takes an expression (such as a constant, or macro
56// constant) and creates a pair to initalize an array of pairs. In this case,
57// our pair consists of the expressions value, and the "stringized" version
58// of the expression (i.e., the exrpression put in quotes). For example, if
59// we have:
60// #define FOO 2
61// #define BAR 5
62// then the following:
63// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
64// will expand to:
65// {7, "FOO + BAR"}
66// We use the resulting array as an argument to our histogram, which reads the
67// number as a bucket identifier, and proceeds to use the corresponding name
68// in the pair (i.e., the quoted string) when printing out a histogram.
69#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
70
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090071const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090072 // Provide some pretty print capability in our histogram for our internal
73 // messages.
74
75 // A few events we handle (kindred to messages), and used to profile actions.
76 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
77 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
78
79 {-1, NULL} // The list must be null terminated, per API to histogram.
80};
81
82bool enable_histogrammer_ = false;
83
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090084// TODO(ajwong): This is one use case for having a Owned() tag that behaves
85// like a "Unique" pointer. If we had that, and Tasks were always safe to
86// delete on MessageLoop shutdown, this class could just be a function.
87class TaskClosureAdapter : public base::RefCounted<TaskClosureAdapter> {
88 public:
89 // |should_leak_task| points to a flag variable that can be used to determine
90 // if this class should leak the Task on destruction. This is important
91 // at MessageLoop shutdown since not all tasks can be safely deleted without
92 // running. See MessageLoop::DeletePendingTasks() for the exact behavior
93 // of when a Task should be deleted. It is subtle.
94 TaskClosureAdapter(Task* task, bool* should_leak_task)
95 : task_(task),
96 should_leak_task_(should_leak_task) {
97 }
98
99 void Run() {
100 task_->Run();
101 delete task_;
102 task_ = NULL;
103 }
104
105 private:
106 friend class base::RefCounted<TaskClosureAdapter>;
107
108 ~TaskClosureAdapter() {
109 if (!*should_leak_task_) {
110 delete task_;
111 }
112 }
113
114 Task* task_;
115 bool* should_leak_task_;
116};
117
erg@chromium.orga7528522010-07-16 02:23:23 +0900118} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +0900119
120//------------------------------------------------------------------------------
121
darin@google.com981f3552008-08-16 12:09:05 +0900122#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900123
initial.commit3f4a7322008-07-27 06:49:38 +0900124// Upon a SEH exception in this thread, it restores the original unhandled
125// exception filter.
126static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
127 ::SetUnhandledExceptionFilter(old_filter);
128 return EXCEPTION_CONTINUE_SEARCH;
129}
130
131// Retrieves a pointer to the current unhandled exception filter. There
132// is no standalone getter method.
133static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
134 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
135 top_filter = ::SetUnhandledExceptionFilter(0);
136 ::SetUnhandledExceptionFilter(top_filter);
137 return top_filter;
138}
139
darin@google.com981f3552008-08-16 12:09:05 +0900140#endif // defined(OS_WIN)
141
initial.commit3f4a7322008-07-27 06:49:38 +0900142//------------------------------------------------------------------------------
143
erg@chromium.org493f5f62010-07-16 06:03:54 +0900144MessageLoop::TaskObserver::TaskObserver() {
145}
146
147MessageLoop::TaskObserver::~TaskObserver() {
148}
149
150MessageLoop::DestructionObserver::~DestructionObserver() {
151}
152
153//------------------------------------------------------------------------------
154
darin@google.comd936b5b2008-08-26 14:53:57 +0900155MessageLoop::MessageLoop(Type type)
156 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900157 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900158 exception_restoration_(false),
jar@chromium.org34571142011-04-05 13:48:53 +0900159 message_histogram_(NULL),
darin@google.combe165ae2008-09-07 17:08:29 +0900160 state_(NULL),
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900161 should_leak_tasks_(true),
ananta@chromium.orgc542fec2011-03-24 12:40:28 +0900162#ifdef OS_WIN
163 os_modal_loop_(false),
164#endif // OS_WIN
darin@google.combe165ae2008-09-07 17:08:29 +0900165 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900166 DCHECK(!current()) << "should only have one message loop per thread";
167 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900168
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900169// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900170#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900171#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
172#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
173#elif defined(OS_MACOSX)
174#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
175#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900176#elif defined(TOUCH_UI)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900177#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900178#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900179#elif defined(OS_NACL)
180// Currently NaCl doesn't have a UI or an IO MessageLoop.
181// TODO(abarth): Figure out if we need these.
182#define MESSAGE_PUMP_UI NULL
183#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900184#elif defined(OS_POSIX) // POSIX but not MACOSX.
185#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
186#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900187#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900188#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900189#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900190
191 if (type_ == TYPE_UI) {
192 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900193 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900194 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900195 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900196 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900197 pump_ = new base::MessagePumpDefault();
198 }
initial.commit3f4a7322008-07-27 06:49:38 +0900199}
200
201MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900202 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900203
darin@google.com0e500502008-09-09 14:55:35 +0900204 DCHECK(!state_);
205
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900206 // Clean up any unprocessed tasks, but take care: deleting a task could
207 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
208 // limit on the number of times we will allow a deleted task to generate more
209 // tasks. Normally, we should only pass through this loop once or twice. If
210 // we end up hitting the loop limit, then it is probably due to one task that
211 // is being stubborn. Inspect the queues to see who is left.
212 bool did_work;
213 for (int i = 0; i < 100; ++i) {
214 DeletePendingTasks();
215 ReloadWorkQueue();
216 // If we end up with empty queues, then break out of the loop.
217 did_work = DeletePendingTasks();
218 if (!did_work)
219 break;
darin@google.com0e500502008-09-09 14:55:35 +0900220 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900221 DCHECK(!did_work);
222
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900223 // Let interested parties have one last shot at accessing this.
224 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
225 WillDestroyCurrentMessageLoop());
226
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900227 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900228 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900229}
230
erg@google.com67a25432011-01-08 05:23:43 +0900231// static
232MessageLoop* MessageLoop::current() {
233 // TODO(darin): sadly, we cannot enable this yet since people call us even
234 // when they have no intention of using us.
235 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
236 return lazy_tls_ptr.Pointer()->Get();
237}
238
239// static
240void MessageLoop::EnableHistogrammer(bool enable) {
241 enable_histogrammer_ = enable;
242}
243
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900244void MessageLoop::AddDestructionObserver(
245 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900246 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900247 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900248}
249
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900250void MessageLoop::RemoveDestructionObserver(
251 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900252 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900253 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900254}
255
darin@google.combe165ae2008-09-07 17:08:29 +0900256void MessageLoop::PostTask(
257 const tracked_objects::Location& from_here, Task* task) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900258 PendingTask pending_task(
259 base::Bind(&TaskClosureAdapter::Run,
260 new TaskClosureAdapter(task, &should_leak_tasks_)),
261 from_here,
262 CalculateDelayedRuntime(0), true);
263 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900264}
265
266void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900267 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900268 PendingTask pending_task(
269 base::Bind(&TaskClosureAdapter::Run,
270 new TaskClosureAdapter(task, &should_leak_tasks_)),
271 from_here,
272 CalculateDelayedRuntime(delay_ms), true);
273 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900274}
275
276void MessageLoop::PostNonNestableTask(
277 const tracked_objects::Location& from_here, Task* task) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900278 PendingTask pending_task(
279 base::Bind(&TaskClosureAdapter::Run,
280 new TaskClosureAdapter(task, &should_leak_tasks_)),
281 from_here,
282 CalculateDelayedRuntime(0), false);
283 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900284}
285
286void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900287 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900288 PendingTask pending_task(
289 base::Bind(&TaskClosureAdapter::Run,
290 new TaskClosureAdapter(task, &should_leak_tasks_)),
291 from_here,
292 CalculateDelayedRuntime(delay_ms), false);
293 AddToIncomingQueue(&pending_task);
294}
295
296void MessageLoop::PostTask(
297 const tracked_objects::Location& from_here, const base::Closure& task) {
298 DCHECK(!task.is_null());
299 PendingTask pending_task(task, from_here, CalculateDelayedRuntime(0), true);
300 AddToIncomingQueue(&pending_task);
301}
302
303void MessageLoop::PostDelayedTask(
304 const tracked_objects::Location& from_here, const base::Closure& task,
305 int64 delay_ms) {
306 DCHECK(!task.is_null());
307 PendingTask pending_task(task, from_here,
308 CalculateDelayedRuntime(delay_ms), true);
309 AddToIncomingQueue(&pending_task);
310}
311
312void MessageLoop::PostNonNestableTask(
313 const tracked_objects::Location& from_here, const base::Closure& task) {
314 DCHECK(!task.is_null());
315 PendingTask pending_task(task, from_here, CalculateDelayedRuntime(0), false);
316 AddToIncomingQueue(&pending_task);
317}
318
319void MessageLoop::PostNonNestableDelayedTask(
320 const tracked_objects::Location& from_here, const base::Closure& task,
321 int64 delay_ms) {
322 DCHECK(!task.is_null());
323 PendingTask pending_task(task, from_here,
324 CalculateDelayedRuntime(delay_ms), false);
325 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900326}
327
erg@google.com67a25432011-01-08 05:23:43 +0900328void MessageLoop::Run() {
329 AutoRunState save_state(this);
330 RunHandler();
331}
darin@google.com0795f572008-08-30 09:22:48 +0900332
erg@google.com67a25432011-01-08 05:23:43 +0900333void MessageLoop::RunAllPending() {
334 AutoRunState save_state(this);
335 state_->quit_received = true; // Means run until we would otherwise block.
336 RunHandler();
337}
darin@google.com0795f572008-08-30 09:22:48 +0900338
erg@google.com67a25432011-01-08 05:23:43 +0900339void MessageLoop::Quit() {
340 DCHECK_EQ(this, current());
341 if (state_) {
342 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900343 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900344 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900345 }
erg@google.com67a25432011-01-08 05:23:43 +0900346}
darin@google.com0795f572008-08-30 09:22:48 +0900347
erg@google.com67a25432011-01-08 05:23:43 +0900348void MessageLoop::QuitNow() {
349 DCHECK_EQ(this, current());
350 if (state_) {
351 pump_->Quit();
352 } else {
353 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900354 }
initial.commit3f4a7322008-07-27 06:49:38 +0900355}
356
357void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900358 if (nestable_tasks_allowed_ != allowed) {
359 nestable_tasks_allowed_ = allowed;
360 if (!nestable_tasks_allowed_)
361 return;
362 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900363 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900364 }
initial.commit3f4a7322008-07-27 06:49:38 +0900365}
366
367bool MessageLoop::NestableTasksAllowed() const {
368 return nestable_tasks_allowed_;
369}
370
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900371bool MessageLoop::IsNested() {
372 return state_->run_depth > 1;
373}
374
erg@google.com67a25432011-01-08 05:23:43 +0900375void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
376 DCHECK_EQ(this, current());
377 task_observers_.AddObserver(task_observer);
378}
379
380void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
381 DCHECK_EQ(this, current());
382 task_observers_.RemoveObserver(task_observer);
383}
384
willchan@chromium.org3a397672011-01-26 09:53:48 +0900385void MessageLoop::AssertIdle() const {
386 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
387 base::AutoLock lock(incoming_queue_lock_);
388 DCHECK(incoming_queue_.empty());
389}
390
initial.commit3f4a7322008-07-27 06:49:38 +0900391//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900392
erg@google.com67a25432011-01-08 05:23:43 +0900393// Runs the loop in two different SEH modes:
394// enable_SEH_restoration_ = false : any unhandled exception goes to the last
395// one that calls SetUnhandledExceptionFilter().
396// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
397// that was existed before the loop was run.
398void MessageLoop::RunHandler() {
399#if defined(OS_WIN)
400 if (exception_restoration_) {
401 RunInternalInSEHFrame();
402 return;
403 }
404#endif
405
406 RunInternal();
407}
408
409#if defined(OS_WIN)
410__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
411 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
412 __try {
413 RunInternal();
414 } __except(SEHFilter(current_filter)) {
415 }
416 return;
417}
418#endif
419
420void MessageLoop::RunInternal() {
421 DCHECK_EQ(this, current());
422
423 StartHistogrammer();
424
425#if !defined(OS_MACOSX)
426 if (state_->dispatcher && type() == TYPE_UI) {
427 static_cast<base::MessagePumpForUI*>(pump_.get())->
428 RunWithDispatcher(this, state_->dispatcher);
429 return;
430 }
431#endif
432
433 pump_->Run(this);
434}
435
436bool MessageLoop::ProcessNextDelayedNonNestableTask() {
437 if (state_->run_depth != 1)
438 return false;
439
440 if (deferred_non_nestable_work_queue_.empty())
441 return false;
442
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900443 PendingTask pending_task = deferred_non_nestable_work_queue_.front();
erg@google.com67a25432011-01-08 05:23:43 +0900444 deferred_non_nestable_work_queue_.pop();
445
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900446 RunTask(pending_task);
erg@google.com67a25432011-01-08 05:23:43 +0900447 return true;
448}
449
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900450void MessageLoop::RunTask(const PendingTask& pending_task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900451 DCHECK(nestable_tasks_allowed_);
452 // Execute the task and assume the worst: It is probably not reentrant.
453 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900454
455 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900456 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900457 WillProcessTask(pending_task.time_posted));
458 pending_task.task.Run();
459 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
460 DidProcessTask(pending_task.time_posted));
461
462#if defined(TRACK_ALL_TASK_OBJECTS)
463 if (tracked_objects::ThreadData::IsActive() && pending_task.post_births) {
464 tracked_objects::ThreadData::current()->TallyADeath(
465 *pending_task.post_births,
466 TimeTicks::Now() - pending_task.time_posted);
467 }
468#endif // defined(TRACK_ALL_TASK_OBJECTS)
darin@google.combe165ae2008-09-07 17:08:29 +0900469
470 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900471}
472
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900473bool MessageLoop::DeferOrRunPendingTask(
474 const PendingTask& pending_task) {
darin@google.combe165ae2008-09-07 17:08:29 +0900475 if (pending_task.nestable || state_->run_depth == 1) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900476 RunTask(pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900477 // Show that we ran a task (Note: a new one might arrive as a
478 // consequence!).
479 return true;
480 }
481
482 // We couldn't run the task now because we're in a nested message loop
483 // and the task isn't nestable.
484 deferred_non_nestable_work_queue_.push(pending_task);
485 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900486}
487
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900488void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
489 // Move to the delayed work queue. Initialize the sequence number
490 // before inserting into the delayed_work_queue_. The sequence number
491 // is used to faciliate FIFO sorting when two tasks have the same
492 // delayed_run_time value.
493 PendingTask new_pending_task(pending_task);
494 new_pending_task.sequence_num = next_sequence_num_++;
495 delayed_work_queue_.push(new_pending_task);
496}
497
initial.commit3f4a7322008-07-27 06:49:38 +0900498void MessageLoop::ReloadWorkQueue() {
499 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900500 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
501 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900502 // queues get large.
503 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900504 return; // Wait till we *really* need to lock and load.
505
506 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900507 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900508 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900509 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900510 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900511 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900512 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900513 }
514}
515
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900516bool MessageLoop::DeletePendingTasks() {
517 bool did_work = !work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900518 // TODO(darin): Delete all tasks once it is safe to do so.
519 // Until it is totally safe, just do it when running Purify or
520 // Valgrind.
521 //
522 // See http://crbug.com/61131
523 //
524#if defined(PURIFY) || defined(USE_HEAPCHECKER)
525 should_leak_tasks_ = false;
526#else
527 if (RunningOnValgrind())
528 should_leak_tasks_ = false;
529#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900530 while (!work_queue_.empty()) {
531 PendingTask pending_task = work_queue_.front();
532 work_queue_.pop();
533 if (!pending_task.delayed_run_time.is_null()) {
534 // We want to delete delayed tasks in the same order in which they would
535 // normally be deleted in case of any funny dependencies between delayed
536 // tasks.
537 AddToDelayedWorkQueue(pending_task);
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900538 }
initial.commit3f4a7322008-07-27 06:49:38 +0900539 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900540 did_work |= !deferred_non_nestable_work_queue_.empty();
541 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900542 deferred_non_nestable_work_queue_.pop();
initial.commit3f4a7322008-07-27 06:49:38 +0900543 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900544 did_work |= !delayed_work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900545
546 // Historically, we always delete the task regardless of valgrind status. It's
547 // not completely clear why we want to leak them in the loops above. This
548 // code is replicating legacy behavior, and should not be considered
549 // absolutely "correct" behavior. See TODO above about deleting all tasks
550 // when it's safe.
551 should_leak_tasks_ = false;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900552 while (!delayed_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900553 delayed_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900554 }
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900555 should_leak_tasks_ = true;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900556 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900557}
558
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900559TimeTicks MessageLoop::CalculateDelayedRuntime(int64 delay_ms) {
560 TimeTicks delayed_run_time;
erg@google.com67a25432011-01-08 05:23:43 +0900561 if (delay_ms > 0) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900562 delayed_run_time =
erg@google.com67a25432011-01-08 05:23:43 +0900563 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
564
565#if defined(OS_WIN)
566 if (high_resolution_timer_expiration_.is_null()) {
567 // Windows timers are granular to 15.6ms. If we only set high-res
568 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
569 // which as a percentage is pretty inaccurate. So enable high
570 // res timers for any timer which is within 2x of the granularity.
571 // This is a tradeoff between accuracy and power management.
572 bool needs_high_res_timers =
573 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
574 if (needs_high_res_timers) {
575 base::Time::ActivateHighResolutionTimer(true);
576 high_resolution_timer_expiration_ = TimeTicks::Now() +
577 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
578 }
579 }
580#endif
581 } else {
582 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
583 }
584
585#if defined(OS_WIN)
586 if (!high_resolution_timer_expiration_.is_null()) {
587 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
588 base::Time::ActivateHighResolutionTimer(false);
589 high_resolution_timer_expiration_ = TimeTicks();
590 }
591 }
592#endif
593
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900594 return delayed_run_time;
595}
596
597// Possibly called on a background thread!
598void MessageLoop::AddToIncomingQueue(PendingTask* pending_task) {
erg@google.com67a25432011-01-08 05:23:43 +0900599 // Warning: Don't try to short-circuit, and handle this thread's tasks more
600 // directly, as it could starve handling of foreign threads. Put every task
601 // into this queue.
602
603 scoped_refptr<base::MessagePump> pump;
604 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900605 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900606
607 bool was_empty = incoming_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900608 incoming_queue_.push(*pending_task);
609 pending_task->task.Reset();
erg@google.com67a25432011-01-08 05:23:43 +0900610 if (!was_empty)
611 return; // Someone else should have started the sub-pump.
612
613 pump = pump_;
614 }
615 // Since the incoming_queue_ may contain a task that destroys this message
616 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
617 // We use a stack-based reference to the message pump so that we can call
618 // ScheduleWork outside of incoming_queue_lock_.
619
620 pump->ScheduleWork();
621}
622
623//------------------------------------------------------------------------------
624// Method and data for histogramming events and actions taken by each instance
625// on each thread.
626
627void MessageLoop::StartHistogrammer() {
jar@chromium.org34571142011-04-05 13:48:53 +0900628 if (enable_histogrammer_ && !message_histogram_
erg@google.com67a25432011-01-08 05:23:43 +0900629 && base::StatisticsRecorder::IsActive()) {
630 DCHECK(!thread_name_.empty());
631 message_histogram_ = base::LinearHistogram::FactoryGet(
632 "MsgLoop:" + thread_name_,
633 kLeastNonZeroMessageId, kMaxMessageId,
634 kNumberOfDistinctMessagesDisplayed,
635 message_histogram_->kHexRangePrintingFlag);
636 message_histogram_->SetRangeDescriptions(event_descriptions_);
637 }
638}
639
640void MessageLoop::HistogramEvent(int event) {
jar@chromium.org34571142011-04-05 13:48:53 +0900641 if (message_histogram_)
erg@google.com67a25432011-01-08 05:23:43 +0900642 message_histogram_->Add(event);
643}
644
darin@google.com981f3552008-08-16 12:09:05 +0900645bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900646 if (!nestable_tasks_allowed_) {
647 // Task can't be executed right now.
648 return false;
649 }
650
651 for (;;) {
652 ReloadWorkQueue();
653 if (work_queue_.empty())
654 break;
655
656 // Execute oldest task.
657 do {
658 PendingTask pending_task = work_queue_.front();
659 work_queue_.pop();
660 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900661 AddToDelayedWorkQueue(pending_task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900662 // If we changed the topmost task, then it is time to reschedule.
663 if (delayed_work_queue_.top().task.Equals(pending_task.task))
darin@google.combe165ae2008-09-07 17:08:29 +0900664 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
665 } else {
666 if (DeferOrRunPendingTask(pending_task))
667 return true;
668 }
669 } while (!work_queue_.empty());
670 }
671
672 // Nothing happened.
673 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900674}
675
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900676bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900677 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900678 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900679 return false;
680 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900681
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900682 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900683 // queue that are ready to run. To increase efficiency when we fall behind,
684 // we will only call Time::Now() intermittently, and then process all tasks
685 // that are ready to run before calling it again. As a result, the more we
686 // fall behind (and have a lot of ready-to-run delayed tasks), the more
687 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900688
689 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900690 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900691 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900692 if (next_run_time > recent_time_) {
693 *next_delayed_work_time = next_run_time;
694 return false;
695 }
darin@google.combe165ae2008-09-07 17:08:29 +0900696 }
darin@google.com981f3552008-08-16 12:09:05 +0900697
jar@chromium.org40355072010-10-21 15:32:33 +0900698 PendingTask pending_task = delayed_work_queue_.top();
699 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900700
jar@chromium.org40355072010-10-21 15:32:33 +0900701 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900702 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900703
darin@google.combe165ae2008-09-07 17:08:29 +0900704 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900705}
706
707bool MessageLoop::DoIdleWork() {
708 if (ProcessNextDelayedNonNestableTask())
709 return true;
710
711 if (state_->quit_received)
712 pump_->Quit();
713
714 return false;
715}
716
717//------------------------------------------------------------------------------
718// MessageLoop::AutoRunState
719
720MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
721 // Make the loop reference us.
722 previous_state_ = loop_->state_;
723 if (previous_state_) {
724 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900725 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900726 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900727 }
darin@google.com981f3552008-08-16 12:09:05 +0900728 loop_->state_ = this;
729
730 // Initialize the other fields:
731 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900732#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900733 dispatcher = NULL;
734#endif
735}
736
737MessageLoop::AutoRunState::~AutoRunState() {
738 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900739}
740
initial.commit3f4a7322008-07-27 06:49:38 +0900741//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900742// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900743
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900744MessageLoop::PendingTask::PendingTask(
745 const base::Closure& task,
746 const tracked_objects::Location& posted_from,
747 TimeTicks delayed_run_time,
748 bool nestable)
749 : task(task),
750 time_posted(TimeTicks::Now()),
751 delayed_run_time(delayed_run_time),
752 sequence_num(0),
753 nestable(nestable) {
754#if defined(TRACK_ALL_TASK_OBJECTS)
755 if (tracked_objects::ThreadData::IsActive()) {
756 tracked_objects::ThreadData* current_thread_data =
757 tracked_objects::ThreadData::current();
758 if (current_thread_data) {
759 post_births = current_thread_data->TallyABirth(posted_from);
760 } else {
761 // Shutdown started, and this thread wasn't registered.
762 post_births = NULL;
763 }
764 }
765#endif // defined(TRACK_ALL_TASK_OBJECTS)
766}
767
768MessageLoop::PendingTask::~PendingTask() {
769}
770
darin@google.combe165ae2008-09-07 17:08:29 +0900771bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
772 // Since the top of a priority queue is defined as the "greatest" element, we
773 // need to invert the comparison here. We want the smaller time to be at the
774 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900775
darin@google.combe165ae2008-09-07 17:08:29 +0900776 if (delayed_run_time < other.delayed_run_time)
777 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900778
darin@google.combe165ae2008-09-07 17:08:29 +0900779 if (delayed_run_time > other.delayed_run_time)
780 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900781
darin@google.combe165ae2008-09-07 17:08:29 +0900782 // If the times happen to match, then we use the sequence number to decide.
783 // Compare the difference to support integer roll-over.
784 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900785}
786
787//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900788// MessageLoopForUI
789
790#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900791void MessageLoopForUI::DidProcessMessage(const MSG& message) {
792 pump_win()->DidProcessMessage(message);
793}
darin@google.comd936b5b2008-08-26 14:53:57 +0900794#endif // defined(OS_WIN)
795
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900796#if defined(USE_X11)
797Display* MessageLoopForUI::GetDisplay() {
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900798 return gdk_x11_get_default_xdisplay();
799}
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900800#endif // defined(USE_X11)
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900801
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900802#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900803void MessageLoopForUI::AddObserver(Observer* observer) {
804 pump_ui()->AddObserver(observer);
805}
806
807void MessageLoopForUI::RemoveObserver(Observer* observer) {
808 pump_ui()->RemoveObserver(observer);
809}
810
811void MessageLoopForUI::Run(Dispatcher* dispatcher) {
812 AutoRunState save_state(this);
813 state_->dispatcher = dispatcher;
814 RunHandler();
815}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900816#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900817
darin@google.comd936b5b2008-08-26 14:53:57 +0900818//------------------------------------------------------------------------------
819// MessageLoopForIO
820
821#if defined(OS_WIN)
822
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900823void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
824 pump_io()->RegisterIOHandler(file, handler);
825}
826
rvargas@google.com73887542008-11-08 06:52:15 +0900827bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
828 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900829}
830
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900831#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900832
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900833bool MessageLoopForIO::WatchFileDescriptor(int fd,
834 bool persistent,
835 Mode mode,
836 FileDescriptorWatcher *controller,
837 Watcher *delegate) {
838 return pump_libevent()->WatchFileDescriptor(
839 fd,
840 persistent,
841 static_cast<base::MessagePumpLibevent::Mode>(mode),
842 controller,
843 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900844}
845
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900846#endif