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/profiler/scoped_tracker.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/win/wrapped_window_proc.h"
21 enum MessageLoopProblems
{
23 COMPLETION_POST_ERROR
,
25 MESSAGE_LOOP_PROBLEM_MAX
,
30 static const wchar_t kWndClassFormat
[] = L
"Chrome_MessagePumpWindow_%p";
32 // Message sent to get an additional time slice for pumping (processing) another
33 // task (a series of such messages creates a continuous task pump).
34 static const int kMsgHaveWork
= WM_USER
+ 1;
36 //-----------------------------------------------------------------------------
37 // MessagePumpWin public:
39 void MessagePumpWin::RunWithDispatcher(
40 Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
) {
42 s
.delegate
= delegate
;
43 s
.dispatcher
= dispatcher
;
44 s
.should_quit
= false;
45 s
.run_depth
= state_
? state_
->run_depth
+ 1 : 1;
47 RunState
* previous_state
= state_
;
52 state_
= previous_state
;
55 void MessagePumpWin::Quit() {
57 state_
->should_quit
= true;
60 //-----------------------------------------------------------------------------
61 // MessagePumpWin protected:
63 int MessagePumpWin::GetCurrentDelay() const {
64 if (delayed_work_time_
.is_null())
67 // Be careful here. TimeDelta has a precision of microseconds, but we want a
68 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
69 // 6? It should be 6 to avoid executing delayed work too early.
71 ceil((delayed_work_time_
- TimeTicks::Now()).InMillisecondsF());
73 // If this value is negative, then we need to run delayed work soon.
74 int delay
= static_cast<int>(timeout
);
81 //-----------------------------------------------------------------------------
82 // MessagePumpForUI public:
84 MessagePumpForUI::MessagePumpForUI()
89 MessagePumpForUI::~MessagePumpForUI() {
90 DestroyWindow(message_hwnd_
);
91 UnregisterClass(MAKEINTATOM(atom_
),
92 GetModuleFromAddress(&WndProcThunk
));
95 void MessagePumpForUI::ScheduleWork() {
96 if (InterlockedExchange(&have_work_
, 1))
97 return; // Someone else continued the pumping.
99 // Make sure the MessagePump does some work for us.
100 BOOL ret
= PostMessage(message_hwnd_
, kMsgHaveWork
,
101 reinterpret_cast<WPARAM
>(this), 0);
103 return; // There was room in the Window Message queue.
105 // We have failed to insert a have-work message, so there is a chance that we
106 // will starve tasks/timers while sitting in a nested message loop. Nested
107 // loops only look at Windows Message queues, and don't look at *our* task
108 // queues, etc., so we might not get a time slice in such. :-(
109 // We could abort here, but the fear is that this failure mode is plausibly
110 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
111 // recovery. Nested loops are pretty transient (we think), so this will
112 // probably be recoverable.
113 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't really insert.
114 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR
,
115 MESSAGE_LOOP_PROBLEM_MAX
);
118 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
120 // We would *like* to provide high resolution timers. Windows timers using
121 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
122 // mechanism because the application can enter modal windows loops where it
123 // is not running our MessageLoop; the only way to have our timers fire in
124 // these cases is to post messages there.
126 // To provide sub-10ms timers, we process timers directly from our run loop.
127 // For the common case, timers will be processed there as the run loop does
128 // its normal work. However, we *also* set the system timer so that WM_TIMER
129 // events fire. This mops up the case of timers not being able to work in
130 // modal message loops. It is possible for the SetTimer to pop and have no
131 // pending timers, because they could have already been processed by the
134 // We use a single SetTimer corresponding to the timer that will expire
135 // soonest. As new timers are created and destroyed, we update SetTimer.
136 // Getting a spurrious SetTimer event firing is benign, as we'll just be
137 // processing an empty timer queue.
139 delayed_work_time_
= delayed_work_time
;
141 int delay_msec
= GetCurrentDelay();
142 DCHECK_GE(delay_msec
, 0);
143 if (delay_msec
< USER_TIMER_MINIMUM
)
144 delay_msec
= USER_TIMER_MINIMUM
;
146 // Create a WM_TIMER event that will wake us up to check for any pending
147 // timers (in case we are running within a nested, external sub-pump).
148 BOOL ret
= SetTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this),
152 // If we can't set timers, we are in big trouble... but cross our fingers for
154 // TODO(jar): If we don't see this error, use a CHECK() here instead.
155 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR
,
156 MESSAGE_LOOP_PROBLEM_MAX
);
159 //-----------------------------------------------------------------------------
160 // MessagePumpForUI private:
163 LRESULT CALLBACK
MessagePumpForUI::WndProcThunk(
164 HWND hwnd
, UINT message
, WPARAM wparam
, LPARAM lparam
) {
165 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
166 tracked_objects::ScopedTracker
tracking_profile(
167 FROM_HERE_WITH_EXPLICIT_FUNCTION(
168 "440919 MessagePumpForUI::WndProcThunk"));
172 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleWorkMessage();
175 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleTimerMessage();
178 return DefWindowProc(hwnd
, message
, wparam
, lparam
);
181 void MessagePumpForUI::DoRunLoop() {
182 // IF this was just a simple PeekMessage() loop (servicing all possible work
183 // queues), then Windows would try to achieve the following order according
184 // to MSDN documentation about PeekMessage with no filter):
187 // * Sent messages (again)
188 // * WM_PAINT messages
189 // * WM_TIMER messages
191 // Summary: none of the above classes is starved, and sent messages has twice
192 // the chance of being processed (i.e., reduced service time).
195 // If we do any work, we may create more messages etc., and more work may
196 // possibly be waiting in another task group. When we (for example)
197 // ProcessNextWindowsMessage(), there is a good chance there are still more
198 // messages waiting. On the other hand, when any of these methods return
199 // having done no work, then it is pretty unlikely that calling them again
200 // quickly will find any work to do. Finally, if they all say they had no
201 // work, then it is a good time to consider sleeping (waiting) for more
204 bool more_work_is_plausible
= ProcessNextWindowsMessage();
205 if (state_
->should_quit
)
208 more_work_is_plausible
|= state_
->delegate
->DoWork();
209 if (state_
->should_quit
)
212 more_work_is_plausible
|=
213 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
214 // If we did not process any delayed work, then we can assume that our
215 // existing WM_TIMER if any will fire when delayed work should run. We
216 // don't want to disturb that timer if it is already in flight. However,
217 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
218 if (more_work_is_plausible
&& delayed_work_time_
.is_null())
219 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
220 if (state_
->should_quit
)
223 if (more_work_is_plausible
)
226 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
227 if (state_
->should_quit
)
230 if (more_work_is_plausible
)
233 WaitForWork(); // Wait (sleep) until we have work to do again.
237 void MessagePumpForUI::InitMessageWnd() {
238 // Generate a unique window class name.
239 string16 class_name
= StringPrintf(kWndClassFormat
, this);
241 HINSTANCE instance
= GetModuleFromAddress(&WndProcThunk
);
243 wc
.cbSize
= sizeof(wc
);
244 wc
.lpfnWndProc
= base::win::WrappedWindowProc
<WndProcThunk
>;
245 wc
.hInstance
= instance
;
246 wc
.lpszClassName
= class_name
.c_str();
247 atom_
= RegisterClassEx(&wc
);
250 message_hwnd_
= CreateWindow(MAKEINTATOM(atom_
), 0, 0, 0, 0, 0, 0,
251 HWND_MESSAGE
, 0, instance
, 0);
252 DCHECK(message_hwnd_
);
255 void MessagePumpForUI::WaitForWork() {
256 // Wait until a message is available, up to the time needed by the timer
257 // manager to fire the next set of timers.
258 int delay
= GetCurrentDelay();
259 if (delay
< 0) // Negative value means no timers waiting.
263 result
= MsgWaitForMultipleObjectsEx(0, NULL
, delay
, QS_ALLINPUT
,
264 MWMO_INPUTAVAILABLE
);
266 if (WAIT_OBJECT_0
== result
) {
267 // A WM_* message is available.
268 // If a parent child relationship exists between windows across threads
269 // then their thread inputs are implicitly attached.
270 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
271 // that messages are ready for processing (Specifically, mouse messages
272 // intended for the child window may appear if the child window has
274 // The subsequent PeekMessages call may fail to return any messages thus
275 // causing us to enter a tight loop at times.
276 // The WaitMessage call below is a workaround to give the child window
277 // some time to process its input messages.
279 DWORD queue_status
= GetQueueStatus(QS_MOUSE
);
280 if (HIWORD(queue_status
) & QS_MOUSE
&&
281 !PeekMessage(&msg
, NULL
, WM_MOUSEFIRST
, WM_MOUSELAST
, PM_NOREMOVE
)) {
287 DCHECK_NE(WAIT_FAILED
, result
) << GetLastError();
290 void MessagePumpForUI::HandleWorkMessage() {
291 // If we are being called outside of the context of Run, then don't try to do
292 // any work. This could correspond to a MessageBox call or something of that
295 // Since we handled a kMsgHaveWork message, we must still update this flag.
296 InterlockedExchange(&have_work_
, 0);
300 // Let whatever would have run had we not been putting messages in the queue
301 // run now. This is an attempt to make our dummy message not starve other
302 // messages that may be in the Windows message queue.
303 ProcessPumpReplacementMessage();
305 // Now give the delegate a chance to do some work. He'll let us know if he
306 // needs to do more work.
307 if (state_
->delegate
->DoWork())
311 void MessagePumpForUI::HandleTimerMessage() {
312 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
314 // If we are being called outside of the context of Run, then don't do
315 // anything. This could correspond to a MessageBox call or something of
320 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
321 if (!delayed_work_time_
.is_null()) {
322 // A bit gratuitous to set delayed_work_time_ again, but oh well.
323 ScheduleDelayedWork(delayed_work_time_
);
327 bool MessagePumpForUI::ProcessNextWindowsMessage() {
328 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
329 tracked_objects::ScopedTracker
tracking_profile1(
330 FROM_HERE_WITH_EXPLICIT_FUNCTION(
331 "440919 MessagePumpForUI::ProcessNextWindowsMessage1"));
333 // If there are sent messages in the queue then PeekMessage internally
334 // dispatches the message and returns false. We return true in this
335 // case to ensure that the message loop peeks again instead of calling
336 // MsgWaitForMultipleObjectsEx again.
337 bool sent_messages_in_queue
= false;
338 DWORD queue_status
= GetQueueStatus(QS_SENDMESSAGE
);
339 if (HIWORD(queue_status
) & QS_SENDMESSAGE
)
340 sent_messages_in_queue
= true;
342 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
343 tracked_objects::ScopedTracker
tracking_profile2(
344 FROM_HERE_WITH_EXPLICIT_FUNCTION(
345 "440919 MessagePumpForUI::ProcessNextWindowsMessage2"));
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 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
356 tracked_objects::ScopedTracker
tracking_profile1(
357 FROM_HERE_WITH_EXPLICIT_FUNCTION(
358 "440919 MessagePumpForUI::ProcessMessageHelper1"));
360 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
361 "message", msg
.message
);
362 if (WM_QUIT
== msg
.message
) {
363 // Repost the QUIT message so that it will be retrieved by the primary
364 // GetMessage() loop.
365 state_
->should_quit
= true;
366 PostQuitMessage(static_cast<int>(msg
.wParam
));
370 // While running our main message pump, we discard kMsgHaveWork messages.
371 if (msg
.message
== kMsgHaveWork
&& msg
.hwnd
== message_hwnd_
)
372 return ProcessPumpReplacementMessage();
374 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
375 tracked_objects::ScopedTracker
tracking_profile2(
376 FROM_HERE_WITH_EXPLICIT_FUNCTION(
377 "440919 MessagePumpForUI::ProcessMessageHelper2"));
379 if (CallMsgFilter(const_cast<MSG
*>(&msg
), kMessageFilterCode
))
382 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
383 tracked_objects::ScopedTracker
tracking_profile3(
384 FROM_HERE_WITH_EXPLICIT_FUNCTION(
385 "440919 MessagePumpForUI::ProcessMessageHelper3"));
387 uint32_t action
= MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
;
388 if (state_
->dispatcher
) {
389 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
390 tracked_objects::ScopedTracker
tracking_profile4(
391 FROM_HERE_WITH_EXPLICIT_FUNCTION(
392 "440919 MessagePumpForUI::ProcessMessageHelper4"));
394 action
= state_
->dispatcher
->Dispatch(msg
);
396 if (action
& MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP
)
397 state_
->should_quit
= true;
398 if (action
& MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT
) {
399 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
400 tracked_objects::ScopedTracker
tracking_profile5(
401 FROM_HERE_WITH_EXPLICIT_FUNCTION(
402 "440919 MessagePumpForUI::ProcessMessageHelper5"));
404 TranslateMessage(&msg
);
406 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
407 tracked_objects::ScopedTracker
tracking_profile6(
408 FROM_HERE_WITH_EXPLICIT_FUNCTION(
409 "440919 MessagePumpForUI::ProcessMessageHelper6"));
411 DispatchMessage(&msg
);
417 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
418 // When we encounter a kMsgHaveWork message, this method is called to peek
419 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
420 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
421 // a continuous stream of such messages are posted. This method carefully
422 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
423 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
424 // possibly be posted), and finally dispatches that peeked replacement. Note
425 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
427 bool have_message
= false;
429 // We should not process all window messages if we are in the context of an
430 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
431 // This is to ensure that these messages are peeked out by the OS modal loop.
432 if (MessageLoop::current()->os_modal_loop()) {
433 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
434 have_message
= PeekMessage(&msg
, NULL
, WM_PAINT
, WM_PAINT
, PM_REMOVE
) ||
435 PeekMessage(&msg
, NULL
, WM_TIMER
, WM_TIMER
, PM_REMOVE
);
437 have_message
= PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
) != FALSE
;
440 DCHECK(!have_message
|| kMsgHaveWork
!= msg
.message
||
441 msg
.hwnd
!= message_hwnd_
);
443 // Since we discarded a kMsgHaveWork message, we must update the flag.
444 int old_have_work
= InterlockedExchange(&have_work_
, 0);
445 DCHECK(old_have_work
);
447 // We don't need a special time slice if we didn't have_message to process.
451 // Guarantee we'll get another time slice in the case where we go into native
452 // windows code. This ScheduleWork() may hurt performance a tiny bit when
453 // tasks appear very infrequently, but when the event queue is busy, the
454 // kMsgHaveWork events get (percentage wise) rarer and rarer.
456 return ProcessMessageHelper(msg
);
459 //-----------------------------------------------------------------------------
460 // MessagePumpForIO public:
462 MessagePumpForIO::MessagePumpForIO() {
463 port_
.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE
, NULL
, NULL
, 1));
464 DCHECK(port_
.IsValid());
467 void MessagePumpForIO::ScheduleWork() {
468 if (InterlockedExchange(&have_work_
, 1))
469 return; // Someone else continued the pumping.
471 // Make sure the MessagePump does some work for us.
472 BOOL ret
= PostQueuedCompletionStatus(port_
.Get(), 0,
473 reinterpret_cast<ULONG_PTR
>(this),
474 reinterpret_cast<OVERLAPPED
*>(this));
476 return; // Post worked perfectly.
478 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
479 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't succeed.
480 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR
,
481 MESSAGE_LOOP_PROBLEM_MAX
);
484 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
485 // We know that we can't be blocked right now since this method can only be
486 // called on the same thread as Run, so we only need to update our record of
487 // how long to sleep when we do sleep.
488 delayed_work_time_
= delayed_work_time
;
491 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle
,
492 IOHandler
* handler
) {
493 ULONG_PTR key
= HandlerToKey(handler
, true);
494 HANDLE port
= CreateIoCompletionPort(file_handle
, port_
.Get(), key
, 1);
498 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle
,
499 IOHandler
* handler
) {
500 // Job object notifications use the OVERLAPPED pointer to carry the message
501 // data. Mark the completion key correspondingly, so we will not try to
502 // convert OVERLAPPED* to IOContext*.
503 ULONG_PTR key
= HandlerToKey(handler
, false);
504 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info
;
505 info
.CompletionKey
= reinterpret_cast<void*>(key
);
506 info
.CompletionPort
= port_
.Get();
507 return SetInformationJobObject(job_handle
,
508 JobObjectAssociateCompletionPortInformation
,
510 sizeof(info
)) != FALSE
;
513 //-----------------------------------------------------------------------------
514 // MessagePumpForIO private:
516 void MessagePumpForIO::DoRunLoop() {
518 // If we do any work, we may create more messages etc., and more work may
519 // possibly be waiting in another task group. When we (for example)
520 // WaitForIOCompletion(), there is a good chance there are still more
521 // messages waiting. On the other hand, when any of these methods return
522 // having done no work, then it is pretty unlikely that calling them
523 // again quickly will find any work to do. Finally, if they all say they
524 // had no work, then it is a good time to consider sleeping (waiting) for
527 bool more_work_is_plausible
= state_
->delegate
->DoWork();
528 if (state_
->should_quit
)
531 more_work_is_plausible
|= WaitForIOCompletion(0, NULL
);
532 if (state_
->should_quit
)
535 more_work_is_plausible
|=
536 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
537 if (state_
->should_quit
)
540 if (more_work_is_plausible
)
543 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
544 if (state_
->should_quit
)
547 if (more_work_is_plausible
)
550 WaitForWork(); // Wait (sleep) until we have work to do again.
554 // Wait until IO completes, up to the time needed by the timer manager to fire
555 // the next set of timers.
556 void MessagePumpForIO::WaitForWork() {
557 // We do not support nested IO message loops. This is to avoid messy
558 // recursion problems.
559 DCHECK_EQ(1, state_
->run_depth
) << "Cannot nest an IO message loop!";
561 int timeout
= GetCurrentDelay();
562 if (timeout
< 0) // Negative value means no timers waiting.
565 WaitForIOCompletion(timeout
, NULL
);
568 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
570 if (completed_io_
.empty() || !MatchCompletedIOItem(filter
, &item
)) {
571 // We have to ask the system for another IO completion.
572 if (!GetIOItem(timeout
, &item
))
575 if (ProcessInternalIOItem(item
))
579 // If |item.has_valid_io_context| is false then |item.context| does not point
580 // to a context structure, and so should not be dereferenced, although it may
581 // still hold valid non-pointer data.
582 if (!item
.has_valid_io_context
|| item
.context
->handler
) {
583 if (filter
&& item
.handler
!= filter
) {
584 // Save this item for later
585 completed_io_
.push_back(item
);
587 DCHECK(!item
.has_valid_io_context
||
588 (item
.context
->handler
== item
.handler
));
589 WillProcessIOEvent();
590 item
.handler
->OnIOCompleted(item
.context
, item
.bytes_transfered
,
595 // The handler must be gone by now, just cleanup the mess.
601 // Asks the OS for another IO completion result.
602 bool MessagePumpForIO::GetIOItem(DWORD timeout
, IOItem
* item
) {
603 memset(item
, 0, sizeof(*item
));
604 ULONG_PTR key
= NULL
;
605 OVERLAPPED
* overlapped
= NULL
;
606 if (!GetQueuedCompletionStatus(port_
.Get(), &item
->bytes_transfered
, &key
,
607 &overlapped
, timeout
)) {
609 return false; // Nothing in the queue.
610 item
->error
= GetLastError();
611 item
->bytes_transfered
= 0;
614 item
->handler
= KeyToHandler(key
, &item
->has_valid_io_context
);
615 item
->context
= reinterpret_cast<IOContext
*>(overlapped
);
619 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem
& item
) {
620 if (this == reinterpret_cast<MessagePumpForIO
*>(item
.context
) &&
621 this == reinterpret_cast<MessagePumpForIO
*>(item
.handler
)) {
622 // This is our internal completion.
623 DCHECK(!item
.bytes_transfered
);
624 InterlockedExchange(&have_work_
, 0);
630 // Returns a completion item that was previously received.
631 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
) {
632 DCHECK(!completed_io_
.empty());
633 for (std::list
<IOItem
>::iterator it
= completed_io_
.begin();
634 it
!= completed_io_
.end(); ++it
) {
635 if (!filter
|| it
->handler
== filter
) {
637 completed_io_
.erase(it
);
644 void MessagePumpForIO::AddIOObserver(IOObserver
*obs
) {
645 io_observers_
.AddObserver(obs
);
648 void MessagePumpForIO::RemoveIOObserver(IOObserver
*obs
) {
649 io_observers_
.RemoveObserver(obs
);
652 void MessagePumpForIO::WillProcessIOEvent() {
653 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
656 void MessagePumpForIO::DidProcessIOEvent() {
657 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
661 ULONG_PTR
MessagePumpForIO::HandlerToKey(IOHandler
* handler
,
662 bool has_valid_io_context
) {
663 ULONG_PTR key
= reinterpret_cast<ULONG_PTR
>(handler
);
665 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
666 // always cleared. We use the lowest bit to distinguish completion keys with
667 // and without the associated |IOContext|.
668 DCHECK((key
& 1) == 0);
670 // Mark the completion key as context-less.
671 if (!has_valid_io_context
)
677 MessagePumpForIO::IOHandler
* MessagePumpForIO::KeyToHandler(
679 bool* has_valid_io_context
) {
680 *has_valid_io_context
= ((key
& 1) == 0);
681 return reinterpret_cast<IOHandler
*>(key
& ~static_cast<ULONG_PTR
>(1));