blob: a3520a6a189bdfdcf4614f9fd358f3c37f39dec7 [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) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900258 CHECK(task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900259 PendingTask pending_task(
260 base::Bind(&TaskClosureAdapter::Run,
261 new TaskClosureAdapter(task, &should_leak_tasks_)),
262 from_here,
263 CalculateDelayedRuntime(0), true);
264 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900265}
266
267void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900268 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900269 CHECK(task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900270 PendingTask pending_task(
271 base::Bind(&TaskClosureAdapter::Run,
272 new TaskClosureAdapter(task, &should_leak_tasks_)),
273 from_here,
274 CalculateDelayedRuntime(delay_ms), true);
275 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900276}
277
278void MessageLoop::PostNonNestableTask(
279 const tracked_objects::Location& from_here, Task* task) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900280 CHECK(task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900281 PendingTask pending_task(
282 base::Bind(&TaskClosureAdapter::Run,
283 new TaskClosureAdapter(task, &should_leak_tasks_)),
284 from_here,
285 CalculateDelayedRuntime(0), false);
286 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900287}
288
289void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900290 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900291 CHECK(task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900292 PendingTask pending_task(
293 base::Bind(&TaskClosureAdapter::Run,
294 new TaskClosureAdapter(task, &should_leak_tasks_)),
295 from_here,
296 CalculateDelayedRuntime(delay_ms), false);
297 AddToIncomingQueue(&pending_task);
298}
299
300void MessageLoop::PostTask(
301 const tracked_objects::Location& from_here, const base::Closure& task) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900302 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900303 PendingTask pending_task(task, from_here, CalculateDelayedRuntime(0), true);
304 AddToIncomingQueue(&pending_task);
305}
306
307void MessageLoop::PostDelayedTask(
308 const tracked_objects::Location& from_here, const base::Closure& task,
309 int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900310 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900311 PendingTask pending_task(task, from_here,
312 CalculateDelayedRuntime(delay_ms), true);
313 AddToIncomingQueue(&pending_task);
314}
315
316void MessageLoop::PostNonNestableTask(
317 const tracked_objects::Location& from_here, const base::Closure& task) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900318 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900319 PendingTask pending_task(task, from_here, CalculateDelayedRuntime(0), false);
320 AddToIncomingQueue(&pending_task);
321}
322
323void MessageLoop::PostNonNestableDelayedTask(
324 const tracked_objects::Location& from_here, const base::Closure& task,
325 int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900326 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900327 PendingTask pending_task(task, from_here,
328 CalculateDelayedRuntime(delay_ms), false);
329 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900330}
331
erg@google.com67a25432011-01-08 05:23:43 +0900332void MessageLoop::Run() {
333 AutoRunState save_state(this);
334 RunHandler();
335}
darin@google.com0795f572008-08-30 09:22:48 +0900336
erg@google.com67a25432011-01-08 05:23:43 +0900337void MessageLoop::RunAllPending() {
338 AutoRunState save_state(this);
339 state_->quit_received = true; // Means run until we would otherwise block.
340 RunHandler();
341}
darin@google.com0795f572008-08-30 09:22:48 +0900342
erg@google.com67a25432011-01-08 05:23:43 +0900343void MessageLoop::Quit() {
344 DCHECK_EQ(this, current());
345 if (state_) {
346 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900347 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900348 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900349 }
erg@google.com67a25432011-01-08 05:23:43 +0900350}
darin@google.com0795f572008-08-30 09:22:48 +0900351
erg@google.com67a25432011-01-08 05:23:43 +0900352void MessageLoop::QuitNow() {
353 DCHECK_EQ(this, current());
354 if (state_) {
355 pump_->Quit();
356 } else {
357 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900358 }
initial.commit3f4a7322008-07-27 06:49:38 +0900359}
360
361void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900362 if (nestable_tasks_allowed_ != allowed) {
363 nestable_tasks_allowed_ = allowed;
364 if (!nestable_tasks_allowed_)
365 return;
366 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900367 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900368 }
initial.commit3f4a7322008-07-27 06:49:38 +0900369}
370
371bool MessageLoop::NestableTasksAllowed() const {
372 return nestable_tasks_allowed_;
373}
374
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900375bool MessageLoop::IsNested() {
376 return state_->run_depth > 1;
377}
378
erg@google.com67a25432011-01-08 05:23:43 +0900379void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
380 DCHECK_EQ(this, current());
381 task_observers_.AddObserver(task_observer);
382}
383
384void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
385 DCHECK_EQ(this, current());
386 task_observers_.RemoveObserver(task_observer);
387}
388
willchan@chromium.org3a397672011-01-26 09:53:48 +0900389void MessageLoop::AssertIdle() const {
390 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
391 base::AutoLock lock(incoming_queue_lock_);
392 DCHECK(incoming_queue_.empty());
393}
394
initial.commit3f4a7322008-07-27 06:49:38 +0900395//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900396
erg@google.com67a25432011-01-08 05:23:43 +0900397// Runs the loop in two different SEH modes:
398// enable_SEH_restoration_ = false : any unhandled exception goes to the last
399// one that calls SetUnhandledExceptionFilter().
400// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
401// that was existed before the loop was run.
402void MessageLoop::RunHandler() {
403#if defined(OS_WIN)
404 if (exception_restoration_) {
405 RunInternalInSEHFrame();
406 return;
407 }
408#endif
409
410 RunInternal();
411}
412
413#if defined(OS_WIN)
414__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
415 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
416 __try {
417 RunInternal();
418 } __except(SEHFilter(current_filter)) {
419 }
420 return;
421}
422#endif
423
424void MessageLoop::RunInternal() {
425 DCHECK_EQ(this, current());
426
427 StartHistogrammer();
428
429#if !defined(OS_MACOSX)
430 if (state_->dispatcher && type() == TYPE_UI) {
431 static_cast<base::MessagePumpForUI*>(pump_.get())->
432 RunWithDispatcher(this, state_->dispatcher);
433 return;
434 }
435#endif
436
437 pump_->Run(this);
438}
439
440bool MessageLoop::ProcessNextDelayedNonNestableTask() {
441 if (state_->run_depth != 1)
442 return false;
443
444 if (deferred_non_nestable_work_queue_.empty())
445 return false;
446
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900447 PendingTask pending_task = deferred_non_nestable_work_queue_.front();
erg@google.com67a25432011-01-08 05:23:43 +0900448 deferred_non_nestable_work_queue_.pop();
449
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900450 RunTask(pending_task);
erg@google.com67a25432011-01-08 05:23:43 +0900451 return true;
452}
453
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900454void MessageLoop::RunTask(const PendingTask& pending_task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900455 DCHECK(nestable_tasks_allowed_);
456 // Execute the task and assume the worst: It is probably not reentrant.
457 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900458
459 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900460 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900461 WillProcessTask(pending_task.time_posted));
462 pending_task.task.Run();
463 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
464 DidProcessTask(pending_task.time_posted));
465
466#if defined(TRACK_ALL_TASK_OBJECTS)
467 if (tracked_objects::ThreadData::IsActive() && pending_task.post_births) {
468 tracked_objects::ThreadData::current()->TallyADeath(
469 *pending_task.post_births,
470 TimeTicks::Now() - pending_task.time_posted);
471 }
472#endif // defined(TRACK_ALL_TASK_OBJECTS)
darin@google.combe165ae2008-09-07 17:08:29 +0900473
474 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900475}
476
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900477bool MessageLoop::DeferOrRunPendingTask(
478 const PendingTask& pending_task) {
darin@google.combe165ae2008-09-07 17:08:29 +0900479 if (pending_task.nestable || state_->run_depth == 1) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900480 RunTask(pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900481 // Show that we ran a task (Note: a new one might arrive as a
482 // consequence!).
483 return true;
484 }
485
486 // We couldn't run the task now because we're in a nested message loop
487 // and the task isn't nestable.
488 deferred_non_nestable_work_queue_.push(pending_task);
489 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900490}
491
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900492void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
493 // Move to the delayed work queue. Initialize the sequence number
494 // before inserting into the delayed_work_queue_. The sequence number
495 // is used to faciliate FIFO sorting when two tasks have the same
496 // delayed_run_time value.
497 PendingTask new_pending_task(pending_task);
498 new_pending_task.sequence_num = next_sequence_num_++;
499 delayed_work_queue_.push(new_pending_task);
500}
501
initial.commit3f4a7322008-07-27 06:49:38 +0900502void MessageLoop::ReloadWorkQueue() {
503 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900504 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
505 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900506 // queues get large.
507 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900508 return; // Wait till we *really* need to lock and load.
509
510 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900511 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900512 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900513 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900514 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900515 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900516 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900517 }
518}
519
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900520bool MessageLoop::DeletePendingTasks() {
521 bool did_work = !work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900522 // TODO(darin): Delete all tasks once it is safe to do so.
523 // Until it is totally safe, just do it when running Purify or
524 // Valgrind.
525 //
526 // See http://crbug.com/61131
527 //
528#if defined(PURIFY) || defined(USE_HEAPCHECKER)
529 should_leak_tasks_ = false;
530#else
531 if (RunningOnValgrind())
532 should_leak_tasks_ = false;
533#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900534 while (!work_queue_.empty()) {
535 PendingTask pending_task = work_queue_.front();
536 work_queue_.pop();
537 if (!pending_task.delayed_run_time.is_null()) {
538 // We want to delete delayed tasks in the same order in which they would
539 // normally be deleted in case of any funny dependencies between delayed
540 // tasks.
541 AddToDelayedWorkQueue(pending_task);
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900542 }
initial.commit3f4a7322008-07-27 06:49:38 +0900543 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900544 did_work |= !deferred_non_nestable_work_queue_.empty();
545 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900546 deferred_non_nestable_work_queue_.pop();
initial.commit3f4a7322008-07-27 06:49:38 +0900547 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900548 did_work |= !delayed_work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900549
550 // Historically, we always delete the task regardless of valgrind status. It's
551 // not completely clear why we want to leak them in the loops above. This
552 // code is replicating legacy behavior, and should not be considered
553 // absolutely "correct" behavior. See TODO above about deleting all tasks
554 // when it's safe.
555 should_leak_tasks_ = false;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900556 while (!delayed_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900557 delayed_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900558 }
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900559 should_leak_tasks_ = true;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900560 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900561}
562
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900563TimeTicks MessageLoop::CalculateDelayedRuntime(int64 delay_ms) {
564 TimeTicks delayed_run_time;
erg@google.com67a25432011-01-08 05:23:43 +0900565 if (delay_ms > 0) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900566 delayed_run_time =
erg@google.com67a25432011-01-08 05:23:43 +0900567 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
568
569#if defined(OS_WIN)
570 if (high_resolution_timer_expiration_.is_null()) {
571 // Windows timers are granular to 15.6ms. If we only set high-res
572 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
573 // which as a percentage is pretty inaccurate. So enable high
574 // res timers for any timer which is within 2x of the granularity.
575 // This is a tradeoff between accuracy and power management.
576 bool needs_high_res_timers =
577 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
578 if (needs_high_res_timers) {
579 base::Time::ActivateHighResolutionTimer(true);
580 high_resolution_timer_expiration_ = TimeTicks::Now() +
581 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
582 }
583 }
584#endif
585 } else {
586 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
587 }
588
589#if defined(OS_WIN)
590 if (!high_resolution_timer_expiration_.is_null()) {
591 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
592 base::Time::ActivateHighResolutionTimer(false);
593 high_resolution_timer_expiration_ = TimeTicks();
594 }
595 }
596#endif
597
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900598 return delayed_run_time;
599}
600
601// Possibly called on a background thread!
602void MessageLoop::AddToIncomingQueue(PendingTask* pending_task) {
erg@google.com67a25432011-01-08 05:23:43 +0900603 // Warning: Don't try to short-circuit, and handle this thread's tasks more
604 // directly, as it could starve handling of foreign threads. Put every task
605 // into this queue.
606
607 scoped_refptr<base::MessagePump> pump;
608 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900609 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900610
611 bool was_empty = incoming_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900612 incoming_queue_.push(*pending_task);
613 pending_task->task.Reset();
erg@google.com67a25432011-01-08 05:23:43 +0900614 if (!was_empty)
615 return; // Someone else should have started the sub-pump.
616
617 pump = pump_;
618 }
619 // Since the incoming_queue_ may contain a task that destroys this message
620 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
621 // We use a stack-based reference to the message pump so that we can call
622 // ScheduleWork outside of incoming_queue_lock_.
623
624 pump->ScheduleWork();
625}
626
627//------------------------------------------------------------------------------
628// Method and data for histogramming events and actions taken by each instance
629// on each thread.
630
631void MessageLoop::StartHistogrammer() {
jar@chromium.org34571142011-04-05 13:48:53 +0900632 if (enable_histogrammer_ && !message_histogram_
erg@google.com67a25432011-01-08 05:23:43 +0900633 && base::StatisticsRecorder::IsActive()) {
634 DCHECK(!thread_name_.empty());
635 message_histogram_ = base::LinearHistogram::FactoryGet(
636 "MsgLoop:" + thread_name_,
637 kLeastNonZeroMessageId, kMaxMessageId,
638 kNumberOfDistinctMessagesDisplayed,
639 message_histogram_->kHexRangePrintingFlag);
640 message_histogram_->SetRangeDescriptions(event_descriptions_);
641 }
642}
643
644void MessageLoop::HistogramEvent(int event) {
jar@chromium.org34571142011-04-05 13:48:53 +0900645 if (message_histogram_)
erg@google.com67a25432011-01-08 05:23:43 +0900646 message_histogram_->Add(event);
647}
648
darin@google.com981f3552008-08-16 12:09:05 +0900649bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900650 if (!nestable_tasks_allowed_) {
651 // Task can't be executed right now.
652 return false;
653 }
654
655 for (;;) {
656 ReloadWorkQueue();
657 if (work_queue_.empty())
658 break;
659
660 // Execute oldest task.
661 do {
662 PendingTask pending_task = work_queue_.front();
663 work_queue_.pop();
664 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900665 AddToDelayedWorkQueue(pending_task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900666 // If we changed the topmost task, then it is time to reschedule.
667 if (delayed_work_queue_.top().task.Equals(pending_task.task))
darin@google.combe165ae2008-09-07 17:08:29 +0900668 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
669 } else {
670 if (DeferOrRunPendingTask(pending_task))
671 return true;
672 }
673 } while (!work_queue_.empty());
674 }
675
676 // Nothing happened.
677 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900678}
679
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900680bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900681 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900682 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900683 return false;
684 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900685
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900686 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900687 // queue that are ready to run. To increase efficiency when we fall behind,
688 // we will only call Time::Now() intermittently, and then process all tasks
689 // that are ready to run before calling it again. As a result, the more we
690 // fall behind (and have a lot of ready-to-run delayed tasks), the more
691 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900692
693 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900694 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900695 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900696 if (next_run_time > recent_time_) {
697 *next_delayed_work_time = next_run_time;
698 return false;
699 }
darin@google.combe165ae2008-09-07 17:08:29 +0900700 }
darin@google.com981f3552008-08-16 12:09:05 +0900701
jar@chromium.org40355072010-10-21 15:32:33 +0900702 PendingTask pending_task = delayed_work_queue_.top();
703 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900704
jar@chromium.org40355072010-10-21 15:32:33 +0900705 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900706 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900707
darin@google.combe165ae2008-09-07 17:08:29 +0900708 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900709}
710
711bool MessageLoop::DoIdleWork() {
712 if (ProcessNextDelayedNonNestableTask())
713 return true;
714
715 if (state_->quit_received)
716 pump_->Quit();
717
718 return false;
719}
720
721//------------------------------------------------------------------------------
722// MessageLoop::AutoRunState
723
724MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
725 // Make the loop reference us.
726 previous_state_ = loop_->state_;
727 if (previous_state_) {
728 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900729 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900730 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900731 }
darin@google.com981f3552008-08-16 12:09:05 +0900732 loop_->state_ = this;
733
734 // Initialize the other fields:
735 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900736#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900737 dispatcher = NULL;
738#endif
739}
740
741MessageLoop::AutoRunState::~AutoRunState() {
742 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900743}
744
initial.commit3f4a7322008-07-27 06:49:38 +0900745//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900746// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900747
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900748MessageLoop::PendingTask::PendingTask(
749 const base::Closure& task,
750 const tracked_objects::Location& posted_from,
751 TimeTicks delayed_run_time,
752 bool nestable)
753 : task(task),
754 time_posted(TimeTicks::Now()),
755 delayed_run_time(delayed_run_time),
756 sequence_num(0),
757 nestable(nestable) {
758#if defined(TRACK_ALL_TASK_OBJECTS)
759 if (tracked_objects::ThreadData::IsActive()) {
760 tracked_objects::ThreadData* current_thread_data =
761 tracked_objects::ThreadData::current();
762 if (current_thread_data) {
763 post_births = current_thread_data->TallyABirth(posted_from);
764 } else {
765 // Shutdown started, and this thread wasn't registered.
766 post_births = NULL;
767 }
768 }
769#endif // defined(TRACK_ALL_TASK_OBJECTS)
770}
771
772MessageLoop::PendingTask::~PendingTask() {
773}
774
darin@google.combe165ae2008-09-07 17:08:29 +0900775bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
776 // Since the top of a priority queue is defined as the "greatest" element, we
777 // need to invert the comparison here. We want the smaller time to be at the
778 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900779
darin@google.combe165ae2008-09-07 17:08:29 +0900780 if (delayed_run_time < other.delayed_run_time)
781 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900782
darin@google.combe165ae2008-09-07 17:08:29 +0900783 if (delayed_run_time > other.delayed_run_time)
784 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900785
darin@google.combe165ae2008-09-07 17:08:29 +0900786 // If the times happen to match, then we use the sequence number to decide.
787 // Compare the difference to support integer roll-over.
788 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900789}
790
791//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900792// MessageLoopForUI
793
794#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900795void MessageLoopForUI::DidProcessMessage(const MSG& message) {
796 pump_win()->DidProcessMessage(message);
797}
darin@google.comd936b5b2008-08-26 14:53:57 +0900798#endif // defined(OS_WIN)
799
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900800#if defined(USE_X11)
801Display* MessageLoopForUI::GetDisplay() {
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900802 return gdk_x11_get_default_xdisplay();
803}
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900804#endif // defined(USE_X11)
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900805
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900806#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900807void MessageLoopForUI::AddObserver(Observer* observer) {
808 pump_ui()->AddObserver(observer);
809}
810
811void MessageLoopForUI::RemoveObserver(Observer* observer) {
812 pump_ui()->RemoveObserver(observer);
813}
814
815void MessageLoopForUI::Run(Dispatcher* dispatcher) {
816 AutoRunState save_state(this);
817 state_->dispatcher = dispatcher;
818 RunHandler();
819}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900820#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900821
darin@google.comd936b5b2008-08-26 14:53:57 +0900822//------------------------------------------------------------------------------
823// MessageLoopForIO
824
825#if defined(OS_WIN)
826
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900827void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
828 pump_io()->RegisterIOHandler(file, handler);
829}
830
rvargas@google.com73887542008-11-08 06:52:15 +0900831bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
832 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900833}
834
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900835#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900836
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900837bool MessageLoopForIO::WatchFileDescriptor(int fd,
838 bool persistent,
839 Mode mode,
840 FileDescriptorWatcher *controller,
841 Watcher *delegate) {
842 return pump_libevent()->WatchFileDescriptor(
843 fd,
844 persistent,
845 static_cast<base::MessagePumpLibevent::Mode>(mode),
846 controller,
847 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900848}
849
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900850#endif