1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/message_loop/message_pump_win.h"
9 #include "base/debug/trace_event.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process/memory.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/win/wrapped_window_proc.h"
20 enum MessageLoopProblems
{
22 COMPLETION_POST_ERROR
,
24 MESSAGE_LOOP_PROBLEM_MAX
,
29 static const wchar_t kWndClassFormat
[] = L
"Chrome_MessagePumpWindow_%p";
31 // Message sent to get an additional time slice for pumping (processing) another
32 // task (a series of such messages creates a continuous task pump).
33 static const int kMsgHaveWork
= WM_USER
+ 1;
35 //-----------------------------------------------------------------------------
36 // MessagePumpWin public:
38 void MessagePumpWin::AddObserver(MessagePumpObserver
* observer
) {
39 observers_
.AddObserver(observer
);
42 void MessagePumpWin::RemoveObserver(MessagePumpObserver
* observer
) {
43 observers_
.RemoveObserver(observer
);
46 void MessagePumpWin::WillProcessMessage(const MSG
& msg
) {
47 FOR_EACH_OBSERVER(MessagePumpObserver
, observers_
, WillProcessEvent(msg
));
50 void MessagePumpWin::DidProcessMessage(const MSG
& msg
) {
51 FOR_EACH_OBSERVER(MessagePumpObserver
, observers_
, DidProcessEvent(msg
));
54 void MessagePumpWin::RunWithDispatcher(
55 Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
) {
57 s
.delegate
= delegate
;
58 s
.dispatcher
= dispatcher
;
59 s
.should_quit
= false;
60 s
.run_depth
= state_
? state_
->run_depth
+ 1 : 1;
62 RunState
* previous_state
= state_
;
67 state_
= previous_state
;
70 void MessagePumpWin::Quit() {
72 state_
->should_quit
= true;
75 //-----------------------------------------------------------------------------
76 // MessagePumpWin protected:
78 int MessagePumpWin::GetCurrentDelay() const {
79 if (delayed_work_time_
.is_null())
82 // Be careful here. TimeDelta has a precision of microseconds, but we want a
83 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
84 // 6? It should be 6 to avoid executing delayed work too early.
86 ceil((delayed_work_time_
- TimeTicks::Now()).InMillisecondsF());
88 // If this value is negative, then we need to run delayed work soon.
89 int delay
= static_cast<int>(timeout
);
96 //-----------------------------------------------------------------------------
97 // MessagePumpForUI public:
99 MessagePumpForUI::MessagePumpForUI()
104 MessagePumpForUI::~MessagePumpForUI() {
105 DestroyWindow(message_hwnd_
);
106 UnregisterClass(MAKEINTATOM(atom_
),
107 GetModuleFromAddress(&WndProcThunk
));
110 void MessagePumpForUI::ScheduleWork() {
111 if (InterlockedExchange(&have_work_
, 1))
112 return; // Someone else continued the pumping.
114 // Make sure the MessagePump does some work for us.
115 BOOL ret
= PostMessage(message_hwnd_
, kMsgHaveWork
,
116 reinterpret_cast<WPARAM
>(this), 0);
118 return; // There was room in the Window Message queue.
120 // We have failed to insert a have-work message, so there is a chance that we
121 // will starve tasks/timers while sitting in a nested message loop. Nested
122 // loops only look at Windows Message queues, and don't look at *our* task
123 // queues, etc., so we might not get a time slice in such. :-(
124 // We could abort here, but the fear is that this failure mode is plausibly
125 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
126 // recovery. Nested loops are pretty transient (we think), so this will
127 // probably be recoverable.
128 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't really insert.
129 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR
,
130 MESSAGE_LOOP_PROBLEM_MAX
);
133 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
135 // We would *like* to provide high resolution timers. Windows timers using
136 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
137 // mechanism because the application can enter modal windows loops where it
138 // is not running our MessageLoop; the only way to have our timers fire in
139 // these cases is to post messages there.
141 // To provide sub-10ms timers, we process timers directly from our run loop.
142 // For the common case, timers will be processed there as the run loop does
143 // its normal work. However, we *also* set the system timer so that WM_TIMER
144 // events fire. This mops up the case of timers not being able to work in
145 // modal message loops. It is possible for the SetTimer to pop and have no
146 // pending timers, because they could have already been processed by the
149 // We use a single SetTimer corresponding to the timer that will expire
150 // soonest. As new timers are created and destroyed, we update SetTimer.
151 // Getting a spurrious SetTimer event firing is benign, as we'll just be
152 // processing an empty timer queue.
154 delayed_work_time_
= delayed_work_time
;
156 int delay_msec
= GetCurrentDelay();
157 DCHECK_GE(delay_msec
, 0);
158 if (delay_msec
< USER_TIMER_MINIMUM
)
159 delay_msec
= USER_TIMER_MINIMUM
;
161 // Create a WM_TIMER event that will wake us up to check for any pending
162 // timers (in case we are running within a nested, external sub-pump).
163 BOOL ret
= SetTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this),
167 // If we can't set timers, we are in big trouble... but cross our fingers for
169 // TODO(jar): If we don't see this error, use a CHECK() here instead.
170 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR
,
171 MESSAGE_LOOP_PROBLEM_MAX
);
174 //-----------------------------------------------------------------------------
175 // MessagePumpForUI private:
178 LRESULT CALLBACK
MessagePumpForUI::WndProcThunk(
179 HWND hwnd
, UINT message
, WPARAM wparam
, LPARAM lparam
) {
182 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleWorkMessage();
185 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleTimerMessage();
188 return DefWindowProc(hwnd
, message
, wparam
, lparam
);
191 void MessagePumpForUI::DoRunLoop() {
192 // IF this was just a simple PeekMessage() loop (servicing all possible work
193 // queues), then Windows would try to achieve the following order according
194 // to MSDN documentation about PeekMessage with no filter):
197 // * Sent messages (again)
198 // * WM_PAINT messages
199 // * WM_TIMER messages
201 // Summary: none of the above classes is starved, and sent messages has twice
202 // the chance of being processed (i.e., reduced service time).
205 // If we do any work, we may create more messages etc., and more work may
206 // possibly be waiting in another task group. When we (for example)
207 // ProcessNextWindowsMessage(), there is a good chance there are still more
208 // messages waiting. On the other hand, when any of these methods return
209 // having done no work, then it is pretty unlikely that calling them again
210 // quickly will find any work to do. Finally, if they all say they had no
211 // work, then it is a good time to consider sleeping (waiting) for more
214 bool more_work_is_plausible
= ProcessNextWindowsMessage();
215 if (state_
->should_quit
)
218 more_work_is_plausible
|= state_
->delegate
->DoWork();
219 if (state_
->should_quit
)
222 more_work_is_plausible
|=
223 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
224 // If we did not process any delayed work, then we can assume that our
225 // existing WM_TIMER if any will fire when delayed work should run. We
226 // don't want to disturb that timer if it is already in flight. However,
227 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
228 if (more_work_is_plausible
&& delayed_work_time_
.is_null())
229 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
230 if (state_
->should_quit
)
233 if (more_work_is_plausible
)
236 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
237 if (state_
->should_quit
)
240 if (more_work_is_plausible
)
243 WaitForWork(); // Wait (sleep) until we have work to do again.
247 void MessagePumpForUI::InitMessageWnd() {
248 // Generate a unique window class name.
249 string16 class_name
= StringPrintf(kWndClassFormat
, this);
251 HINSTANCE instance
= GetModuleFromAddress(&WndProcThunk
);
253 wc
.cbSize
= sizeof(wc
);
254 wc
.lpfnWndProc
= base::win::WrappedWindowProc
<WndProcThunk
>;
255 wc
.hInstance
= instance
;
256 wc
.lpszClassName
= class_name
.c_str();
257 atom_
= RegisterClassEx(&wc
);
260 message_hwnd_
= CreateWindow(MAKEINTATOM(atom_
), 0, 0, 0, 0, 0, 0,
261 HWND_MESSAGE
, 0, instance
, 0);
262 DCHECK(message_hwnd_
);
265 void MessagePumpForUI::WaitForWork() {
266 // Wait until a message is available, up to the time needed by the timer
267 // manager to fire the next set of timers.
268 int delay
= GetCurrentDelay();
269 if (delay
< 0) // Negative value means no timers waiting.
273 result
= MsgWaitForMultipleObjectsEx(0, NULL
, delay
, QS_ALLINPUT
,
274 MWMO_INPUTAVAILABLE
);
276 if (WAIT_OBJECT_0
== result
) {
277 // A WM_* message is available.
278 // If a parent child relationship exists between windows across threads
279 // then their thread inputs are implicitly attached.
280 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
281 // that messages are ready for processing (Specifically, mouse messages
282 // intended for the child window may appear if the child window has
284 // The subsequent PeekMessages call may fail to return any messages thus
285 // causing us to enter a tight loop at times.
286 // The WaitMessage call below is a workaround to give the child window
287 // some time to process its input messages.
289 DWORD queue_status
= GetQueueStatus(QS_MOUSE
);
290 if (HIWORD(queue_status
) & QS_MOUSE
&&
291 !PeekMessage(&msg
, NULL
, WM_MOUSEFIRST
, WM_MOUSELAST
, PM_NOREMOVE
)) {
297 DCHECK_NE(WAIT_FAILED
, result
) << GetLastError();
300 void MessagePumpForUI::HandleWorkMessage() {
301 // If we are being called outside of the context of Run, then don't try to do
302 // any work. This could correspond to a MessageBox call or something of that
305 // Since we handled a kMsgHaveWork message, we must still update this flag.
306 InterlockedExchange(&have_work_
, 0);
310 // Let whatever would have run had we not been putting messages in the queue
311 // run now. This is an attempt to make our dummy message not starve other
312 // messages that may be in the Windows message queue.
313 ProcessPumpReplacementMessage();
315 // Now give the delegate a chance to do some work. He'll let us know if he
316 // needs to do more work.
317 if (state_
->delegate
->DoWork())
321 void MessagePumpForUI::HandleTimerMessage() {
322 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
324 // If we are being called outside of the context of Run, then don't do
325 // anything. This could correspond to a MessageBox call or something of
330 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
331 if (!delayed_work_time_
.is_null()) {
332 // A bit gratuitous to set delayed_work_time_ again, but oh well.
333 ScheduleDelayedWork(delayed_work_time_
);
337 bool MessagePumpForUI::ProcessNextWindowsMessage() {
338 // If there are sent messages in the queue then PeekMessage internally
339 // dispatches the message and returns false. We return true in this
340 // case to ensure that the message loop peeks again instead of calling
341 // MsgWaitForMultipleObjectsEx again.
342 bool sent_messages_in_queue
= false;
343 DWORD queue_status
= GetQueueStatus(QS_SENDMESSAGE
);
344 if (HIWORD(queue_status
) & QS_SENDMESSAGE
)
345 sent_messages_in_queue
= true;
348 if (PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
)
349 return ProcessMessageHelper(msg
);
351 return sent_messages_in_queue
;
354 bool MessagePumpForUI::ProcessMessageHelper(const MSG
& msg
) {
355 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
356 "message", msg
.message
);
357 if (WM_QUIT
== msg
.message
) {
358 // Repost the QUIT message so that it will be retrieved by the primary
359 // GetMessage() loop.
360 state_
->should_quit
= true;
361 PostQuitMessage(static_cast<int>(msg
.wParam
));
365 // While running our main message pump, we discard kMsgHaveWork messages.
366 if (msg
.message
== kMsgHaveWork
&& msg
.hwnd
== message_hwnd_
)
367 return ProcessPumpReplacementMessage();
369 if (CallMsgFilter(const_cast<MSG
*>(&msg
), kMessageFilterCode
))
372 WillProcessMessage(msg
);
374 uint32_t action
= MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
;
375 if (state_
->dispatcher
)
376 action
= state_
->dispatcher
->Dispatch(msg
);
377 if (action
& MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP
)
378 state_
->should_quit
= true;
379 if (action
& MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
) {
380 TranslateMessage(&msg
);
381 DispatchMessage(&msg
);
384 DidProcessMessage(msg
);
388 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
389 // When we encounter a kMsgHaveWork message, this method is called to peek
390 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
391 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
392 // a continuous stream of such messages are posted. This method carefully
393 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
394 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
395 // possibly be posted), and finally dispatches that peeked replacement. Note
396 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
398 bool have_message
= false;
400 // We should not process all window messages if we are in the context of an
401 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
402 // This is to ensure that these messages are peeked out by the OS modal loop.
403 if (MessageLoop::current()->os_modal_loop()) {
404 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
405 have_message
= PeekMessage(&msg
, NULL
, WM_PAINT
, WM_PAINT
, PM_REMOVE
) ||
406 PeekMessage(&msg
, NULL
, WM_TIMER
, WM_TIMER
, PM_REMOVE
);
408 have_message
= PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
;
411 DCHECK(!have_message
|| kMsgHaveWork
!= msg
.message
||
412 msg
.hwnd
!= message_hwnd_
);
414 // Since we discarded a kMsgHaveWork message, we must update the flag.
415 int old_have_work
= InterlockedExchange(&have_work_
, 0);
416 DCHECK(old_have_work
);
418 // We don't need a special time slice if we didn't have_message to process.
422 // Guarantee we'll get another time slice in the case where we go into native
423 // windows code. This ScheduleWork() may hurt performance a tiny bit when
424 // tasks appear very infrequently, but when the event queue is busy, the
425 // kMsgHaveWork events get (percentage wise) rarer and rarer.
427 return ProcessMessageHelper(msg
);
430 //-----------------------------------------------------------------------------
431 // MessagePumpForIO public:
433 MessagePumpForIO::MessagePumpForIO() {
434 port_
.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE
, NULL
, NULL
, 1));
435 DCHECK(port_
.IsValid());
438 void MessagePumpForIO::ScheduleWork() {
439 if (InterlockedExchange(&have_work_
, 1))
440 return; // Someone else continued the pumping.
442 // Make sure the MessagePump does some work for us.
443 BOOL ret
= PostQueuedCompletionStatus(port_
, 0,
444 reinterpret_cast<ULONG_PTR
>(this),
445 reinterpret_cast<OVERLAPPED
*>(this));
447 return; // Post worked perfectly.
449 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
450 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't succeed.
451 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR
,
452 MESSAGE_LOOP_PROBLEM_MAX
);
455 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
456 // We know that we can't be blocked right now since this method can only be
457 // called on the same thread as Run, so we only need to update our record of
458 // how long to sleep when we do sleep.
459 delayed_work_time_
= delayed_work_time
;
462 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle
,
463 IOHandler
* handler
) {
464 ULONG_PTR key
= HandlerToKey(handler
, true);
465 HANDLE port
= CreateIoCompletionPort(file_handle
, port_
, key
, 1);
469 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle
,
470 IOHandler
* handler
) {
471 // Job object notifications use the OVERLAPPED pointer to carry the message
472 // data. Mark the completion key correspondingly, so we will not try to
473 // convert OVERLAPPED* to IOContext*.
474 ULONG_PTR key
= HandlerToKey(handler
, false);
475 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info
;
476 info
.CompletionKey
= reinterpret_cast<void*>(key
);
477 info
.CompletionPort
= port_
;
478 return SetInformationJobObject(job_handle
,
479 JobObjectAssociateCompletionPortInformation
,
481 sizeof(info
)) != FALSE
;
484 //-----------------------------------------------------------------------------
485 // MessagePumpForIO private:
487 void MessagePumpForIO::DoRunLoop() {
489 // If we do any work, we may create more messages etc., and more work may
490 // possibly be waiting in another task group. When we (for example)
491 // WaitForIOCompletion(), there is a good chance there are still more
492 // messages waiting. On the other hand, when any of these methods return
493 // having done no work, then it is pretty unlikely that calling them
494 // again quickly will find any work to do. Finally, if they all say they
495 // had no work, then it is a good time to consider sleeping (waiting) for
498 bool more_work_is_plausible
= state_
->delegate
->DoWork();
499 if (state_
->should_quit
)
502 more_work_is_plausible
|= WaitForIOCompletion(0, NULL
);
503 if (state_
->should_quit
)
506 more_work_is_plausible
|=
507 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
508 if (state_
->should_quit
)
511 if (more_work_is_plausible
)
514 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
515 if (state_
->should_quit
)
518 if (more_work_is_plausible
)
521 WaitForWork(); // Wait (sleep) until we have work to do again.
525 // Wait until IO completes, up to the time needed by the timer manager to fire
526 // the next set of timers.
527 void MessagePumpForIO::WaitForWork() {
528 // We do not support nested IO message loops. This is to avoid messy
529 // recursion problems.
530 DCHECK_EQ(1, state_
->run_depth
) << "Cannot nest an IO message loop!";
532 int timeout
= GetCurrentDelay();
533 if (timeout
< 0) // Negative value means no timers waiting.
536 WaitForIOCompletion(timeout
, NULL
);
539 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
541 if (completed_io_
.empty() || !MatchCompletedIOItem(filter
, &item
)) {
542 // We have to ask the system for another IO completion.
543 if (!GetIOItem(timeout
, &item
))
546 if (ProcessInternalIOItem(item
))
550 // If |item.has_valid_io_context| is false then |item.context| does not point
551 // to a context structure, and so should not be dereferenced, although it may
552 // still hold valid non-pointer data.
553 if (!item
.has_valid_io_context
|| item
.context
->handler
) {
554 if (filter
&& item
.handler
!= filter
) {
555 // Save this item for later
556 completed_io_
.push_back(item
);
558 DCHECK(!item
.has_valid_io_context
||
559 (item
.context
->handler
== item
.handler
));
560 WillProcessIOEvent();
561 item
.handler
->OnIOCompleted(item
.context
, item
.bytes_transfered
,
566 // The handler must be gone by now, just cleanup the mess.
572 // Asks the OS for another IO completion result.
573 bool MessagePumpForIO::GetIOItem(DWORD timeout
, IOItem
* item
) {
574 memset(item
, 0, sizeof(*item
));
575 ULONG_PTR key
= NULL
;
576 OVERLAPPED
* overlapped
= NULL
;
577 if (!GetQueuedCompletionStatus(port_
.Get(), &item
->bytes_transfered
, &key
,
578 &overlapped
, timeout
)) {
580 return false; // Nothing in the queue.
581 item
->error
= GetLastError();
582 item
->bytes_transfered
= 0;
585 item
->handler
= KeyToHandler(key
, &item
->has_valid_io_context
);
586 item
->context
= reinterpret_cast<IOContext
*>(overlapped
);
590 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem
& item
) {
591 if (this == reinterpret_cast<MessagePumpForIO
*>(item
.context
) &&
592 this == reinterpret_cast<MessagePumpForIO
*>(item
.handler
)) {
593 // This is our internal completion.
594 DCHECK(!item
.bytes_transfered
);
595 InterlockedExchange(&have_work_
, 0);
601 // Returns a completion item that was previously received.
602 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
) {
603 DCHECK(!completed_io_
.empty());
604 for (std::list
<IOItem
>::iterator it
= completed_io_
.begin();
605 it
!= completed_io_
.end(); ++it
) {
606 if (!filter
|| it
->handler
== filter
) {
608 completed_io_
.erase(it
);
615 void MessagePumpForIO::AddIOObserver(IOObserver
*obs
) {
616 io_observers_
.AddObserver(obs
);
619 void MessagePumpForIO::RemoveIOObserver(IOObserver
*obs
) {
620 io_observers_
.RemoveObserver(obs
);
623 void MessagePumpForIO::WillProcessIOEvent() {
624 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
627 void MessagePumpForIO::DidProcessIOEvent() {
628 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
632 ULONG_PTR
MessagePumpForIO::HandlerToKey(IOHandler
* handler
,
633 bool has_valid_io_context
) {
634 ULONG_PTR key
= reinterpret_cast<ULONG_PTR
>(handler
);
636 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
637 // always cleared. We use the lowest bit to distinguish completion keys with
638 // and without the associated |IOContext|.
639 DCHECK((key
& 1) == 0);
641 // Mark the completion key as context-less.
642 if (!has_valid_io_context
)
648 MessagePumpForIO::IOHandler
* MessagePumpForIO::KeyToHandler(
650 bool* has_valid_io_context
) {
651 *has_valid_io_context
= ((key
& 1) == 0);
652 return reinterpret_cast<IOHandler
*>(key
& ~static_cast<ULONG_PTR
>(1));