blob: aa04f45ff3d3c66b3f97932330d4588b59a33962 [file] [log] [blame]
jhawkins@chromium.orge194f3d2012-01-05 11:18:18 +09001// Copyright (c) 2012 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"
apatrick@chromium.org87164042011-05-20 07:28:25 +090011#include "base/debug/alias.h"
jbates@chromium.orgb84db522011-10-04 02:51:25 +090012#include "base/debug/trace_event.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090013#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090014#include "base/logging.h"
thestig@chromium.orgefd4aaf2011-06-15 13:14:23 +090015#include "base/memory/scoped_ptr.h"
nduca@chromium.orgba048612011-08-16 05:33:46 +090016#include "base/message_loop_proxy_impl.h"
darin@google.com12d40bb2008-08-20 03:36:23 +090017#include "base/message_pump_default.h"
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090018#include "base/metrics/histogram.h"
timurrrr@chromium.org490200b2011-01-05 04:06:51 +090019#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
brettw@chromium.org63965582010-12-31 07:18:56 +090020#include "base/threading/thread_local.h"
mbelshe@chromium.orgbee85b32011-05-16 04:20:49 +090021#include "base/time.h"
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090022#include "base/tracked_objects.h"
initial.commit3f4a7322008-07-27 06:49:38 +090023
mark@chromium.org059d0492008-09-24 06:08:28 +090024#if defined(OS_MACOSX)
25#include "base/message_pump_mac.h"
26#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090027#if defined(OS_POSIX)
28#include "base/message_pump_libevent.h"
29#endif
michaelbai@google.com686190b2011-08-03 01:11:16 +090030#if defined(OS_ANDROID)
31#include "base/message_pump_android.h"
32#endif
sadrul@chromium.org847a5722011-09-21 09:17:19 +090033#if defined(TOOLKIT_USES_GTK)
ajwong@chromium.org94d2a582011-04-21 01:02:23 +090034#include <gdk/gdk.h>
35#include <gdk/gdkx.h>
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +090036#endif // defined(OS_POSIX) && !defined(OS_MACOSX)
dkegel@google.com9e044ae2008-09-19 03:46:26 +090037
jhawkins@chromium.org2af12f22011-11-16 08:36:30 +090038using base::PendingTask;
dsh@google.com0f8dd262008-10-28 05:43:33 +090039using base::TimeDelta;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090040using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090041
erg@chromium.orga7528522010-07-16 02:23:23 +090042namespace {
43
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090044// A lazily created thread local storage for quick access to a thread's message
45// loop, if one exists. This should be safe and free of static constructors.
joth@chromium.orgb24883c2011-11-15 22:31:49 +090046base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr =
47 LAZY_INSTANCE_INITIALIZER;
initial.commit3f4a7322008-07-27 06:49:38 +090048
initial.commit3f4a7322008-07-27 06:49:38 +090049// Logical events for Histogram profiling. Run with -message-loop-histogrammer
50// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090051const int kTaskRunEvent = 0x1;
52const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090053
54// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090055const int kLeastNonZeroMessageId = 1;
56const int kMaxMessageId = 1099;
57const int kNumberOfDistinctMessagesDisplayed = 1100;
58
59// Provide a macro that takes an expression (such as a constant, or macro
60// constant) and creates a pair to initalize an array of pairs. In this case,
61// our pair consists of the expressions value, and the "stringized" version
62// of the expression (i.e., the exrpression put in quotes). For example, if
63// we have:
64// #define FOO 2
65// #define BAR 5
66// then the following:
67// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
68// will expand to:
69// {7, "FOO + BAR"}
70// We use the resulting array as an argument to our histogram, which reads the
71// number as a bucket identifier, and proceeds to use the corresponding name
72// in the pair (i.e., the quoted string) when printing out a histogram.
73#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
74
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090075const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090076 // Provide some pretty print capability in our histogram for our internal
77 // messages.
78
79 // A few events we handle (kindred to messages), and used to profile actions.
80 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
81 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
82
83 {-1, NULL} // The list must be null terminated, per API to histogram.
84};
85
86bool enable_histogrammer_ = false;
87
michaelbai@google.com686190b2011-08-03 01:11:16 +090088MessageLoop::MessagePumpFactory* message_pump_for_ui_factory_ = NULL;
89
erg@chromium.orga7528522010-07-16 02:23:23 +090090} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090091
92//------------------------------------------------------------------------------
93
darin@google.com981f3552008-08-16 12:09:05 +090094#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090095
initial.commit3f4a7322008-07-27 06:49:38 +090096// Upon a SEH exception in this thread, it restores the original unhandled
97// exception filter.
98static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
99 ::SetUnhandledExceptionFilter(old_filter);
100 return EXCEPTION_CONTINUE_SEARCH;
101}
102
103// Retrieves a pointer to the current unhandled exception filter. There
104// is no standalone getter method.
105static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
106 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
107 top_filter = ::SetUnhandledExceptionFilter(0);
108 ::SetUnhandledExceptionFilter(top_filter);
109 return top_filter;
110}
111
darin@google.com981f3552008-08-16 12:09:05 +0900112#endif // defined(OS_WIN)
113
initial.commit3f4a7322008-07-27 06:49:38 +0900114//------------------------------------------------------------------------------
115
erg@chromium.org493f5f62010-07-16 06:03:54 +0900116MessageLoop::TaskObserver::TaskObserver() {
117}
118
119MessageLoop::TaskObserver::~TaskObserver() {
120}
121
122MessageLoop::DestructionObserver::~DestructionObserver() {
123}
124
125//------------------------------------------------------------------------------
126
darin@google.comd936b5b2008-08-26 14:53:57 +0900127MessageLoop::MessageLoop(Type type)
128 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900129 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900130 exception_restoration_(false),
jar@chromium.org34571142011-04-05 13:48:53 +0900131 message_histogram_(NULL),
darin@google.combe165ae2008-09-07 17:08:29 +0900132 state_(NULL),
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900133 should_leak_tasks_(true),
ananta@chromium.orgc542fec2011-03-24 12:40:28 +0900134#ifdef OS_WIN
135 os_modal_loop_(false),
136#endif // OS_WIN
darin@google.combe165ae2008-09-07 17:08:29 +0900137 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900138 DCHECK(!current()) << "should only have one message loop per thread";
139 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900140
nduca@chromium.orgba048612011-08-16 05:33:46 +0900141 message_loop_proxy_ = new base::MessageLoopProxyImpl();
142
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900143// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900144#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900145#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
146#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
147#elif defined(OS_MACOSX)
148#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
149#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900150#elif defined(OS_NACL)
151// Currently NaCl doesn't have a UI or an IO MessageLoop.
152// TODO(abarth): Figure out if we need these.
153#define MESSAGE_PUMP_UI NULL
154#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900155#elif defined(OS_POSIX) // POSIX but not MACOSX.
piman@chromium.orgbfd272d2011-12-15 01:34:31 +0900156#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900157#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900158#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900159#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900160#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900161
162 if (type_ == TYPE_UI) {
michaelbai@google.com686190b2011-08-03 01:11:16 +0900163 if (message_pump_for_ui_factory_)
164 pump_ = message_pump_for_ui_factory_();
165 else
166 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900167 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900168 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900169 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900170 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900171 pump_ = new base::MessagePumpDefault();
172 }
initial.commit3f4a7322008-07-27 06:49:38 +0900173}
174
175MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900176 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900177
darin@google.com0e500502008-09-09 14:55:35 +0900178 DCHECK(!state_);
179
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900180 // Clean up any unprocessed tasks, but take care: deleting a task could
181 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
182 // limit on the number of times we will allow a deleted task to generate more
183 // tasks. Normally, we should only pass through this loop once or twice. If
184 // we end up hitting the loop limit, then it is probably due to one task that
185 // is being stubborn. Inspect the queues to see who is left.
186 bool did_work;
187 for (int i = 0; i < 100; ++i) {
188 DeletePendingTasks();
189 ReloadWorkQueue();
190 // If we end up with empty queues, then break out of the loop.
191 did_work = DeletePendingTasks();
192 if (!did_work)
193 break;
darin@google.com0e500502008-09-09 14:55:35 +0900194 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900195 DCHECK(!did_work);
196
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900197 // Let interested parties have one last shot at accessing this.
198 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
199 WillDestroyCurrentMessageLoop());
200
nduca@chromium.orgba048612011-08-16 05:33:46 +0900201 // Tell the message_loop_proxy that we are dying.
202 static_cast<base::MessageLoopProxyImpl*>(message_loop_proxy_.get())->
203 WillDestroyCurrentMessageLoop();
204 message_loop_proxy_ = NULL;
205
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900206 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900207 lazy_tls_ptr.Pointer()->Set(NULL);
mbelshe@chromium.orgbee85b32011-05-16 04:20:49 +0900208
209#if defined(OS_WIN)
210 // If we left the high-resolution timer activated, deactivate it now.
211 // Doing this is not-critical, it is mainly to make sure we track
212 // the high resolution timer activations properly in our unit tests.
213 if (!high_resolution_timer_expiration_.is_null()) {
214 base::Time::ActivateHighResolutionTimer(false);
215 high_resolution_timer_expiration_ = base::TimeTicks();
216 }
217#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900218}
219
erg@google.com67a25432011-01-08 05:23:43 +0900220// static
221MessageLoop* MessageLoop::current() {
222 // TODO(darin): sadly, we cannot enable this yet since people call us even
223 // when they have no intention of using us.
224 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
225 return lazy_tls_ptr.Pointer()->Get();
226}
227
228// static
229void MessageLoop::EnableHistogrammer(bool enable) {
230 enable_histogrammer_ = enable;
231}
232
michaelbai@google.com686190b2011-08-03 01:11:16 +0900233// static
234void MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory* factory) {
235 DCHECK(!message_pump_for_ui_factory_);
236 message_pump_for_ui_factory_ = factory;
237}
238
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900239void MessageLoop::AddDestructionObserver(
240 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900241 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900242 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900243}
244
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900245void MessageLoop::RemoveDestructionObserver(
246 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900247 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900248 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900249}
250
darin@google.combe165ae2008-09-07 17:08:29 +0900251void MessageLoop::PostTask(
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900252 const tracked_objects::Location& from_here, const base::Closure& task) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900253 DCHECK(!task.is_null()) << from_here.ToString();
jhawkins@chromium.org2af12f22011-11-16 08:36:30 +0900254 PendingTask pending_task(from_here, task, CalculateDelayedRuntime(0), true);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900255 AddToIncomingQueue(&pending_task);
256}
257
258void MessageLoop::PostDelayedTask(
tedvessenes@gmail.com658a87f2011-12-30 10:04:36 +0900259 const tracked_objects::Location& from_here,
260 const base::Closure& task,
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900261 int64 delay_ms) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900262 DCHECK(!task.is_null()) << from_here.ToString();
jhawkins@chromium.org2af12f22011-11-16 08:36:30 +0900263 PendingTask pending_task(from_here, task,
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900264 CalculateDelayedRuntime(delay_ms), true);
265 AddToIncomingQueue(&pending_task);
266}
267
tedvessenes@gmail.com658a87f2011-12-30 10:04:36 +0900268void MessageLoop::PostDelayedTask(
269 const tracked_objects::Location& from_here,
270 const base::Closure& task,
271 base::TimeDelta delay) {
272 PostDelayedTask(from_here, task, delay.InMillisecondsRoundedUp());
273}
274
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900275void MessageLoop::PostNonNestableTask(
276 const tracked_objects::Location& from_here, const base::Closure& task) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900277 DCHECK(!task.is_null()) << from_here.ToString();
jhawkins@chromium.org2af12f22011-11-16 08:36:30 +0900278 PendingTask pending_task(from_here, task, CalculateDelayedRuntime(0), false);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900279 AddToIncomingQueue(&pending_task);
280}
281
282void MessageLoop::PostNonNestableDelayedTask(
283 const tracked_objects::Location& from_here, const base::Closure& task,
284 int64 delay_ms) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900285 DCHECK(!task.is_null()) << from_here.ToString();
jhawkins@chromium.org2af12f22011-11-16 08:36:30 +0900286 PendingTask pending_task(from_here, task,
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900287 CalculateDelayedRuntime(delay_ms), false);
288 AddToIncomingQueue(&pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900289}
290
tedvessenes@gmail.com658a87f2011-12-30 10:04:36 +0900291void MessageLoop::PostNonNestableDelayedTask(
292 const tracked_objects::Location& from_here,
293 const base::Closure& task,
294 base::TimeDelta delay) {
295 PostNonNestableDelayedTask(from_here, task, delay.InMillisecondsRoundedUp());
296}
297
erg@google.com67a25432011-01-08 05:23:43 +0900298void MessageLoop::Run() {
299 AutoRunState save_state(this);
300 RunHandler();
301}
darin@google.com0795f572008-08-30 09:22:48 +0900302
erg@google.com67a25432011-01-08 05:23:43 +0900303void MessageLoop::RunAllPending() {
304 AutoRunState save_state(this);
305 state_->quit_received = true; // Means run until we would otherwise block.
306 RunHandler();
307}
darin@google.com0795f572008-08-30 09:22:48 +0900308
erg@google.com67a25432011-01-08 05:23:43 +0900309void MessageLoop::Quit() {
310 DCHECK_EQ(this, current());
311 if (state_) {
312 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900313 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900314 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900315 }
erg@google.com67a25432011-01-08 05:23:43 +0900316}
darin@google.com0795f572008-08-30 09:22:48 +0900317
erg@google.com67a25432011-01-08 05:23:43 +0900318void MessageLoop::QuitNow() {
319 DCHECK_EQ(this, current());
320 if (state_) {
321 pump_->Quit();
322 } else {
323 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900324 }
initial.commit3f4a7322008-07-27 06:49:38 +0900325}
326
kalman@chromium.orgc89ed902011-10-21 15:21:57 +0900327static void QuitCurrent() {
328 MessageLoop::current()->Quit();
329}
330
jhawkins@chromium.org573d4182011-10-17 10:20:36 +0900331// static
332base::Closure MessageLoop::QuitClosure() {
kalman@chromium.orgc89ed902011-10-21 15:21:57 +0900333 return base::Bind(&QuitCurrent);
jhawkins@chromium.org573d4182011-10-17 10:20:36 +0900334}
335
initial.commit3f4a7322008-07-27 06:49:38 +0900336void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900337 if (nestable_tasks_allowed_ != allowed) {
338 nestable_tasks_allowed_ = allowed;
339 if (!nestable_tasks_allowed_)
340 return;
341 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900342 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900343 }
initial.commit3f4a7322008-07-27 06:49:38 +0900344}
345
346bool MessageLoop::NestableTasksAllowed() const {
347 return nestable_tasks_allowed_;
348}
349
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900350bool MessageLoop::IsNested() {
351 return state_->run_depth > 1;
352}
353
erg@google.com67a25432011-01-08 05:23:43 +0900354void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
355 DCHECK_EQ(this, current());
356 task_observers_.AddObserver(task_observer);
357}
358
359void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
360 DCHECK_EQ(this, current());
361 task_observers_.RemoveObserver(task_observer);
362}
363
willchan@chromium.org3a397672011-01-26 09:53:48 +0900364void MessageLoop::AssertIdle() const {
365 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
366 base::AutoLock lock(incoming_queue_lock_);
367 DCHECK(incoming_queue_.empty());
368}
369
willchan@chromium.orgfe2201e2011-11-02 07:06:58 +0900370bool MessageLoop::is_running() const {
371 DCHECK_EQ(this, current());
372 return state_ != NULL;
373}
374
initial.commit3f4a7322008-07-27 06:49:38 +0900375//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900376
erg@google.com67a25432011-01-08 05:23:43 +0900377// Runs the loop in two different SEH modes:
378// enable_SEH_restoration_ = false : any unhandled exception goes to the last
379// one that calls SetUnhandledExceptionFilter().
380// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
381// that was existed before the loop was run.
382void MessageLoop::RunHandler() {
383#if defined(OS_WIN)
384 if (exception_restoration_) {
385 RunInternalInSEHFrame();
386 return;
387 }
388#endif
389
390 RunInternal();
391}
392
393#if defined(OS_WIN)
394__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
395 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
396 __try {
397 RunInternal();
398 } __except(SEHFilter(current_filter)) {
399 }
400 return;
401}
402#endif
403
404void MessageLoop::RunInternal() {
405 DCHECK_EQ(this, current());
406
407 StartHistogrammer();
408
michaelbai@google.com686190b2011-08-03 01:11:16 +0900409#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
erg@google.com67a25432011-01-08 05:23:43 +0900410 if (state_->dispatcher && type() == TYPE_UI) {
411 static_cast<base::MessagePumpForUI*>(pump_.get())->
412 RunWithDispatcher(this, state_->dispatcher);
413 return;
414 }
415#endif
416
417 pump_->Run(this);
418}
419
420bool MessageLoop::ProcessNextDelayedNonNestableTask() {
421 if (state_->run_depth != 1)
422 return false;
423
424 if (deferred_non_nestable_work_queue_.empty())
425 return false;
426
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900427 PendingTask pending_task = deferred_non_nestable_work_queue_.front();
erg@google.com67a25432011-01-08 05:23:43 +0900428 deferred_non_nestable_work_queue_.pop();
429
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900430 RunTask(pending_task);
erg@google.com67a25432011-01-08 05:23:43 +0900431 return true;
432}
433
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900434void MessageLoop::RunTask(const PendingTask& pending_task) {
jbates@chromium.orgb84db522011-10-04 02:51:25 +0900435 UNSHIPPED_TRACE_EVENT2("task", "MessageLoop::RunTask",
436 "src_file", pending_task.posted_from.file_name(),
437 "src_func", pending_task.posted_from.function_name());
initial.commit3f4a7322008-07-27 06:49:38 +0900438 DCHECK(nestable_tasks_allowed_);
439 // Execute the task and assume the worst: It is probably not reentrant.
440 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900441
apatrick@chromium.org87164042011-05-20 07:28:25 +0900442 // Before running the task, store the program counter where it was posted
443 // and deliberately alias it to ensure it is on the stack if the task
444 // crashes. Be careful not to assume that the variable itself will have the
445 // expected value when displayed by the optimizer in an optimized build.
446 // Look at a memory dump of the stack.
jbates@chromium.orgb84db522011-10-04 02:51:25 +0900447 const void* program_counter =
448 pending_task.posted_from.program_counter();
apatrick@chromium.org87164042011-05-20 07:28:25 +0900449 base::debug::Alias(&program_counter);
450
darin@google.combe165ae2008-09-07 17:08:29 +0900451 HistogramEvent(kTaskRunEvent);
jar@chromium.org79a58c32011-10-16 08:52:45 +0900452
jar@chromium.orgb536eef2011-11-14 14:24:07 +0900453 tracked_objects::TrackedTime start_time =
jar@chromium.orgb5c974b2011-12-14 10:36:48 +0900454 tracked_objects::ThreadData::NowForStartOfRun(pending_task.birth_tally);
jar@chromium.org79a58c32011-10-16 08:52:45 +0900455
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));
jar@chromium.org4be2cb02011-11-01 07:36:21 +0900461
462 tracked_objects::ThreadData::TallyRunOnNamedThreadIfTracking(pending_task,
jar@chromium.orgb536eef2011-11-14 14:24:07 +0900463 start_time, tracked_objects::ThreadData::NowForEndOfRun());
darin@google.combe165ae2008-09-07 17:08:29 +0900464
465 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900466}
467
jar@chromium.org79a58c32011-10-16 08:52:45 +0900468bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
darin@google.combe165ae2008-09-07 17:08:29 +0900469 if (pending_task.nestable || state_->run_depth == 1) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900470 RunTask(pending_task);
darin@google.combe165ae2008-09-07 17:08:29 +0900471 // Show that we ran a task (Note: a new one might arrive as a
472 // consequence!).
473 return true;
474 }
475
476 // We couldn't run the task now because we're in a nested message loop
477 // and the task isn't nestable.
478 deferred_non_nestable_work_queue_.push(pending_task);
479 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900480}
481
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900482void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
483 // Move to the delayed work queue. Initialize the sequence number
484 // before inserting into the delayed_work_queue_. The sequence number
485 // is used to faciliate FIFO sorting when two tasks have the same
486 // delayed_run_time value.
487 PendingTask new_pending_task(pending_task);
488 new_pending_task.sequence_num = next_sequence_num_++;
489 delayed_work_queue_.push(new_pending_task);
490}
491
initial.commit3f4a7322008-07-27 06:49:38 +0900492void MessageLoop::ReloadWorkQueue() {
493 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900494 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
495 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900496 // queues get large.
497 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900498 return; // Wait till we *really* need to lock and load.
499
500 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900501 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900502 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900503 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900504 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900505 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900506 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900507 }
508}
509
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900510bool MessageLoop::DeletePendingTasks() {
511 bool did_work = !work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900512 // TODO(darin): Delete all tasks once it is safe to do so.
jeanluc@chromium.org5fcf7872011-08-18 02:41:02 +0900513 // Until it is totally safe, just do it when running Valgrind.
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900514 //
515 // See http://crbug.com/61131
516 //
jeanluc@chromium.org5fcf7872011-08-18 02:41:02 +0900517#if defined(USE_HEAPCHECKER)
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900518 should_leak_tasks_ = false;
519#else
520 if (RunningOnValgrind())
521 should_leak_tasks_ = false;
522#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900523 while (!work_queue_.empty()) {
524 PendingTask pending_task = work_queue_.front();
525 work_queue_.pop();
526 if (!pending_task.delayed_run_time.is_null()) {
527 // We want to delete delayed tasks in the same order in which they would
528 // normally be deleted in case of any funny dependencies between delayed
529 // tasks.
530 AddToDelayedWorkQueue(pending_task);
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900531 }
initial.commit3f4a7322008-07-27 06:49:38 +0900532 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900533 did_work |= !deferred_non_nestable_work_queue_.empty();
534 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900535 deferred_non_nestable_work_queue_.pop();
initial.commit3f4a7322008-07-27 06:49:38 +0900536 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900537 did_work |= !delayed_work_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900538
539 // Historically, we always delete the task regardless of valgrind status. It's
540 // not completely clear why we want to leak them in the loops above. This
541 // code is replicating legacy behavior, and should not be considered
542 // absolutely "correct" behavior. See TODO above about deleting all tasks
543 // when it's safe.
544 should_leak_tasks_ = false;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900545 while (!delayed_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900546 delayed_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900547 }
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900548 should_leak_tasks_ = true;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900549 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900550}
551
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900552TimeTicks MessageLoop::CalculateDelayedRuntime(int64 delay_ms) {
553 TimeTicks delayed_run_time;
erg@google.com67a25432011-01-08 05:23:43 +0900554 if (delay_ms > 0) {
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900555 delayed_run_time =
erg@google.com67a25432011-01-08 05:23:43 +0900556 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
557
558#if defined(OS_WIN)
559 if (high_resolution_timer_expiration_.is_null()) {
560 // Windows timers are granular to 15.6ms. If we only set high-res
561 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
562 // which as a percentage is pretty inaccurate. So enable high
563 // res timers for any timer which is within 2x of the granularity.
564 // This is a tradeoff between accuracy and power management.
565 bool needs_high_res_timers =
566 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
567 if (needs_high_res_timers) {
mbelshe@chromium.orgbee85b32011-05-16 04:20:49 +0900568 if (base::Time::ActivateHighResolutionTimer(true)) {
569 high_resolution_timer_expiration_ = TimeTicks::Now() +
570 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
571 }
erg@google.com67a25432011-01-08 05:23:43 +0900572 }
573 }
574#endif
575 } else {
576 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
577 }
578
579#if defined(OS_WIN)
580 if (!high_resolution_timer_expiration_.is_null()) {
581 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
582 base::Time::ActivateHighResolutionTimer(false);
583 high_resolution_timer_expiration_ = TimeTicks();
584 }
585 }
586#endif
587
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900588 return delayed_run_time;
589}
590
591// Possibly called on a background thread!
592void MessageLoop::AddToIncomingQueue(PendingTask* pending_task) {
erg@google.com67a25432011-01-08 05:23:43 +0900593 // Warning: Don't try to short-circuit, and handle this thread's tasks more
594 // directly, as it could starve handling of foreign threads. Put every task
595 // into this queue.
596
597 scoped_refptr<base::MessagePump> pump;
598 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900599 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900600
601 bool was_empty = incoming_queue_.empty();
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900602 incoming_queue_.push(*pending_task);
603 pending_task->task.Reset();
erg@google.com67a25432011-01-08 05:23:43 +0900604 if (!was_empty)
605 return; // Someone else should have started the sub-pump.
606
607 pump = pump_;
608 }
609 // Since the incoming_queue_ may contain a task that destroys this message
610 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
611 // We use a stack-based reference to the message pump so that we can call
612 // ScheduleWork outside of incoming_queue_lock_.
613
614 pump->ScheduleWork();
615}
616
617//------------------------------------------------------------------------------
618// Method and data for histogramming events and actions taken by each instance
619// on each thread.
620
621void MessageLoop::StartHistogrammer() {
jar@chromium.org34571142011-04-05 13:48:53 +0900622 if (enable_histogrammer_ && !message_histogram_
erg@google.com67a25432011-01-08 05:23:43 +0900623 && base::StatisticsRecorder::IsActive()) {
624 DCHECK(!thread_name_.empty());
625 message_histogram_ = base::LinearHistogram::FactoryGet(
626 "MsgLoop:" + thread_name_,
627 kLeastNonZeroMessageId, kMaxMessageId,
628 kNumberOfDistinctMessagesDisplayed,
629 message_histogram_->kHexRangePrintingFlag);
630 message_histogram_->SetRangeDescriptions(event_descriptions_);
631 }
632}
633
634void MessageLoop::HistogramEvent(int event) {
jar@chromium.org34571142011-04-05 13:48:53 +0900635 if (message_histogram_)
erg@google.com67a25432011-01-08 05:23:43 +0900636 message_histogram_->Add(event);
637}
638
darin@google.com981f3552008-08-16 12:09:05 +0900639bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900640 if (!nestable_tasks_allowed_) {
641 // Task can't be executed right now.
642 return false;
643 }
644
645 for (;;) {
646 ReloadWorkQueue();
647 if (work_queue_.empty())
648 break;
649
650 // Execute oldest task.
651 do {
652 PendingTask pending_task = work_queue_.front();
653 work_queue_.pop();
654 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900655 AddToDelayedWorkQueue(pending_task);
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900656 // If we changed the topmost task, then it is time to reschedule.
657 if (delayed_work_queue_.top().task.Equals(pending_task.task))
darin@google.combe165ae2008-09-07 17:08:29 +0900658 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
659 } else {
660 if (DeferOrRunPendingTask(pending_task))
661 return true;
662 }
663 } while (!work_queue_.empty());
664 }
665
666 // Nothing happened.
667 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900668}
669
ajwong@chromium.org94d2a582011-04-21 01:02:23 +0900670bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900671 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900672 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900673 return false;
674 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900675
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900676 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900677 // queue that are ready to run. To increase efficiency when we fall behind,
678 // we will only call Time::Now() intermittently, and then process all tasks
679 // that are ready to run before calling it again. As a result, the more we
680 // fall behind (and have a lot of ready-to-run delayed tasks), the more
681 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900682
683 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900684 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900685 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900686 if (next_run_time > recent_time_) {
687 *next_delayed_work_time = next_run_time;
688 return false;
689 }
darin@google.combe165ae2008-09-07 17:08:29 +0900690 }
darin@google.com981f3552008-08-16 12:09:05 +0900691
jar@chromium.org40355072010-10-21 15:32:33 +0900692 PendingTask pending_task = delayed_work_queue_.top();
693 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900694
jar@chromium.org40355072010-10-21 15:32:33 +0900695 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900696 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900697
darin@google.combe165ae2008-09-07 17:08:29 +0900698 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900699}
700
701bool MessageLoop::DoIdleWork() {
702 if (ProcessNextDelayedNonNestableTask())
703 return true;
704
705 if (state_->quit_received)
706 pump_->Quit();
707
708 return false;
709}
710
dcheng@chromium.org36904742011-12-30 13:32:58 +0900711void MessageLoop::DeleteSoonInternal(const tracked_objects::Location& from_here,
712 void(*deleter)(const void*),
713 const void* object) {
714 PostNonNestableTask(from_here, base::Bind(deleter, object));
715}
716
dcheng@chromium.org2116fc92011-12-30 15:46:30 +0900717void MessageLoop::ReleaseSoonInternal(
718 const tracked_objects::Location& from_here,
719 void(*releaser)(const void*),
720 const void* object) {
721 PostNonNestableTask(from_here, base::Bind(releaser, object));
722}
723
darin@google.com981f3552008-08-16 12:09:05 +0900724//------------------------------------------------------------------------------
725// MessageLoop::AutoRunState
726
727MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
728 // Make the loop reference us.
729 previous_state_ = loop_->state_;
730 if (previous_state_) {
731 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900732 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900733 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900734 }
darin@google.com981f3552008-08-16 12:09:05 +0900735 loop_->state_ = this;
736
737 // Initialize the other fields:
738 quit_received = false;
michaelbai@google.com686190b2011-08-03 01:11:16 +0900739#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
darin@google.com981f3552008-08-16 12:09:05 +0900740 dispatcher = NULL;
741#endif
742}
743
744MessageLoop::AutoRunState::~AutoRunState() {
745 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900746}
747
initial.commit3f4a7322008-07-27 06:49:38 +0900748//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900749// MessageLoopForUI
750
751#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900752void MessageLoopForUI::DidProcessMessage(const MSG& message) {
753 pump_win()->DidProcessMessage(message);
754}
darin@google.comd936b5b2008-08-26 14:53:57 +0900755#endif // defined(OS_WIN)
756
michaelbai@google.com686190b2011-08-03 01:11:16 +0900757#if defined(OS_ANDROID)
758void MessageLoopForUI::Start() {
759 // No Histogram support for UI message loop as it is managed by Java side
760 static_cast<base::MessagePumpForUI*>(pump_.get())->Start(this);
761}
762#endif
763
764#if !defined(OS_MACOSX) && !defined(OS_NACL) && !defined(OS_ANDROID)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900765void MessageLoopForUI::AddObserver(Observer* observer) {
766 pump_ui()->AddObserver(observer);
767}
768
769void MessageLoopForUI::RemoveObserver(Observer* observer) {
770 pump_ui()->RemoveObserver(observer);
771}
772
oshima@google.com08ff65e2011-10-24 16:19:51 +0900773void MessageLoopForUI::RunWithDispatcher(Dispatcher* dispatcher) {
jcampan@chromium.org05423582009-08-01 07:53:37 +0900774 AutoRunState save_state(this);
775 state_->dispatcher = dispatcher;
776 RunHandler();
777}
oshima@google.comc7bc27c2011-10-07 03:19:21 +0900778
779void MessageLoopForUI::RunAllPendingWithDispatcher(Dispatcher* dispatcher) {
780 AutoRunState save_state(this);
781 state_->dispatcher = dispatcher;
782 state_->quit_received = true; // Means run until we would otherwise block.
783 RunHandler();
784}
785
michaelbai@google.com686190b2011-08-03 01:11:16 +0900786#endif // !defined(OS_MACOSX) && !defined(OS_NACL) && !defined(OS_ANDROID)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900787
darin@google.comd936b5b2008-08-26 14:53:57 +0900788//------------------------------------------------------------------------------
789// MessageLoopForIO
790
791#if defined(OS_WIN)
792
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900793void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
794 pump_io()->RegisterIOHandler(file, handler);
795}
796
rvargas@google.com73887542008-11-08 06:52:15 +0900797bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
798 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900799}
800
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900801#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900802
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900803bool MessageLoopForIO::WatchFileDescriptor(int fd,
804 bool persistent,
805 Mode mode,
806 FileDescriptorWatcher *controller,
807 Watcher *delegate) {
808 return pump_libevent()->WatchFileDescriptor(
809 fd,
810 persistent,
811 static_cast<base::MessagePumpLibevent::Mode>(mode),
812 controller,
813 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900814}
815
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900816#endif