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::RunWithDispatcher(
39 Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
) {
41 s
.delegate
= delegate
;
42 s
.dispatcher
= dispatcher
;
43 s
.should_quit
= false;
44 s
.run_depth
= state_
? state_
->run_depth
+ 1 : 1;
46 RunState
* previous_state
= state_
;
51 state_
= previous_state
;
54 void MessagePumpWin::Quit() {
56 state_
->should_quit
= true;
59 //-----------------------------------------------------------------------------
60 // MessagePumpWin protected:
62 int MessagePumpWin::GetCurrentDelay() const {
63 if (delayed_work_time_
.is_null())
66 // Be careful here. TimeDelta has a precision of microseconds, but we want a
67 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
68 // 6? It should be 6 to avoid executing delayed work too early.
70 ceil((delayed_work_time_
- TimeTicks::Now()).InMillisecondsF());
72 // If this value is negative, then we need to run delayed work soon.
73 int delay
= static_cast<int>(timeout
);
80 //-----------------------------------------------------------------------------
81 // MessagePumpForUI public:
83 MessagePumpForUI::MessagePumpForUI()
88 MessagePumpForUI::~MessagePumpForUI() {
89 DestroyWindow(message_hwnd_
);
90 UnregisterClass(MAKEINTATOM(atom_
),
91 GetModuleFromAddress(&WndProcThunk
));
94 void MessagePumpForUI::ScheduleWork() {
95 if (InterlockedExchange(&have_work_
, 1))
96 return; // Someone else continued the pumping.
98 // Make sure the MessagePump does some work for us.
99 BOOL ret
= PostMessage(message_hwnd_
, kMsgHaveWork
,
100 reinterpret_cast<WPARAM
>(this), 0);
102 return; // There was room in the Window Message queue.
104 // We have failed to insert a have-work message, so there is a chance that we
105 // will starve tasks/timers while sitting in a nested message loop. Nested
106 // loops only look at Windows Message queues, and don't look at *our* task
107 // queues, etc., so we might not get a time slice in such. :-(
108 // We could abort here, but the fear is that this failure mode is plausibly
109 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
110 // recovery. Nested loops are pretty transient (we think), so this will
111 // probably be recoverable.
112 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't really insert.
113 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR
,
114 MESSAGE_LOOP_PROBLEM_MAX
);
117 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
119 // We would *like* to provide high resolution timers. Windows timers using
120 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
121 // mechanism because the application can enter modal windows loops where it
122 // is not running our MessageLoop; the only way to have our timers fire in
123 // these cases is to post messages there.
125 // To provide sub-10ms timers, we process timers directly from our run loop.
126 // For the common case, timers will be processed there as the run loop does
127 // its normal work. However, we *also* set the system timer so that WM_TIMER
128 // events fire. This mops up the case of timers not being able to work in
129 // modal message loops. It is possible for the SetTimer to pop and have no
130 // pending timers, because they could have already been processed by the
133 // We use a single SetTimer corresponding to the timer that will expire
134 // soonest. As new timers are created and destroyed, we update SetTimer.
135 // Getting a spurrious SetTimer event firing is benign, as we'll just be
136 // processing an empty timer queue.
138 delayed_work_time_
= delayed_work_time
;
140 int delay_msec
= GetCurrentDelay();
141 DCHECK_GE(delay_msec
, 0);
142 if (delay_msec
< USER_TIMER_MINIMUM
)
143 delay_msec
= USER_TIMER_MINIMUM
;
145 // Create a WM_TIMER event that will wake us up to check for any pending
146 // timers (in case we are running within a nested, external sub-pump).
147 BOOL ret
= SetTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this),
151 // If we can't set timers, we are in big trouble... but cross our fingers for
153 // TODO(jar): If we don't see this error, use a CHECK() here instead.
154 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR
,
155 MESSAGE_LOOP_PROBLEM_MAX
);
158 //-----------------------------------------------------------------------------
159 // MessagePumpForUI private:
162 LRESULT CALLBACK
MessagePumpForUI::WndProcThunk(
163 HWND hwnd
, UINT message
, WPARAM wparam
, LPARAM lparam
) {
166 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleWorkMessage();
169 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleTimerMessage();
172 return DefWindowProc(hwnd
, message
, wparam
, lparam
);
175 void MessagePumpForUI::DoRunLoop() {
176 // IF this was just a simple PeekMessage() loop (servicing all possible work
177 // queues), then Windows would try to achieve the following order according
178 // to MSDN documentation about PeekMessage with no filter):
181 // * Sent messages (again)
182 // * WM_PAINT messages
183 // * WM_TIMER messages
185 // Summary: none of the above classes is starved, and sent messages has twice
186 // the chance of being processed (i.e., reduced service time).
189 // If we do any work, we may create more messages etc., and more work may
190 // possibly be waiting in another task group. When we (for example)
191 // ProcessNextWindowsMessage(), there is a good chance there are still more
192 // messages waiting. On the other hand, when any of these methods return
193 // having done no work, then it is pretty unlikely that calling them again
194 // quickly will find any work to do. Finally, if they all say they had no
195 // work, then it is a good time to consider sleeping (waiting) for more
198 bool more_work_is_plausible
= ProcessNextWindowsMessage();
199 if (state_
->should_quit
)
202 more_work_is_plausible
|= state_
->delegate
->DoWork();
203 if (state_
->should_quit
)
206 more_work_is_plausible
|=
207 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
208 // If we did not process any delayed work, then we can assume that our
209 // existing WM_TIMER if any will fire when delayed work should run. We
210 // don't want to disturb that timer if it is already in flight. However,
211 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
212 if (more_work_is_plausible
&& delayed_work_time_
.is_null())
213 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
214 if (state_
->should_quit
)
217 if (more_work_is_plausible
)
220 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
221 if (state_
->should_quit
)
224 if (more_work_is_plausible
)
227 WaitForWork(); // Wait (sleep) until we have work to do again.
231 void MessagePumpForUI::InitMessageWnd() {
232 // Generate a unique window class name.
233 string16 class_name
= StringPrintf(kWndClassFormat
, this);
235 HINSTANCE instance
= GetModuleFromAddress(&WndProcThunk
);
237 wc
.cbSize
= sizeof(wc
);
238 wc
.lpfnWndProc
= base::win::WrappedWindowProc
<WndProcThunk
>;
239 wc
.hInstance
= instance
;
240 wc
.lpszClassName
= class_name
.c_str();
241 atom_
= RegisterClassEx(&wc
);
244 message_hwnd_
= CreateWindow(MAKEINTATOM(atom_
), 0, 0, 0, 0, 0, 0,
245 HWND_MESSAGE
, 0, instance
, 0);
246 DCHECK(message_hwnd_
);
249 void MessagePumpForUI::WaitForWork() {
250 // Wait until a message is available, up to the time needed by the timer
251 // manager to fire the next set of timers.
252 int delay
= GetCurrentDelay();
253 if (delay
< 0) // Negative value means no timers waiting.
257 result
= MsgWaitForMultipleObjectsEx(0, NULL
, delay
, QS_ALLINPUT
,
258 MWMO_INPUTAVAILABLE
);
260 if (WAIT_OBJECT_0
== result
) {
261 // A WM_* message is available.
262 // If a parent child relationship exists between windows across threads
263 // then their thread inputs are implicitly attached.
264 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
265 // that messages are ready for processing (Specifically, mouse messages
266 // intended for the child window may appear if the child window has
268 // The subsequent PeekMessages call may fail to return any messages thus
269 // causing us to enter a tight loop at times.
270 // The WaitMessage call below is a workaround to give the child window
271 // some time to process its input messages.
273 DWORD queue_status
= GetQueueStatus(QS_MOUSE
);
274 if (HIWORD(queue_status
) & QS_MOUSE
&&
275 !PeekMessage(&msg
, NULL
, WM_MOUSEFIRST
, WM_MOUSELAST
, PM_NOREMOVE
)) {
281 DCHECK_NE(WAIT_FAILED
, result
) << GetLastError();
284 void MessagePumpForUI::HandleWorkMessage() {
285 // If we are being called outside of the context of Run, then don't try to do
286 // any work. This could correspond to a MessageBox call or something of that
289 // Since we handled a kMsgHaveWork message, we must still update this flag.
290 InterlockedExchange(&have_work_
, 0);
294 // Let whatever would have run had we not been putting messages in the queue
295 // run now. This is an attempt to make our dummy message not starve other
296 // messages that may be in the Windows message queue.
297 ProcessPumpReplacementMessage();
299 // Now give the delegate a chance to do some work. He'll let us know if he
300 // needs to do more work.
301 if (state_
->delegate
->DoWork())
305 void MessagePumpForUI::HandleTimerMessage() {
306 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
308 // If we are being called outside of the context of Run, then don't do
309 // anything. This could correspond to a MessageBox call or something of
314 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
315 if (!delayed_work_time_
.is_null()) {
316 // A bit gratuitous to set delayed_work_time_ again, but oh well.
317 ScheduleDelayedWork(delayed_work_time_
);
321 bool MessagePumpForUI::ProcessNextWindowsMessage() {
322 // If there are sent messages in the queue then PeekMessage internally
323 // dispatches the message and returns false. We return true in this
324 // case to ensure that the message loop peeks again instead of calling
325 // MsgWaitForMultipleObjectsEx again.
326 bool sent_messages_in_queue
= false;
327 DWORD queue_status
= GetQueueStatus(QS_SENDMESSAGE
);
328 if (HIWORD(queue_status
) & QS_SENDMESSAGE
)
329 sent_messages_in_queue
= true;
332 if (PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
)
333 return ProcessMessageHelper(msg
);
335 return sent_messages_in_queue
;
338 bool MessagePumpForUI::ProcessMessageHelper(const MSG
& msg
) {
339 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
340 "message", msg
.message
);
341 if (WM_QUIT
== msg
.message
) {
342 // Repost the QUIT message so that it will be retrieved by the primary
343 // GetMessage() loop.
344 state_
->should_quit
= true;
345 PostQuitMessage(static_cast<int>(msg
.wParam
));
349 // While running our main message pump, we discard kMsgHaveWork messages.
350 if (msg
.message
== kMsgHaveWork
&& msg
.hwnd
== message_hwnd_
)
351 return ProcessPumpReplacementMessage();
353 if (CallMsgFilter(const_cast<MSG
*>(&msg
), kMessageFilterCode
))
356 uint32_t action
= MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
;
357 if (state_
->dispatcher
)
358 action
= state_
->dispatcher
->Dispatch(msg
);
359 if (action
& MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP
)
360 state_
->should_quit
= true;
361 if (action
& MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
) {
362 TranslateMessage(&msg
);
363 DispatchMessage(&msg
);
369 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
370 // When we encounter a kMsgHaveWork message, this method is called to peek
371 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
372 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
373 // a continuous stream of such messages are posted. This method carefully
374 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
375 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
376 // possibly be posted), and finally dispatches that peeked replacement. Note
377 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
379 bool have_message
= false;
381 // We should not process all window messages if we are in the context of an
382 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
383 // This is to ensure that these messages are peeked out by the OS modal loop.
384 if (MessageLoop::current()->os_modal_loop()) {
385 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
386 have_message
= PeekMessage(&msg
, NULL
, WM_PAINT
, WM_PAINT
, PM_REMOVE
) ||
387 PeekMessage(&msg
, NULL
, WM_TIMER
, WM_TIMER
, PM_REMOVE
);
389 have_message
= PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
;
392 DCHECK(!have_message
|| kMsgHaveWork
!= msg
.message
||
393 msg
.hwnd
!= message_hwnd_
);
395 // Since we discarded a kMsgHaveWork message, we must update the flag.
396 int old_have_work
= InterlockedExchange(&have_work_
, 0);
397 DCHECK(old_have_work
);
399 // We don't need a special time slice if we didn't have_message to process.
403 // Guarantee we'll get another time slice in the case where we go into native
404 // windows code. This ScheduleWork() may hurt performance a tiny bit when
405 // tasks appear very infrequently, but when the event queue is busy, the
406 // kMsgHaveWork events get (percentage wise) rarer and rarer.
408 return ProcessMessageHelper(msg
);
411 //-----------------------------------------------------------------------------
412 // MessagePumpForIO public:
414 MessagePumpForIO::MessagePumpForIO() {
415 port_
.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE
, NULL
, NULL
, 1));
416 DCHECK(port_
.IsValid());
419 void MessagePumpForIO::ScheduleWork() {
420 if (InterlockedExchange(&have_work_
, 1))
421 return; // Someone else continued the pumping.
423 // Make sure the MessagePump does some work for us.
424 BOOL ret
= PostQueuedCompletionStatus(port_
, 0,
425 reinterpret_cast<ULONG_PTR
>(this),
426 reinterpret_cast<OVERLAPPED
*>(this));
428 return; // Post worked perfectly.
430 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
431 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't succeed.
432 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR
,
433 MESSAGE_LOOP_PROBLEM_MAX
);
436 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
437 // We know that we can't be blocked right now since this method can only be
438 // called on the same thread as Run, so we only need to update our record of
439 // how long to sleep when we do sleep.
440 delayed_work_time_
= delayed_work_time
;
443 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle
,
444 IOHandler
* handler
) {
445 ULONG_PTR key
= HandlerToKey(handler
, true);
446 HANDLE port
= CreateIoCompletionPort(file_handle
, port_
, key
, 1);
450 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle
,
451 IOHandler
* handler
) {
452 // Job object notifications use the OVERLAPPED pointer to carry the message
453 // data. Mark the completion key correspondingly, so we will not try to
454 // convert OVERLAPPED* to IOContext*.
455 ULONG_PTR key
= HandlerToKey(handler
, false);
456 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info
;
457 info
.CompletionKey
= reinterpret_cast<void*>(key
);
458 info
.CompletionPort
= port_
;
459 return SetInformationJobObject(job_handle
,
460 JobObjectAssociateCompletionPortInformation
,
462 sizeof(info
)) != FALSE
;
465 //-----------------------------------------------------------------------------
466 // MessagePumpForIO private:
468 void MessagePumpForIO::DoRunLoop() {
470 // If we do any work, we may create more messages etc., and more work may
471 // possibly be waiting in another task group. When we (for example)
472 // WaitForIOCompletion(), there is a good chance there are still more
473 // messages waiting. On the other hand, when any of these methods return
474 // having done no work, then it is pretty unlikely that calling them
475 // again quickly will find any work to do. Finally, if they all say they
476 // had no work, then it is a good time to consider sleeping (waiting) for
479 bool more_work_is_plausible
= state_
->delegate
->DoWork();
480 if (state_
->should_quit
)
483 more_work_is_plausible
|= WaitForIOCompletion(0, NULL
);
484 if (state_
->should_quit
)
487 more_work_is_plausible
|=
488 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
489 if (state_
->should_quit
)
492 if (more_work_is_plausible
)
495 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
496 if (state_
->should_quit
)
499 if (more_work_is_plausible
)
502 WaitForWork(); // Wait (sleep) until we have work to do again.
506 // Wait until IO completes, up to the time needed by the timer manager to fire
507 // the next set of timers.
508 void MessagePumpForIO::WaitForWork() {
509 // We do not support nested IO message loops. This is to avoid messy
510 // recursion problems.
511 DCHECK_EQ(1, state_
->run_depth
) << "Cannot nest an IO message loop!";
513 int timeout
= GetCurrentDelay();
514 if (timeout
< 0) // Negative value means no timers waiting.
517 WaitForIOCompletion(timeout
, NULL
);
520 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
522 if (completed_io_
.empty() || !MatchCompletedIOItem(filter
, &item
)) {
523 // We have to ask the system for another IO completion.
524 if (!GetIOItem(timeout
, &item
))
527 if (ProcessInternalIOItem(item
))
531 // If |item.has_valid_io_context| is false then |item.context| does not point
532 // to a context structure, and so should not be dereferenced, although it may
533 // still hold valid non-pointer data.
534 if (!item
.has_valid_io_context
|| item
.context
->handler
) {
535 if (filter
&& item
.handler
!= filter
) {
536 // Save this item for later
537 completed_io_
.push_back(item
);
539 DCHECK(!item
.has_valid_io_context
||
540 (item
.context
->handler
== item
.handler
));
541 WillProcessIOEvent();
542 item
.handler
->OnIOCompleted(item
.context
, item
.bytes_transfered
,
547 // The handler must be gone by now, just cleanup the mess.
553 // Asks the OS for another IO completion result.
554 bool MessagePumpForIO::GetIOItem(DWORD timeout
, IOItem
* item
) {
555 memset(item
, 0, sizeof(*item
));
556 ULONG_PTR key
= NULL
;
557 OVERLAPPED
* overlapped
= NULL
;
558 if (!GetQueuedCompletionStatus(port_
.Get(), &item
->bytes_transfered
, &key
,
559 &overlapped
, timeout
)) {
561 return false; // Nothing in the queue.
562 item
->error
= GetLastError();
563 item
->bytes_transfered
= 0;
566 item
->handler
= KeyToHandler(key
, &item
->has_valid_io_context
);
567 item
->context
= reinterpret_cast<IOContext
*>(overlapped
);
571 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem
& item
) {
572 if (this == reinterpret_cast<MessagePumpForIO
*>(item
.context
) &&
573 this == reinterpret_cast<MessagePumpForIO
*>(item
.handler
)) {
574 // This is our internal completion.
575 DCHECK(!item
.bytes_transfered
);
576 InterlockedExchange(&have_work_
, 0);
582 // Returns a completion item that was previously received.
583 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
) {
584 DCHECK(!completed_io_
.empty());
585 for (std::list
<IOItem
>::iterator it
= completed_io_
.begin();
586 it
!= completed_io_
.end(); ++it
) {
587 if (!filter
|| it
->handler
== filter
) {
589 completed_io_
.erase(it
);
596 void MessagePumpForIO::AddIOObserver(IOObserver
*obs
) {
597 io_observers_
.AddObserver(obs
);
600 void MessagePumpForIO::RemoveIOObserver(IOObserver
*obs
) {
601 io_observers_
.RemoveObserver(obs
);
604 void MessagePumpForIO::WillProcessIOEvent() {
605 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
608 void MessagePumpForIO::DidProcessIOEvent() {
609 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
613 ULONG_PTR
MessagePumpForIO::HandlerToKey(IOHandler
* handler
,
614 bool has_valid_io_context
) {
615 ULONG_PTR key
= reinterpret_cast<ULONG_PTR
>(handler
);
617 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
618 // always cleared. We use the lowest bit to distinguish completion keys with
619 // and without the associated |IOContext|.
620 DCHECK((key
& 1) == 0);
622 // Mark the completion key as context-less.
623 if (!has_valid_io_context
)
629 MessagePumpForIO::IOHandler
* MessagePumpForIO::KeyToHandler(
631 bool* has_valid_io_context
) {
632 *has_valid_io_context
= ((key
& 1) == 0);
633 return reinterpret_cast<IOHandler
*>(key
& ~static_cast<ULONG_PTR
>(1));