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"
10 #include "base/message_loop/message_loop.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process/memory.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/win/wrapped_window_proc.h"
22 enum MessageLoopProblems
{
24 COMPLETION_POST_ERROR
,
26 MESSAGE_LOOP_PROBLEM_MAX
,
31 static const wchar_t kWndClassFormat
[] = L
"Chrome_MessagePumpWindow_%p";
33 // Message sent to get an additional time slice for pumping (processing) another
34 // task (a series of such messages creates a continuous task pump).
35 static const int kMsgHaveWork
= WM_USER
+ 1;
37 //-----------------------------------------------------------------------------
38 // MessagePumpWin public:
40 void MessagePumpWin::RunWithDispatcher(
41 Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
) {
43 s
.delegate
= delegate
;
44 s
.dispatcher
= dispatcher
;
45 s
.should_quit
= false;
46 s
.run_depth
= state_
? state_
->run_depth
+ 1 : 1;
48 RunState
* previous_state
= state_
;
53 state_
= previous_state
;
56 void MessagePumpWin::Quit() {
58 state_
->should_quit
= true;
61 //-----------------------------------------------------------------------------
62 // MessagePumpWin protected:
64 int MessagePumpWin::GetCurrentDelay() const {
65 if (delayed_work_time_
.is_null())
68 // Be careful here. TimeDelta has a precision of microseconds, but we want a
69 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
70 // 6? It should be 6 to avoid executing delayed work too early.
72 ceil((delayed_work_time_
- TimeTicks::Now()).InMillisecondsF());
74 // Range check the |timeout| while converting to an integer. If the |timeout|
75 // is negative, then we need to run delayed work soon. If the |timeout| is
76 // "overflowingly" large, that means a delayed task was posted with a
78 return timeout
< 0 ? 0 :
79 (timeout
> std::numeric_limits
<int>::max() ?
80 std::numeric_limits
<int>::max() : static_cast<int>(timeout
));
83 //-----------------------------------------------------------------------------
84 // MessagePumpForUI public:
86 MessagePumpForUI::MessagePumpForUI()
91 MessagePumpForUI::~MessagePumpForUI() {
92 DestroyWindow(message_hwnd_
);
93 UnregisterClass(MAKEINTATOM(atom_
),
94 GetModuleFromAddress(&WndProcThunk
));
97 void MessagePumpForUI::ScheduleWork() {
98 if (InterlockedExchange(&have_work_
, 1))
99 return; // Someone else continued the pumping.
101 // Make sure the MessagePump does some work for us.
102 BOOL ret
= PostMessage(message_hwnd_
, kMsgHaveWork
,
103 reinterpret_cast<WPARAM
>(this), 0);
105 return; // There was room in the Window Message queue.
107 // We have failed to insert a have-work message, so there is a chance that we
108 // will starve tasks/timers while sitting in a nested message loop. Nested
109 // loops only look at Windows Message queues, and don't look at *our* task
110 // queues, etc., so we might not get a time slice in such. :-(
111 // We could abort here, but the fear is that this failure mode is plausibly
112 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
113 // recovery. Nested loops are pretty transient (we think), so this will
114 // probably be recoverable.
115 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't really insert.
116 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR
,
117 MESSAGE_LOOP_PROBLEM_MAX
);
120 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
122 // We would *like* to provide high resolution timers. Windows timers using
123 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
124 // mechanism because the application can enter modal windows loops where it
125 // is not running our MessageLoop; the only way to have our timers fire in
126 // these cases is to post messages there.
128 // To provide sub-10ms timers, we process timers directly from our run loop.
129 // For the common case, timers will be processed there as the run loop does
130 // its normal work. However, we *also* set the system timer so that WM_TIMER
131 // events fire. This mops up the case of timers not being able to work in
132 // modal message loops. It is possible for the SetTimer to pop and have no
133 // pending timers, because they could have already been processed by the
136 // We use a single SetTimer corresponding to the timer that will expire
137 // soonest. As new timers are created and destroyed, we update SetTimer.
138 // Getting a spurrious SetTimer event firing is benign, as we'll just be
139 // processing an empty timer queue.
141 delayed_work_time_
= delayed_work_time
;
143 int delay_msec
= GetCurrentDelay();
144 DCHECK_GE(delay_msec
, 0);
145 if (delay_msec
< USER_TIMER_MINIMUM
)
146 delay_msec
= USER_TIMER_MINIMUM
;
148 // Create a WM_TIMER event that will wake us up to check for any pending
149 // timers (in case we are running within a nested, external sub-pump).
150 BOOL ret
= SetTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this),
154 // If we can't set timers, we are in big trouble... but cross our fingers for
156 // TODO(jar): If we don't see this error, use a CHECK() here instead.
157 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR
,
158 MESSAGE_LOOP_PROBLEM_MAX
);
161 //-----------------------------------------------------------------------------
162 // MessagePumpForUI private:
165 LRESULT CALLBACK
MessagePumpForUI::WndProcThunk(
166 HWND hwnd
, UINT message
, WPARAM wparam
, LPARAM lparam
) {
167 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
168 tracked_objects::ScopedTracker
tracking_profile1(
169 FROM_HERE_WITH_EXPLICIT_FUNCTION(
170 "440919 MessagePumpForUI::WndProcThunk1"));
174 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleWorkMessage();
177 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleTimerMessage();
181 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
182 tracked_objects::ScopedTracker
tracking_profile2(
183 FROM_HERE_WITH_EXPLICIT_FUNCTION(
184 "440919 MessagePumpForUI::WndProcThunk2"));
186 return DefWindowProc(hwnd
, message
, wparam
, lparam
);
189 void MessagePumpForUI::DoRunLoop() {
190 // IF this was just a simple PeekMessage() loop (servicing all possible work
191 // queues), then Windows would try to achieve the following order according
192 // to MSDN documentation about PeekMessage with no filter):
195 // * Sent messages (again)
196 // * WM_PAINT messages
197 // * WM_TIMER messages
199 // Summary: none of the above classes is starved, and sent messages has twice
200 // the chance of being processed (i.e., reduced service time).
203 // If we do any work, we may create more messages etc., and more work may
204 // possibly be waiting in another task group. When we (for example)
205 // ProcessNextWindowsMessage(), there is a good chance there are still more
206 // messages waiting. On the other hand, when any of these methods return
207 // having done no work, then it is pretty unlikely that calling them again
208 // quickly will find any work to do. Finally, if they all say they had no
209 // work, then it is a good time to consider sleeping (waiting) for more
212 bool more_work_is_plausible
= ProcessNextWindowsMessage();
213 if (state_
->should_quit
)
216 more_work_is_plausible
|= state_
->delegate
->DoWork();
217 if (state_
->should_quit
)
220 more_work_is_plausible
|=
221 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
222 // If we did not process any delayed work, then we can assume that our
223 // existing WM_TIMER if any will fire when delayed work should run. We
224 // don't want to disturb that timer if it is already in flight. However,
225 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
226 if (more_work_is_plausible
&& delayed_work_time_
.is_null())
227 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
228 if (state_
->should_quit
)
231 if (more_work_is_plausible
)
234 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
235 if (state_
->should_quit
)
238 if (more_work_is_plausible
)
241 WaitForWork(); // Wait (sleep) until we have work to do again.
245 void MessagePumpForUI::InitMessageWnd() {
246 // Generate a unique window class name.
247 string16 class_name
= StringPrintf(kWndClassFormat
, this);
249 HINSTANCE instance
= GetModuleFromAddress(&WndProcThunk
);
251 wc
.cbSize
= sizeof(wc
);
252 wc
.lpfnWndProc
= base::win::WrappedWindowProc
<WndProcThunk
>;
253 wc
.hInstance
= instance
;
254 wc
.lpszClassName
= class_name
.c_str();
255 atom_
= RegisterClassEx(&wc
);
258 message_hwnd_
= CreateWindow(MAKEINTATOM(atom_
), 0, 0, 0, 0, 0, 0,
259 HWND_MESSAGE
, 0, instance
, 0);
260 DCHECK(message_hwnd_
);
263 void MessagePumpForUI::WaitForWork() {
264 // Wait until a message is available, up to the time needed by the timer
265 // manager to fire the next set of timers.
266 int delay
= GetCurrentDelay();
267 if (delay
< 0) // Negative value means no timers waiting.
271 result
= MsgWaitForMultipleObjectsEx(0, NULL
, delay
, QS_ALLINPUT
,
272 MWMO_INPUTAVAILABLE
);
274 if (WAIT_OBJECT_0
== result
) {
275 // A WM_* message is available.
276 // If a parent child relationship exists between windows across threads
277 // then their thread inputs are implicitly attached.
278 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
279 // that messages are ready for processing (Specifically, mouse messages
280 // intended for the child window may appear if the child window has
282 // The subsequent PeekMessages call may fail to return any messages thus
283 // causing us to enter a tight loop at times.
284 // The WaitMessage call below is a workaround to give the child window
285 // some time to process its input messages.
287 DWORD queue_status
= GetQueueStatus(QS_MOUSE
);
288 if (HIWORD(queue_status
) & QS_MOUSE
&&
289 !PeekMessage(&msg
, NULL
, WM_MOUSEFIRST
, WM_MOUSELAST
, PM_NOREMOVE
)) {
295 DCHECK_NE(WAIT_FAILED
, result
) << GetLastError();
298 void MessagePumpForUI::HandleWorkMessage() {
299 // If we are being called outside of the context of Run, then don't try to do
300 // any work. This could correspond to a MessageBox call or something of that
303 // Since we handled a kMsgHaveWork message, we must still update this flag.
304 InterlockedExchange(&have_work_
, 0);
308 // Let whatever would have run had we not been putting messages in the queue
309 // run now. This is an attempt to make our dummy message not starve other
310 // messages that may be in the Windows message queue.
311 ProcessPumpReplacementMessage();
313 // Now give the delegate a chance to do some work. He'll let us know if he
314 // needs to do more work.
315 if (state_
->delegate
->DoWork())
319 void MessagePumpForUI::HandleTimerMessage() {
320 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
322 // If we are being called outside of the context of Run, then don't do
323 // anything. This could correspond to a MessageBox call or something of
328 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
329 if (!delayed_work_time_
.is_null()) {
330 // A bit gratuitous to set delayed_work_time_ again, but oh well.
331 ScheduleDelayedWork(delayed_work_time_
);
335 bool MessagePumpForUI::ProcessNextWindowsMessage() {
336 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
337 tracked_objects::ScopedTracker
tracking_profile1(
338 FROM_HERE_WITH_EXPLICIT_FUNCTION(
339 "440919 MessagePumpForUI::ProcessNextWindowsMessage1"));
341 // If there are sent messages in the queue then PeekMessage internally
342 // dispatches the message and returns false. We return true in this
343 // case to ensure that the message loop peeks again instead of calling
344 // MsgWaitForMultipleObjectsEx again.
345 bool sent_messages_in_queue
= false;
346 DWORD queue_status
= GetQueueStatus(QS_SENDMESSAGE
);
347 if (HIWORD(queue_status
) & QS_SENDMESSAGE
)
348 sent_messages_in_queue
= true;
350 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
351 tracked_objects::ScopedTracker
tracking_profile2(
352 FROM_HERE_WITH_EXPLICIT_FUNCTION(
353 "440919 MessagePumpForUI::ProcessNextWindowsMessage2"));
356 if (PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
)
357 return ProcessMessageHelper(msg
);
359 return sent_messages_in_queue
;
362 bool MessagePumpForUI::ProcessMessageHelper(const MSG
& msg
) {
363 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
364 tracked_objects::ScopedTracker
tracking_profile1(
365 FROM_HERE_WITH_EXPLICIT_FUNCTION(
366 "440919 MessagePumpForUI::ProcessMessageHelper1"));
368 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
369 "message", msg
.message
);
370 if (WM_QUIT
== msg
.message
) {
371 // Repost the QUIT message so that it will be retrieved by the primary
372 // GetMessage() loop.
373 state_
->should_quit
= true;
374 PostQuitMessage(static_cast<int>(msg
.wParam
));
378 // While running our main message pump, we discard kMsgHaveWork messages.
379 if (msg
.message
== kMsgHaveWork
&& msg
.hwnd
== message_hwnd_
)
380 return ProcessPumpReplacementMessage();
382 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
383 tracked_objects::ScopedTracker
tracking_profile2(
384 FROM_HERE_WITH_EXPLICIT_FUNCTION(
385 "440919 MessagePumpForUI::ProcessMessageHelper2"));
387 if (CallMsgFilter(const_cast<MSG
*>(&msg
), kMessageFilterCode
))
390 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
391 tracked_objects::ScopedTracker
tracking_profile3(
392 FROM_HERE_WITH_EXPLICIT_FUNCTION(
393 "440919 MessagePumpForUI::ProcessMessageHelper3"));
395 uint32_t action
= MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
;
396 if (state_
->dispatcher
) {
397 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
398 tracked_objects::ScopedTracker
tracking_profile4(
399 FROM_HERE_WITH_EXPLICIT_FUNCTION(
400 "440919 MessagePumpForUI::ProcessMessageHelper4"));
402 action
= state_
->dispatcher
->Dispatch(msg
);
404 if (action
& MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP
)
405 state_
->should_quit
= true;
406 if (action
& MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
) {
407 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
408 tracked_objects::ScopedTracker
tracking_profile5(
409 FROM_HERE_WITH_EXPLICIT_FUNCTION(
410 "440919 MessagePumpForUI::ProcessMessageHelper5"));
412 TranslateMessage(&msg
);
414 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
415 tracked_objects::ScopedTracker
tracking_profile6(
416 FROM_HERE_WITH_EXPLICIT_FUNCTION(
417 "440919 MessagePumpForUI::ProcessMessageHelper6"));
419 DispatchMessage(&msg
);
425 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
426 // When we encounter a kMsgHaveWork message, this method is called to peek
427 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
428 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
429 // a continuous stream of such messages are posted. This method carefully
430 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
431 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
432 // possibly be posted), and finally dispatches that peeked replacement. Note
433 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
435 bool have_message
= false;
437 // We should not process all window messages if we are in the context of an
438 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
439 // This is to ensure that these messages are peeked out by the OS modal loop.
440 if (MessageLoop::current()->os_modal_loop()) {
441 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
442 have_message
= PeekMessage(&msg
, NULL
, WM_PAINT
, WM_PAINT
, PM_REMOVE
) ||
443 PeekMessage(&msg
, NULL
, WM_TIMER
, WM_TIMER
, PM_REMOVE
);
445 have_message
= PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
;
448 DCHECK(!have_message
|| kMsgHaveWork
!= msg
.message
||
449 msg
.hwnd
!= message_hwnd_
);
451 // Since we discarded a kMsgHaveWork message, we must update the flag.
452 int old_have_work
= InterlockedExchange(&have_work_
, 0);
453 DCHECK(old_have_work
);
455 // We don't need a special time slice if we didn't have_message to process.
459 // Guarantee we'll get another time slice in the case where we go into native
460 // windows code. This ScheduleWork() may hurt performance a tiny bit when
461 // tasks appear very infrequently, but when the event queue is busy, the
462 // kMsgHaveWork events get (percentage wise) rarer and rarer.
464 return ProcessMessageHelper(msg
);
467 //-----------------------------------------------------------------------------
468 // MessagePumpForIO public:
470 MessagePumpForIO::MessagePumpForIO() {
471 port_
.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE
, NULL
, NULL
, 1));
472 DCHECK(port_
.IsValid());
475 void MessagePumpForIO::ScheduleWork() {
476 if (InterlockedExchange(&have_work_
, 1))
477 return; // Someone else continued the pumping.
479 // Make sure the MessagePump does some work for us.
480 BOOL ret
= PostQueuedCompletionStatus(port_
.Get(), 0,
481 reinterpret_cast<ULONG_PTR
>(this),
482 reinterpret_cast<OVERLAPPED
*>(this));
484 return; // Post worked perfectly.
486 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
487 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't succeed.
488 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR
,
489 MESSAGE_LOOP_PROBLEM_MAX
);
492 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
493 // We know that we can't be blocked right now since this method can only be
494 // called on the same thread as Run, so we only need to update our record of
495 // how long to sleep when we do sleep.
496 delayed_work_time_
= delayed_work_time
;
499 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle
,
500 IOHandler
* handler
) {
501 ULONG_PTR key
= HandlerToKey(handler
, true);
502 HANDLE port
= CreateIoCompletionPort(file_handle
, port_
.Get(), key
, 1);
506 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle
,
507 IOHandler
* handler
) {
508 // Job object notifications use the OVERLAPPED pointer to carry the message
509 // data. Mark the completion key correspondingly, so we will not try to
510 // convert OVERLAPPED* to IOContext*.
511 ULONG_PTR key
= HandlerToKey(handler
, false);
512 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info
;
513 info
.CompletionKey
= reinterpret_cast<void*>(key
);
514 info
.CompletionPort
= port_
.Get();
515 return SetInformationJobObject(job_handle
,
516 JobObjectAssociateCompletionPortInformation
,
518 sizeof(info
)) != FALSE
;
521 //-----------------------------------------------------------------------------
522 // MessagePumpForIO private:
524 void MessagePumpForIO::DoRunLoop() {
526 // If we do any work, we may create more messages etc., and more work may
527 // possibly be waiting in another task group. When we (for example)
528 // WaitForIOCompletion(), there is a good chance there are still more
529 // messages waiting. On the other hand, when any of these methods return
530 // having done no work, then it is pretty unlikely that calling them
531 // again quickly will find any work to do. Finally, if they all say they
532 // had no work, then it is a good time to consider sleeping (waiting) for
535 bool more_work_is_plausible
= state_
->delegate
->DoWork();
536 if (state_
->should_quit
)
539 more_work_is_plausible
|= WaitForIOCompletion(0, NULL
);
540 if (state_
->should_quit
)
543 more_work_is_plausible
|=
544 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
545 if (state_
->should_quit
)
548 if (more_work_is_plausible
)
551 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
552 if (state_
->should_quit
)
555 if (more_work_is_plausible
)
558 WaitForWork(); // Wait (sleep) until we have work to do again.
562 // Wait until IO completes, up to the time needed by the timer manager to fire
563 // the next set of timers.
564 void MessagePumpForIO::WaitForWork() {
565 // We do not support nested IO message loops. This is to avoid messy
566 // recursion problems.
567 DCHECK_EQ(1, state_
->run_depth
) << "Cannot nest an IO message loop!";
569 int timeout
= GetCurrentDelay();
570 if (timeout
< 0) // Negative value means no timers waiting.
573 WaitForIOCompletion(timeout
, NULL
);
576 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
578 if (completed_io_
.empty() || !MatchCompletedIOItem(filter
, &item
)) {
579 // We have to ask the system for another IO completion.
580 if (!GetIOItem(timeout
, &item
))
583 if (ProcessInternalIOItem(item
))
587 // If |item.has_valid_io_context| is false then |item.context| does not point
588 // to a context structure, and so should not be dereferenced, although it may
589 // still hold valid non-pointer data.
590 if (!item
.has_valid_io_context
|| item
.context
->handler
) {
591 if (filter
&& item
.handler
!= filter
) {
592 // Save this item for later
593 completed_io_
.push_back(item
);
595 DCHECK(!item
.has_valid_io_context
||
596 (item
.context
->handler
== item
.handler
));
597 WillProcessIOEvent();
598 item
.handler
->OnIOCompleted(item
.context
, item
.bytes_transfered
,
603 // The handler must be gone by now, just cleanup the mess.
609 // Asks the OS for another IO completion result.
610 bool MessagePumpForIO::GetIOItem(DWORD timeout
, IOItem
* item
) {
611 memset(item
, 0, sizeof(*item
));
612 ULONG_PTR key
= NULL
;
613 OVERLAPPED
* overlapped
= NULL
;
614 if (!GetQueuedCompletionStatus(port_
.Get(), &item
->bytes_transfered
, &key
,
615 &overlapped
, timeout
)) {
617 return false; // Nothing in the queue.
618 item
->error
= GetLastError();
619 item
->bytes_transfered
= 0;
622 item
->handler
= KeyToHandler(key
, &item
->has_valid_io_context
);
623 item
->context
= reinterpret_cast<IOContext
*>(overlapped
);
627 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem
& item
) {
628 if (this == reinterpret_cast<MessagePumpForIO
*>(item
.context
) &&
629 this == reinterpret_cast<MessagePumpForIO
*>(item
.handler
)) {
630 // This is our internal completion.
631 DCHECK(!item
.bytes_transfered
);
632 InterlockedExchange(&have_work_
, 0);
638 // Returns a completion item that was previously received.
639 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
) {
640 DCHECK(!completed_io_
.empty());
641 for (std::list
<IOItem
>::iterator it
= completed_io_
.begin();
642 it
!= completed_io_
.end(); ++it
) {
643 if (!filter
|| it
->handler
== filter
) {
645 completed_io_
.erase(it
);
652 void MessagePumpForIO::AddIOObserver(IOObserver
*obs
) {
653 io_observers_
.AddObserver(obs
);
656 void MessagePumpForIO::RemoveIOObserver(IOObserver
*obs
) {
657 io_observers_
.RemoveObserver(obs
);
660 void MessagePumpForIO::WillProcessIOEvent() {
661 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
664 void MessagePumpForIO::DidProcessIOEvent() {
665 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
669 ULONG_PTR
MessagePumpForIO::HandlerToKey(IOHandler
* handler
,
670 bool has_valid_io_context
) {
671 ULONG_PTR key
= reinterpret_cast<ULONG_PTR
>(handler
);
673 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
674 // always cleared. We use the lowest bit to distinguish completion keys with
675 // and without the associated |IOContext|.
676 DCHECK_EQ(key
& 1, 0u);
678 // Mark the completion key as context-less.
679 if (!has_valid_io_context
)
685 MessagePumpForIO::IOHandler
* MessagePumpForIO::KeyToHandler(
687 bool* has_valid_io_context
) {
688 *has_valid_io_context
= ((key
& 1) == 0);
689 return reinterpret_cast<IOHandler
*>(key
& ~static_cast<ULONG_PTR
>(1));