blob: 059cdc253135737e2cba33ff779489eb80647626 [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"
mbelshe@chromium.orgbee85b32011-05-16 04:20:49 +090018#include "base/time.h"
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090019#include "base/tracked_objects.h"
initial.commit3f4a7322008-07-27 06:49:38 +090020
mark@chromium.org059d0492008-09-24 06:08:28 +090021#if defined(OS_MACOSX)
22#include "base/message_pump_mac.h"
23#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090024#if defined(OS_POSIX)
25#include "base/message_pump_libevent.h"
26#endif
evan@chromium.org875bb6e2009-12-29 09:32:52 +090027#if defined(OS_POSIX) && !defined(OS_MACOSX)
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090028#include <gdk/gdk.h>
29#include <gdk/gdkx.h>
dsh@google.com119a2522008-10-04 01:52:59 +090030#include "base/message_pump_glib.h"
31#endif
rjkroege@google.com3080f442010-10-23 01:17:47 +090032#if defined(TOUCH_UI)
33#include "base/message_pump_glib_x.h"
34#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090035
dsh@google.com0f8dd262008-10-28 05:43:33 +090036using base::TimeDelta;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090037using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090038
erg@chromium.orga7528522010-07-16 02:23:23 +090039namespace {
40
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090041// A lazily created thread local storage for quick access to a thread's message
42// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090043base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090044 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090045
initial.commit3f4a7322008-07-27 06:49:38 +090046// Logical events for Histogram profiling. Run with -message-loop-histogrammer
47// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090048const int kTaskRunEvent = 0x1;
49const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090050
51// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090052const int kLeastNonZeroMessageId = 1;
53const int kMaxMessageId = 1099;
54const int kNumberOfDistinctMessagesDisplayed = 1100;
55
56// Provide a macro that takes an expression (such as a constant, or macro
57// constant) and creates a pair to initalize an array of pairs. In this case,
58// our pair consists of the expressions value, and the "stringized" version
59// of the expression (i.e., the exrpression put in quotes). For example, if
60// we have:
61// #define FOO 2
62// #define BAR 5
63// then the following:
64// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
65// will expand to:
66// {7, "FOO + BAR"}
67// We use the resulting array as an argument to our histogram, which reads the
68// number as a bucket identifier, and proceeds to use the corresponding name
69// in the pair (i.e., the quoted string) when printing out a histogram.
70#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
71
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090072const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090073 // Provide some pretty print capability in our histogram for our internal
74 // messages.
75
76 // A few events we handle (kindred to messages), and used to profile actions.
77 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
78 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
79
80 {-1, NULL} // The list must be null terminated, per API to histogram.
81};
82
83bool enable_histogrammer_ = false;
84
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090085// TODO(ajwong): This is one use case for having a Owned() tag that behaves
86// like a "Unique" pointer. If we had that, and Tasks were always safe to
87// delete on MessageLoop shutdown, this class could just be a function.
88class TaskClosureAdapter : public base::RefCounted<TaskClosureAdapter> {
89 public:
90 // |should_leak_task| points to a flag variable that can be used to determine
91 // if this class should leak the Task on destruction. This is important
92 // at MessageLoop shutdown since not all tasks can be safely deleted without
93 // running. See MessageLoop::DeletePendingTasks() for the exact behavior
94 // of when a Task should be deleted. It is subtle.
95 TaskClosureAdapter(Task* task, bool* should_leak_task)
96 : task_(task),
97 should_leak_task_(should_leak_task) {
98 }
99
100 void Run() {
101 task_->Run();
102 delete task_;
103 task_ = NULL;
104 }
105
106 private:
107 friend class base::RefCounted<TaskClosureAdapter>;
108
109 ~TaskClosureAdapter() {
110 if (!*should_leak_task_) {
111 delete task_;
112 }
113 }
114
115 Task* task_;
116 bool* should_leak_task_;
117};
118
erg@chromium.orga7528522010-07-16 02:23:23 +0900119} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +0900120
121//------------------------------------------------------------------------------
122
darin@google.com981f3552008-08-16 12:09:05 +0900123#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900124
initial.commit3f4a7322008-07-27 06:49:38 +0900125// Upon a SEH exception in this thread, it restores the original unhandled
126// exception filter.
127static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
128 ::SetUnhandledExceptionFilter(old_filter);
129 return EXCEPTION_CONTINUE_SEARCH;
130}
131
132// Retrieves a pointer to the current unhandled exception filter. There
133// is no standalone getter method.
134static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
135 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
136 top_filter = ::SetUnhandledExceptionFilter(0);
137 ::SetUnhandledExceptionFilter(top_filter);
138 return top_filter;
139}
140
darin@google.com981f3552008-08-16 12:09:05 +0900141#endif // defined(OS_WIN)
142
initial.commit3f4a7322008-07-27 06:49:38 +0900143//------------------------------------------------------------------------------
144
erg@chromium.org493f5f62010-07-16 06:03:54 +0900145MessageLoop::TaskObserver::TaskObserver() {
146}
147
148MessageLoop::TaskObserver::~TaskObserver() {
149}
150
151MessageLoop::DestructionObserver::~DestructionObserver() {
152}
153
154//------------------------------------------------------------------------------
155
darin@google.comd936b5b2008-08-26 14:53:57 +0900156MessageLoop::MessageLoop(Type type)
157 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900158 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900159 exception_restoration_(false),
jar@chromium.org34571142011-04-05 13:48:53 +0900160 message_histogram_(NULL),
darin@google.combe165ae2008-09-07 17:08:29 +0900161 state_(NULL),
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900162 should_leak_tasks_(true),
ananta@chromium.orgc542fec2011-03-24 12:40:28 +0900163#ifdef OS_WIN
164 os_modal_loop_(false),
165#endif // OS_WIN
darin@google.combe165ae2008-09-07 17:08:29 +0900166 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900167 DCHECK(!current()) << "should only have one message loop per thread";
168 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900169
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900170// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900171#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900172#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
173#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
174#elif defined(OS_MACOSX)
175#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
176#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900177#elif defined(TOUCH_UI)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900178#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900179#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900180#elif defined(OS_NACL)
181// Currently NaCl doesn't have a UI or an IO MessageLoop.
182// TODO(abarth): Figure out if we need these.
183#define MESSAGE_PUMP_UI NULL
184#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900185#elif defined(OS_POSIX) // POSIX but not MACOSX.
186#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
187#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900188#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900189#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900190#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900191
192 if (type_ == TYPE_UI) {
193 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900194 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900195 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900196 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900197 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900198 pump_ = new base::MessagePumpDefault();
199 }
initial.commit3f4a7322008-07-27 06:49:38 +0900200}
201
202MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900203 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900204
darin@google.com0e500502008-09-09 14:55:35 +0900205 DCHECK(!state_);
206
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900207 // Clean up any unprocessed tasks, but take care: deleting a task could
208 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
209 // limit on the number of times we will allow a deleted task to generate more
210 // tasks. Normally, we should only pass through this loop once or twice. If
211 // we end up hitting the loop limit, then it is probably due to one task that
212 // is being stubborn. Inspect the queues to see who is left.
213 bool did_work;
214 for (int i = 0; i < 100; ++i) {
215 DeletePendingTasks();
216 ReloadWorkQueue();
217 // If we end up with empty queues, then break out of the loop.
218 did_work = DeletePendingTasks();
219 if (!did_work)
220 break;
darin@google.com0e500502008-09-09 14:55:35 +0900221 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900222 DCHECK(!did_work);
223
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900224 // Let interested parties have one last shot at accessing this.
225 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
226 WillDestroyCurrentMessageLoop());
227
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900228 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900229 lazy_tls_ptr.Pointer()->Set(NULL);
mbelshe@chromium.orgbee85b32011-05-16 04:20:49 +0900230
231#if defined(OS_WIN)
232 // If we left the high-resolution timer activated, deactivate it now.
233 // Doing this is not-critical, it is mainly to make sure we track
234 // the high resolution timer activations properly in our unit tests.
235 if (!high_resolution_timer_expiration_.is_null()) {
236 base::Time::ActivateHighResolutionTimer(false);
237 high_resolution_timer_expiration_ = base::TimeTicks();
238 }
239#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900240}
241
erg@google.com67a25432011-01-08 05:23:43 +0900242// static
243MessageLoop* MessageLoop::current() {
244 // TODO(darin): sadly, we cannot enable this yet since people call us even
245 // when they have no intention of using us.
246 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
247 return lazy_tls_ptr.Pointer()->Get();
248}
249
250// static
251void MessageLoop::EnableHistogrammer(bool enable) {
252 enable_histogrammer_ = enable;
253}
254
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900255void MessageLoop::AddDestructionObserver(
256 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900257 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900258 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900259}
260
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900261void MessageLoop::RemoveDestructionObserver(
262 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900263 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900264 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900265}
266
darin@google.combe165ae2008-09-07 17:08:29 +0900267void MessageLoop::PostTask(
268 const tracked_objects::Location& from_here, Task* task) {
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(0), true);
275 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900276}
277
278void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900279 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
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(delay_ms), true);
286 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900287}
288
289void MessageLoop::PostNonNestableTask(
290 const tracked_objects::Location& from_here, Task* task) {
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(0), false);
297 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900298}
299
300void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900301 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900302 CHECK(task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900303 PendingTask pending_task(
304 base::Bind(&TaskClosureAdapter::Run,
305 new TaskClosureAdapter(task, &should_leak_tasks_)),
306 from_here,
307 CalculateDelayedRuntime(delay_ms), false);
308 AddToIncomingQueue(&pending_task);
309}
310
311void MessageLoop::PostTask(
312 const tracked_objects::Location& from_here, const base::Closure& task) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900313 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900314 PendingTask pending_task(task, from_here, CalculateDelayedRuntime(0), true);
315 AddToIncomingQueue(&pending_task);
316}
317
318void MessageLoop::PostDelayedTask(
319 const tracked_objects::Location& from_here, const base::Closure& task,
320 int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900321 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900322 PendingTask pending_task(task, from_here,
323 CalculateDelayedRuntime(delay_ms), true);
324 AddToIncomingQueue(&pending_task);
325}
326
327void MessageLoop::PostNonNestableTask(
328 const tracked_objects::Location& from_here, const base::Closure& task) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900329 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900330 PendingTask pending_task(task, from_here, CalculateDelayedRuntime(0), false);
331 AddToIncomingQueue(&pending_task);
332}
333
334void MessageLoop::PostNonNestableDelayedTask(
335 const tracked_objects::Location& from_here, const base::Closure& task,
336 int64 delay_ms) {
apatrick@chromium.org47db3702011-05-11 06:52:21 +0900337 CHECK(!task.is_null());
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900338 PendingTask pending_task(task, from_here,
339 CalculateDelayedRuntime(delay_ms), false);
340 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900341}
342
erg@google.com67a25432011-01-08 05:23:43 +0900343void MessageLoop::Run() {
344 AutoRunState save_state(this);
345 RunHandler();
346}
darin@google.com0795f572008-08-30 09:22:48 +0900347
erg@google.com67a25432011-01-08 05:23:43 +0900348void MessageLoop::RunAllPending() {
349 AutoRunState save_state(this);
350 state_->quit_received = true; // Means run until we would otherwise block.
351 RunHandler();
352}
darin@google.com0795f572008-08-30 09:22:48 +0900353
erg@google.com67a25432011-01-08 05:23:43 +0900354void MessageLoop::Quit() {
355 DCHECK_EQ(this, current());
356 if (state_) {
357 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900358 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900359 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900360 }
erg@google.com67a25432011-01-08 05:23:43 +0900361}
darin@google.com0795f572008-08-30 09:22:48 +0900362
erg@google.com67a25432011-01-08 05:23:43 +0900363void MessageLoop::QuitNow() {
364 DCHECK_EQ(this, current());
365 if (state_) {
366 pump_->Quit();
367 } else {
368 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900369 }
initial.commit3f4a7322008-07-27 06:49:38 +0900370}
371
372void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900373 if (nestable_tasks_allowed_ != allowed) {
374 nestable_tasks_allowed_ = allowed;
375 if (!nestable_tasks_allowed_)
376 return;
377 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900378 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900379 }
initial.commit3f4a7322008-07-27 06:49:38 +0900380}
381
382bool MessageLoop::NestableTasksAllowed() const {
383 return nestable_tasks_allowed_;
384}
385
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900386bool MessageLoop::IsNested() {
387 return state_->run_depth > 1;
388}
389
erg@google.com67a25432011-01-08 05:23:43 +0900390void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
391 DCHECK_EQ(this, current());
392 task_observers_.AddObserver(task_observer);
393}
394
395void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
396 DCHECK_EQ(this, current());
397 task_observers_.RemoveObserver(task_observer);
398}
399
willchan@chromium.org3a397672011-01-26 09:53:48 +0900400void MessageLoop::AssertIdle() const {
401 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
402 base::AutoLock lock(incoming_queue_lock_);
403 DCHECK(incoming_queue_.empty());
404}
405
initial.commit3f4a7322008-07-27 06:49:38 +0900406//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900407
erg@google.com67a25432011-01-08 05:23:43 +0900408// Runs the loop in two different SEH modes:
409// enable_SEH_restoration_ = false : any unhandled exception goes to the last
410// one that calls SetUnhandledExceptionFilter().
411// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
412// that was existed before the loop was run.
413void MessageLoop::RunHandler() {
414#if defined(OS_WIN)
415 if (exception_restoration_) {
416 RunInternalInSEHFrame();
417 return;
418 }
419#endif
420
421 RunInternal();
422}
423
424#if defined(OS_WIN)
425__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
426 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
427 __try {
428 RunInternal();
429 } __except(SEHFilter(current_filter)) {
430 }
431 return;
432}
433#endif
434
435void MessageLoop::RunInternal() {
436 DCHECK_EQ(this, current());
437
438 StartHistogrammer();
439
440#if !defined(OS_MACOSX)
441 if (state_->dispatcher && type() == TYPE_UI) {
442 static_cast<base::MessagePumpForUI*>(pump_.get())->
443 RunWithDispatcher(this, state_->dispatcher);
444 return;
445 }
446#endif
447
448 pump_->Run(this);
449}
450
451bool MessageLoop::ProcessNextDelayedNonNestableTask() {
452 if (state_->run_depth != 1)
453 return false;
454
455 if (deferred_non_nestable_work_queue_.empty())
456 return false;
457
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900458 PendingTask pending_task = deferred_non_nestable_work_queue_.front();
erg@google.com67a25432011-01-08 05:23:43 +0900459 deferred_non_nestable_work_queue_.pop();
460
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900461 RunTask(pending_task);
erg@google.com67a25432011-01-08 05:23:43 +0900462 return true;
463}
464
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900465void MessageLoop::RunTask(const PendingTask& pending_task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900466 DCHECK(nestable_tasks_allowed_);
467 // Execute the task and assume the worst: It is probably not reentrant.
468 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900469
470 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900471 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900472 WillProcessTask(pending_task.time_posted));
473 pending_task.task.Run();
474 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
475 DidProcessTask(pending_task.time_posted));
476
477#if defined(TRACK_ALL_TASK_OBJECTS)
478 if (tracked_objects::ThreadData::IsActive() && pending_task.post_births) {
479 tracked_objects::ThreadData::current()->TallyADeath(
480 *pending_task.post_births,
481 TimeTicks::Now() - pending_task.time_posted);
482 }
483#endif // defined(TRACK_ALL_TASK_OBJECTS)
darin@google.combe165ae2008-09-07 17:08:29 +0900484
485 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900486}
487
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900488bool MessageLoop::DeferOrRunPendingTask(
489 const PendingTask& pending_task) {
darin@google.combe165ae2008-09-07 17:08:29 +0900490 if (pending_task.nestable || state_->run_depth == 1) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900491 RunTask(pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900492 // Show that we ran a task (Note: a new one might arrive as a
493 // consequence!).
494 return true;
495 }
496
497 // We couldn't run the task now because we're in a nested message loop
498 // and the task isn't nestable.
499 deferred_non_nestable_work_queue_.push(pending_task);
500 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900501}
502
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900503void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
504 // Move to the delayed work queue. Initialize the sequence number
505 // before inserting into the delayed_work_queue_. The sequence number
506 // is used to faciliate FIFO sorting when two tasks have the same
507 // delayed_run_time value.
508 PendingTask new_pending_task(pending_task);
509 new_pending_task.sequence_num = next_sequence_num_++;
510 delayed_work_queue_.push(new_pending_task);
511}
512
initial.commit3f4a7322008-07-27 06:49:38 +0900513void MessageLoop::ReloadWorkQueue() {
514 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900515 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
516 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900517 // queues get large.
518 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900519 return; // Wait till we *really* need to lock and load.
520
521 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900522 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900523 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900524 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900525 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900526 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900527 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900528 }
529}
530
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900531bool MessageLoop::DeletePendingTasks() {
532 bool did_work = !work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900533 // TODO(darin): Delete all tasks once it is safe to do so.
534 // Until it is totally safe, just do it when running Purify or
535 // Valgrind.
536 //
537 // See http://crbug.com/61131
538 //
539#if defined(PURIFY) || defined(USE_HEAPCHECKER)
540 should_leak_tasks_ = false;
541#else
542 if (RunningOnValgrind())
543 should_leak_tasks_ = false;
544#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900545 while (!work_queue_.empty()) {
546 PendingTask pending_task = work_queue_.front();
547 work_queue_.pop();
548 if (!pending_task.delayed_run_time.is_null()) {
549 // We want to delete delayed tasks in the same order in which they would
550 // normally be deleted in case of any funny dependencies between delayed
551 // tasks.
552 AddToDelayedWorkQueue(pending_task);
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900553 }
initial.commit3f4a7322008-07-27 06:49:38 +0900554 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900555 did_work |= !deferred_non_nestable_work_queue_.empty();
556 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900557 deferred_non_nestable_work_queue_.pop();
initial.commit3f4a7322008-07-27 06:49:38 +0900558 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900559 did_work |= !delayed_work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900560
561 // Historically, we always delete the task regardless of valgrind status. It's
562 // not completely clear why we want to leak them in the loops above. This
563 // code is replicating legacy behavior, and should not be considered
564 // absolutely "correct" behavior. See TODO above about deleting all tasks
565 // when it's safe.
566 should_leak_tasks_ = false;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900567 while (!delayed_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900568 delayed_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900569 }
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900570 should_leak_tasks_ = true;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900571 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900572}
573
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900574TimeTicks MessageLoop::CalculateDelayedRuntime(int64 delay_ms) {
575 TimeTicks delayed_run_time;
erg@google.com67a25432011-01-08 05:23:43 +0900576 if (delay_ms > 0) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900577 delayed_run_time =
erg@google.com67a25432011-01-08 05:23:43 +0900578 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
579
580#if defined(OS_WIN)
581 if (high_resolution_timer_expiration_.is_null()) {
582 // Windows timers are granular to 15.6ms. If we only set high-res
583 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
584 // which as a percentage is pretty inaccurate. So enable high
585 // res timers for any timer which is within 2x of the granularity.
586 // This is a tradeoff between accuracy and power management.
587 bool needs_high_res_timers =
588 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
589 if (needs_high_res_timers) {
mbelshe@chromium.orgbee85b32011-05-16 04:20:49 +0900590 if (base::Time::ActivateHighResolutionTimer(true)) {
591 high_resolution_timer_expiration_ = TimeTicks::Now() +
592 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
593 }
erg@google.com67a25432011-01-08 05:23:43 +0900594 }
595 }
596#endif
597 } else {
598 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
599 }
600
601#if defined(OS_WIN)
602 if (!high_resolution_timer_expiration_.is_null()) {
603 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
604 base::Time::ActivateHighResolutionTimer(false);
605 high_resolution_timer_expiration_ = TimeTicks();
606 }
607 }
608#endif
609
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900610 return delayed_run_time;
611}
612
613// Possibly called on a background thread!
614void MessageLoop::AddToIncomingQueue(PendingTask* pending_task) {
erg@google.com67a25432011-01-08 05:23:43 +0900615 // Warning: Don't try to short-circuit, and handle this thread's tasks more
616 // directly, as it could starve handling of foreign threads. Put every task
617 // into this queue.
618
619 scoped_refptr<base::MessagePump> pump;
620 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900621 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900622
623 bool was_empty = incoming_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900624 incoming_queue_.push(*pending_task);
625 pending_task->task.Reset();
erg@google.com67a25432011-01-08 05:23:43 +0900626 if (!was_empty)
627 return; // Someone else should have started the sub-pump.
628
629 pump = pump_;
630 }
631 // Since the incoming_queue_ may contain a task that destroys this message
632 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
633 // We use a stack-based reference to the message pump so that we can call
634 // ScheduleWork outside of incoming_queue_lock_.
635
636 pump->ScheduleWork();
637}
638
639//------------------------------------------------------------------------------
640// Method and data for histogramming events and actions taken by each instance
641// on each thread.
642
643void MessageLoop::StartHistogrammer() {
jar@chromium.org34571142011-04-05 13:48:53 +0900644 if (enable_histogrammer_ && !message_histogram_
erg@google.com67a25432011-01-08 05:23:43 +0900645 && base::StatisticsRecorder::IsActive()) {
646 DCHECK(!thread_name_.empty());
647 message_histogram_ = base::LinearHistogram::FactoryGet(
648 "MsgLoop:" + thread_name_,
649 kLeastNonZeroMessageId, kMaxMessageId,
650 kNumberOfDistinctMessagesDisplayed,
651 message_histogram_->kHexRangePrintingFlag);
652 message_histogram_->SetRangeDescriptions(event_descriptions_);
653 }
654}
655
656void MessageLoop::HistogramEvent(int event) {
jar@chromium.org34571142011-04-05 13:48:53 +0900657 if (message_histogram_)
erg@google.com67a25432011-01-08 05:23:43 +0900658 message_histogram_->Add(event);
659}
660
darin@google.com981f3552008-08-16 12:09:05 +0900661bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900662 if (!nestable_tasks_allowed_) {
663 // Task can't be executed right now.
664 return false;
665 }
666
667 for (;;) {
668 ReloadWorkQueue();
669 if (work_queue_.empty())
670 break;
671
672 // Execute oldest task.
673 do {
674 PendingTask pending_task = work_queue_.front();
675 work_queue_.pop();
676 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900677 AddToDelayedWorkQueue(pending_task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900678 // If we changed the topmost task, then it is time to reschedule.
679 if (delayed_work_queue_.top().task.Equals(pending_task.task))
darin@google.combe165ae2008-09-07 17:08:29 +0900680 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
681 } else {
682 if (DeferOrRunPendingTask(pending_task))
683 return true;
684 }
685 } while (!work_queue_.empty());
686 }
687
688 // Nothing happened.
689 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900690}
691
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900692bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900693 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900694 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900695 return false;
696 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900697
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900698 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900699 // queue that are ready to run. To increase efficiency when we fall behind,
700 // we will only call Time::Now() intermittently, and then process all tasks
701 // that are ready to run before calling it again. As a result, the more we
702 // fall behind (and have a lot of ready-to-run delayed tasks), the more
703 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900704
705 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900706 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900707 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900708 if (next_run_time > recent_time_) {
709 *next_delayed_work_time = next_run_time;
710 return false;
711 }
darin@google.combe165ae2008-09-07 17:08:29 +0900712 }
darin@google.com981f3552008-08-16 12:09:05 +0900713
jar@chromium.org40355072010-10-21 15:32:33 +0900714 PendingTask pending_task = delayed_work_queue_.top();
715 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900716
jar@chromium.org40355072010-10-21 15:32:33 +0900717 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900718 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900719
darin@google.combe165ae2008-09-07 17:08:29 +0900720 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900721}
722
723bool MessageLoop::DoIdleWork() {
724 if (ProcessNextDelayedNonNestableTask())
725 return true;
726
727 if (state_->quit_received)
728 pump_->Quit();
729
730 return false;
731}
732
733//------------------------------------------------------------------------------
734// MessageLoop::AutoRunState
735
736MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
737 // Make the loop reference us.
738 previous_state_ = loop_->state_;
739 if (previous_state_) {
740 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900741 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900742 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900743 }
darin@google.com981f3552008-08-16 12:09:05 +0900744 loop_->state_ = this;
745
746 // Initialize the other fields:
747 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900748#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900749 dispatcher = NULL;
750#endif
751}
752
753MessageLoop::AutoRunState::~AutoRunState() {
754 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900755}
756
initial.commit3f4a7322008-07-27 06:49:38 +0900757//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900758// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900759
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900760MessageLoop::PendingTask::PendingTask(
761 const base::Closure& task,
762 const tracked_objects::Location& posted_from,
763 TimeTicks delayed_run_time,
764 bool nestable)
765 : task(task),
766 time_posted(TimeTicks::Now()),
767 delayed_run_time(delayed_run_time),
768 sequence_num(0),
769 nestable(nestable) {
770#if defined(TRACK_ALL_TASK_OBJECTS)
771 if (tracked_objects::ThreadData::IsActive()) {
772 tracked_objects::ThreadData* current_thread_data =
773 tracked_objects::ThreadData::current();
774 if (current_thread_data) {
775 post_births = current_thread_data->TallyABirth(posted_from);
776 } else {
777 // Shutdown started, and this thread wasn't registered.
778 post_births = NULL;
779 }
780 }
781#endif // defined(TRACK_ALL_TASK_OBJECTS)
782}
783
784MessageLoop::PendingTask::~PendingTask() {
785}
786
darin@google.combe165ae2008-09-07 17:08:29 +0900787bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
788 // Since the top of a priority queue is defined as the "greatest" element, we
789 // need to invert the comparison here. We want the smaller time to be at the
790 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900791
darin@google.combe165ae2008-09-07 17:08:29 +0900792 if (delayed_run_time < other.delayed_run_time)
793 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900794
darin@google.combe165ae2008-09-07 17:08:29 +0900795 if (delayed_run_time > other.delayed_run_time)
796 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900797
darin@google.combe165ae2008-09-07 17:08:29 +0900798 // If the times happen to match, then we use the sequence number to decide.
799 // Compare the difference to support integer roll-over.
800 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900801}
802
803//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900804// MessageLoopForUI
805
806#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900807void MessageLoopForUI::DidProcessMessage(const MSG& message) {
808 pump_win()->DidProcessMessage(message);
809}
darin@google.comd936b5b2008-08-26 14:53:57 +0900810#endif // defined(OS_WIN)
811
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900812#if defined(USE_X11)
813Display* MessageLoopForUI::GetDisplay() {
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900814 return gdk_x11_get_default_xdisplay();
815}
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900816#endif // defined(USE_X11)
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900817
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900818#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900819void MessageLoopForUI::AddObserver(Observer* observer) {
820 pump_ui()->AddObserver(observer);
821}
822
823void MessageLoopForUI::RemoveObserver(Observer* observer) {
824 pump_ui()->RemoveObserver(observer);
825}
826
827void MessageLoopForUI::Run(Dispatcher* dispatcher) {
828 AutoRunState save_state(this);
829 state_->dispatcher = dispatcher;
830 RunHandler();
831}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900832#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900833
darin@google.comd936b5b2008-08-26 14:53:57 +0900834//------------------------------------------------------------------------------
835// MessageLoopForIO
836
837#if defined(OS_WIN)
838
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900839void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
840 pump_io()->RegisterIOHandler(file, handler);
841}
842
rvargas@google.com73887542008-11-08 06:52:15 +0900843bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
844 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900845}
846
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900847#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900848
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900849bool MessageLoopForIO::WatchFileDescriptor(int fd,
850 bool persistent,
851 Mode mode,
852 FileDescriptorWatcher *controller,
853 Watcher *delegate) {
854 return pump_libevent()->WatchFileDescriptor(
855 fd,
856 persistent,
857 static_cast<base::MessagePumpLibevent::Mode>(mode),
858 controller,
859 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900860}
861
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900862#endif