blob: 1154c3e91476160e7f34e643c2e17f7cc8e8c889 [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
ajwong@chromium.org440e0762011-02-19 09:32:44 +09007#if defined(OS_POSIX) && !defined(OS_MACOSX)
8#include <gdk/gdk.h>
9#include <gdk/gdkx.h>
10#endif
11
darin@google.com981f3552008-08-16 12:09:05 +090012#include <algorithm>
13
mmentovai@google.comfa5f9932008-08-22 07:26:06 +090014#include "base/compiler_specific.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090015#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090016#include "base/logging.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"
initial.commit3f4a7322008-07-27 06:49:38 +090021
mark@chromium.org059d0492008-09-24 06:08:28 +090022#if defined(OS_MACOSX)
23#include "base/message_pump_mac.h"
24#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090025#if defined(OS_POSIX)
26#include "base/message_pump_libevent.h"
27#endif
evan@chromium.org875bb6e2009-12-29 09:32:52 +090028#if defined(OS_POSIX) && !defined(OS_MACOSX)
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
84} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090085
86//------------------------------------------------------------------------------
87
darin@google.com981f3552008-08-16 12:09:05 +090088#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090089
initial.commit3f4a7322008-07-27 06:49:38 +090090// Upon a SEH exception in this thread, it restores the original unhandled
91// exception filter.
92static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
93 ::SetUnhandledExceptionFilter(old_filter);
94 return EXCEPTION_CONTINUE_SEARCH;
95}
96
97// Retrieves a pointer to the current unhandled exception filter. There
98// is no standalone getter method.
99static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
100 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
101 top_filter = ::SetUnhandledExceptionFilter(0);
102 ::SetUnhandledExceptionFilter(top_filter);
103 return top_filter;
104}
105
darin@google.com981f3552008-08-16 12:09:05 +0900106#endif // defined(OS_WIN)
107
initial.commit3f4a7322008-07-27 06:49:38 +0900108//------------------------------------------------------------------------------
109
erg@chromium.org493f5f62010-07-16 06:03:54 +0900110MessageLoop::TaskObserver::TaskObserver() {
111}
112
113MessageLoop::TaskObserver::~TaskObserver() {
114}
115
116MessageLoop::DestructionObserver::~DestructionObserver() {
117}
118
119//------------------------------------------------------------------------------
120
darin@google.comd936b5b2008-08-26 14:53:57 +0900121MessageLoop::MessageLoop(Type type)
122 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900123 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900124 exception_restoration_(false),
jar@chromium.org34571142011-04-05 13:48:53 +0900125 message_histogram_(NULL),
darin@google.combe165ae2008-09-07 17:08:29 +0900126 state_(NULL),
ananta@chromium.orgc542fec2011-03-24 12:40:28 +0900127#ifdef OS_WIN
128 os_modal_loop_(false),
129#endif // OS_WIN
darin@google.combe165ae2008-09-07 17:08:29 +0900130 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900131 DCHECK(!current()) << "should only have one message loop per thread";
132 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900133
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900134// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900135#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900136#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
137#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
138#elif defined(OS_MACOSX)
139#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
140#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900141#elif defined(TOUCH_UI)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900142#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900143#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900144#elif defined(OS_NACL)
145// Currently NaCl doesn't have a UI or an IO MessageLoop.
146// TODO(abarth): Figure out if we need these.
147#define MESSAGE_PUMP_UI NULL
148#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900149#elif defined(OS_POSIX) // POSIX but not MACOSX.
150#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
151#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900152#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900153#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900154#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900155
156 if (type_ == TYPE_UI) {
157 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900158 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900159 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900160 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900161 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900162 pump_ = new base::MessagePumpDefault();
163 }
initial.commit3f4a7322008-07-27 06:49:38 +0900164}
165
166MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900167 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900168
darin@google.com0e500502008-09-09 14:55:35 +0900169 DCHECK(!state_);
170
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900171 // Clean up any unprocessed tasks, but take care: deleting a task could
172 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
173 // limit on the number of times we will allow a deleted task to generate more
174 // tasks. Normally, we should only pass through this loop once or twice. If
175 // we end up hitting the loop limit, then it is probably due to one task that
176 // is being stubborn. Inspect the queues to see who is left.
177 bool did_work;
178 for (int i = 0; i < 100; ++i) {
179 DeletePendingTasks();
180 ReloadWorkQueue();
181 // If we end up with empty queues, then break out of the loop.
182 did_work = DeletePendingTasks();
183 if (!did_work)
184 break;
darin@google.com0e500502008-09-09 14:55:35 +0900185 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900186 DCHECK(!did_work);
187
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900188 // Let interested parties have one last shot at accessing this.
189 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
190 WillDestroyCurrentMessageLoop());
191
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900192 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900193 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900194}
195
erg@google.com67a25432011-01-08 05:23:43 +0900196// static
197MessageLoop* MessageLoop::current() {
198 // TODO(darin): sadly, we cannot enable this yet since people call us even
199 // when they have no intention of using us.
200 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
201 return lazy_tls_ptr.Pointer()->Get();
202}
203
204// static
205void MessageLoop::EnableHistogrammer(bool enable) {
206 enable_histogrammer_ = enable;
207}
208
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900209void MessageLoop::AddDestructionObserver(
210 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900211 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900212 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900213}
214
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900215void MessageLoop::RemoveDestructionObserver(
216 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900217 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900218 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900219}
220
darin@google.combe165ae2008-09-07 17:08:29 +0900221void MessageLoop::PostTask(
222 const tracked_objects::Location& from_here, Task* task) {
223 PostTask_Helper(from_here, task, 0, true);
224}
225
226void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900227 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900228 PostTask_Helper(from_here, task, delay_ms, true);
229}
230
231void MessageLoop::PostNonNestableTask(
232 const tracked_objects::Location& from_here, Task* task) {
233 PostTask_Helper(from_here, task, 0, false);
234}
235
236void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900237 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900238 PostTask_Helper(from_here, task, delay_ms, false);
239}
240
erg@google.com67a25432011-01-08 05:23:43 +0900241void MessageLoop::Run() {
242 AutoRunState save_state(this);
243 RunHandler();
244}
darin@google.com0795f572008-08-30 09:22:48 +0900245
erg@google.com67a25432011-01-08 05:23:43 +0900246void MessageLoop::RunAllPending() {
247 AutoRunState save_state(this);
248 state_->quit_received = true; // Means run until we would otherwise block.
249 RunHandler();
250}
darin@google.com0795f572008-08-30 09:22:48 +0900251
erg@google.com67a25432011-01-08 05:23:43 +0900252void MessageLoop::Quit() {
253 DCHECK_EQ(this, current());
254 if (state_) {
255 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900256 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900257 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900258 }
erg@google.com67a25432011-01-08 05:23:43 +0900259}
darin@google.com0795f572008-08-30 09:22:48 +0900260
erg@google.com67a25432011-01-08 05:23:43 +0900261void MessageLoop::QuitNow() {
262 DCHECK_EQ(this, current());
263 if (state_) {
264 pump_->Quit();
265 } else {
266 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900267 }
initial.commit3f4a7322008-07-27 06:49:38 +0900268}
269
270void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900271 if (nestable_tasks_allowed_ != allowed) {
272 nestable_tasks_allowed_ = allowed;
273 if (!nestable_tasks_allowed_)
274 return;
275 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900276 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900277 }
initial.commit3f4a7322008-07-27 06:49:38 +0900278}
279
280bool MessageLoop::NestableTasksAllowed() const {
281 return nestable_tasks_allowed_;
282}
283
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900284bool MessageLoop::IsNested() {
285 return state_->run_depth > 1;
286}
287
erg@google.com67a25432011-01-08 05:23:43 +0900288void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
289 DCHECK_EQ(this, current());
290 task_observers_.AddObserver(task_observer);
291}
292
293void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
294 DCHECK_EQ(this, current());
295 task_observers_.RemoveObserver(task_observer);
296}
297
willchan@chromium.org3a397672011-01-26 09:53:48 +0900298void MessageLoop::AssertIdle() const {
299 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
300 base::AutoLock lock(incoming_queue_lock_);
301 DCHECK(incoming_queue_.empty());
302}
303
initial.commit3f4a7322008-07-27 06:49:38 +0900304//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900305
erg@google.com67a25432011-01-08 05:23:43 +0900306// Runs the loop in two different SEH modes:
307// enable_SEH_restoration_ = false : any unhandled exception goes to the last
308// one that calls SetUnhandledExceptionFilter().
309// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
310// that was existed before the loop was run.
311void MessageLoop::RunHandler() {
312#if defined(OS_WIN)
313 if (exception_restoration_) {
314 RunInternalInSEHFrame();
315 return;
316 }
317#endif
318
319 RunInternal();
320}
321
322#if defined(OS_WIN)
323__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
324 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
325 __try {
326 RunInternal();
327 } __except(SEHFilter(current_filter)) {
328 }
329 return;
330}
331#endif
332
333void MessageLoop::RunInternal() {
334 DCHECK_EQ(this, current());
335
336 StartHistogrammer();
337
338#if !defined(OS_MACOSX)
339 if (state_->dispatcher && type() == TYPE_UI) {
340 static_cast<base::MessagePumpForUI*>(pump_.get())->
341 RunWithDispatcher(this, state_->dispatcher);
342 return;
343 }
344#endif
345
346 pump_->Run(this);
347}
348
349bool MessageLoop::ProcessNextDelayedNonNestableTask() {
350 if (state_->run_depth != 1)
351 return false;
352
353 if (deferred_non_nestable_work_queue_.empty())
354 return false;
355
356 Task* task = deferred_non_nestable_work_queue_.front().task;
357 deferred_non_nestable_work_queue_.pop();
358
359 RunTask(task);
360 return true;
361}
362
initial.commit3f4a7322008-07-27 06:49:38 +0900363void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900364 DCHECK(nestable_tasks_allowed_);
365 // Execute the task and assume the worst: It is probably not reentrant.
366 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900367
368 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900369 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900370 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900371 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900372 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900373 delete task;
374
375 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900376}
377
darin@google.combe165ae2008-09-07 17:08:29 +0900378bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
379 if (pending_task.nestable || state_->run_depth == 1) {
380 RunTask(pending_task.task);
381 // Show that we ran a task (Note: a new one might arrive as a
382 // consequence!).
383 return true;
384 }
385
386 // We couldn't run the task now because we're in a nested message loop
387 // and the task isn't nestable.
388 deferred_non_nestable_work_queue_.push(pending_task);
389 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900390}
391
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900392void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
393 // Move to the delayed work queue. Initialize the sequence number
394 // before inserting into the delayed_work_queue_. The sequence number
395 // is used to faciliate FIFO sorting when two tasks have the same
396 // delayed_run_time value.
397 PendingTask new_pending_task(pending_task);
398 new_pending_task.sequence_num = next_sequence_num_++;
399 delayed_work_queue_.push(new_pending_task);
400}
401
initial.commit3f4a7322008-07-27 06:49:38 +0900402void MessageLoop::ReloadWorkQueue() {
403 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900404 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
405 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900406 // queues get large.
407 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900408 return; // Wait till we *really* need to lock and load.
409
410 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900411 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900412 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900413 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900414 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900415 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900416 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900417 }
418}
419
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900420bool MessageLoop::DeletePendingTasks() {
421 bool did_work = !work_queue_.empty();
422 while (!work_queue_.empty()) {
423 PendingTask pending_task = work_queue_.front();
424 work_queue_.pop();
425 if (!pending_task.delayed_run_time.is_null()) {
426 // We want to delete delayed tasks in the same order in which they would
427 // normally be deleted in case of any funny dependencies between delayed
428 // tasks.
429 AddToDelayedWorkQueue(pending_task);
430 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900431 // TODO(darin): Delete all tasks once it is safe to do so.
432 // Until it is totally safe, just do it when running Purify or
433 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900434#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900435 delete pending_task.task;
timurrrr@chromium.org490200b2011-01-05 04:06:51 +0900436#else
437 if (RunningOnValgrind())
akalin@chromium.org839060b2010-08-03 12:06:21 +0900438 delete pending_task.task;
439#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900440 }
initial.commit3f4a7322008-07-27 06:49:38 +0900441 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900442 did_work |= !deferred_non_nestable_work_queue_.empty();
443 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900444 // TODO(darin): Delete all tasks once it is safe to do so.
445 // Until it is totaly safe, only delete them under Purify and Valgrind.
446 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900447#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900448 task = deferred_non_nestable_work_queue_.front().task;
timurrrr@chromium.org490200b2011-01-05 04:06:51 +0900449#else
450 if (RunningOnValgrind())
akalin@chromium.org839060b2010-08-03 12:06:21 +0900451 task = deferred_non_nestable_work_queue_.front().task;
452#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900453 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900454 if (task)
455 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900456 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900457 did_work |= !delayed_work_queue_.empty();
458 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900459 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900460 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900461 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900462 }
463 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900464}
465
erg@google.com67a25432011-01-08 05:23:43 +0900466// Possibly called on a background thread!
467void MessageLoop::PostTask_Helper(
468 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
469 bool nestable) {
470 task->SetBirthPlace(from_here);
471
472 PendingTask pending_task(task, nestable);
473
474 if (delay_ms > 0) {
475 pending_task.delayed_run_time =
476 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
477
478#if defined(OS_WIN)
479 if (high_resolution_timer_expiration_.is_null()) {
480 // Windows timers are granular to 15.6ms. If we only set high-res
481 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
482 // which as a percentage is pretty inaccurate. So enable high
483 // res timers for any timer which is within 2x of the granularity.
484 // This is a tradeoff between accuracy and power management.
485 bool needs_high_res_timers =
486 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
487 if (needs_high_res_timers) {
488 base::Time::ActivateHighResolutionTimer(true);
489 high_resolution_timer_expiration_ = TimeTicks::Now() +
490 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
491 }
492 }
493#endif
494 } else {
495 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
496 }
497
498#if defined(OS_WIN)
499 if (!high_resolution_timer_expiration_.is_null()) {
500 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
501 base::Time::ActivateHighResolutionTimer(false);
502 high_resolution_timer_expiration_ = TimeTicks();
503 }
504 }
505#endif
506
507 // Warning: Don't try to short-circuit, and handle this thread's tasks more
508 // directly, as it could starve handling of foreign threads. Put every task
509 // into this queue.
510
511 scoped_refptr<base::MessagePump> pump;
512 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900513 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900514
515 bool was_empty = incoming_queue_.empty();
516 incoming_queue_.push(pending_task);
517 if (!was_empty)
518 return; // Someone else should have started the sub-pump.
519
520 pump = pump_;
521 }
522 // Since the incoming_queue_ may contain a task that destroys this message
523 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
524 // We use a stack-based reference to the message pump so that we can call
525 // ScheduleWork outside of incoming_queue_lock_.
526
527 pump->ScheduleWork();
528}
529
530//------------------------------------------------------------------------------
531// Method and data for histogramming events and actions taken by each instance
532// on each thread.
533
534void MessageLoop::StartHistogrammer() {
jar@chromium.org34571142011-04-05 13:48:53 +0900535 if (enable_histogrammer_ && !message_histogram_
erg@google.com67a25432011-01-08 05:23:43 +0900536 && base::StatisticsRecorder::IsActive()) {
537 DCHECK(!thread_name_.empty());
538 message_histogram_ = base::LinearHistogram::FactoryGet(
539 "MsgLoop:" + thread_name_,
540 kLeastNonZeroMessageId, kMaxMessageId,
541 kNumberOfDistinctMessagesDisplayed,
542 message_histogram_->kHexRangePrintingFlag);
543 message_histogram_->SetRangeDescriptions(event_descriptions_);
544 }
545}
546
547void MessageLoop::HistogramEvent(int event) {
jar@chromium.org34571142011-04-05 13:48:53 +0900548 if (message_histogram_)
erg@google.com67a25432011-01-08 05:23:43 +0900549 message_histogram_->Add(event);
550}
551
darin@google.com981f3552008-08-16 12:09:05 +0900552bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900553 if (!nestable_tasks_allowed_) {
554 // Task can't be executed right now.
555 return false;
556 }
557
558 for (;;) {
559 ReloadWorkQueue();
560 if (work_queue_.empty())
561 break;
562
563 // Execute oldest task.
564 do {
565 PendingTask pending_task = work_queue_.front();
566 work_queue_.pop();
567 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900568 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900569 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900570 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900571 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
572 } else {
573 if (DeferOrRunPendingTask(pending_task))
574 return true;
575 }
576 } while (!work_queue_.empty());
577 }
578
579 // Nothing happened.
580 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900581}
582
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900583bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900584 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900585 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900586 return false;
587 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900588
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900589 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900590 // queue that are ready to run. To increase efficiency when we fall behind,
591 // we will only call Time::Now() intermittently, and then process all tasks
592 // that are ready to run before calling it again. As a result, the more we
593 // fall behind (and have a lot of ready-to-run delayed tasks), the more
594 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900595
596 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900597 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900598 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900599 if (next_run_time > recent_time_) {
600 *next_delayed_work_time = next_run_time;
601 return false;
602 }
darin@google.combe165ae2008-09-07 17:08:29 +0900603 }
darin@google.com981f3552008-08-16 12:09:05 +0900604
jar@chromium.org40355072010-10-21 15:32:33 +0900605 PendingTask pending_task = delayed_work_queue_.top();
606 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900607
jar@chromium.org40355072010-10-21 15:32:33 +0900608 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900609 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900610
darin@google.combe165ae2008-09-07 17:08:29 +0900611 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900612}
613
614bool MessageLoop::DoIdleWork() {
615 if (ProcessNextDelayedNonNestableTask())
616 return true;
617
618 if (state_->quit_received)
619 pump_->Quit();
620
621 return false;
622}
623
624//------------------------------------------------------------------------------
625// MessageLoop::AutoRunState
626
627MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
628 // Make the loop reference us.
629 previous_state_ = loop_->state_;
630 if (previous_state_) {
631 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900632 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900633 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900634 }
darin@google.com981f3552008-08-16 12:09:05 +0900635 loop_->state_ = this;
636
637 // Initialize the other fields:
638 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900639#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900640 dispatcher = NULL;
641#endif
642}
643
644MessageLoop::AutoRunState::~AutoRunState() {
645 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900646}
647
initial.commit3f4a7322008-07-27 06:49:38 +0900648//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900649// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900650
darin@google.combe165ae2008-09-07 17:08:29 +0900651bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
652 // Since the top of a priority queue is defined as the "greatest" element, we
653 // need to invert the comparison here. We want the smaller time to be at the
654 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900655
darin@google.combe165ae2008-09-07 17:08:29 +0900656 if (delayed_run_time < other.delayed_run_time)
657 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900658
darin@google.combe165ae2008-09-07 17:08:29 +0900659 if (delayed_run_time > other.delayed_run_time)
660 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900661
darin@google.combe165ae2008-09-07 17:08:29 +0900662 // If the times happen to match, then we use the sequence number to decide.
663 // Compare the difference to support integer roll-over.
664 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900665}
666
667//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900668// MessageLoopForUI
669
670#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900671void MessageLoopForUI::DidProcessMessage(const MSG& message) {
672 pump_win()->DidProcessMessage(message);
673}
darin@google.comd936b5b2008-08-26 14:53:57 +0900674#endif // defined(OS_WIN)
675
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900676#if defined(USE_X11)
677Display* MessageLoopForUI::GetDisplay() {
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900678 return gdk_x11_get_default_xdisplay();
679}
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900680#endif // defined(USE_X11)
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900681
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900682#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900683void MessageLoopForUI::AddObserver(Observer* observer) {
684 pump_ui()->AddObserver(observer);
685}
686
687void MessageLoopForUI::RemoveObserver(Observer* observer) {
688 pump_ui()->RemoveObserver(observer);
689}
690
691void MessageLoopForUI::Run(Dispatcher* dispatcher) {
692 AutoRunState save_state(this);
693 state_->dispatcher = dispatcher;
694 RunHandler();
695}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900696#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900697
darin@google.comd936b5b2008-08-26 14:53:57 +0900698//------------------------------------------------------------------------------
699// MessageLoopForIO
700
701#if defined(OS_WIN)
702
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900703void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
704 pump_io()->RegisterIOHandler(file, handler);
705}
706
rvargas@google.com73887542008-11-08 06:52:15 +0900707bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
708 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900709}
710
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900711#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900712
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900713bool MessageLoopForIO::WatchFileDescriptor(int fd,
714 bool persistent,
715 Mode mode,
716 FileDescriptorWatcher *controller,
717 Watcher *delegate) {
718 return pump_libevent()->WatchFileDescriptor(
719 fd,
720 persistent,
721 static_cast<base::MessagePumpLibevent::Mode>(mode),
722 controller,
723 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900724}
725
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900726#endif