Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / base / message_loop / message_pump_win.cc
blob27b47e1a0f878cfceef3c04b2364116ca64ac4c8
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"
7 #include <limits>
8 #include <math.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"
18 namespace base {
20 namespace {
22 enum MessageLoopProblems {
23 MESSAGE_POST_ERROR,
24 COMPLETION_POST_ERROR,
25 SET_TIMER_ERROR,
26 MESSAGE_LOOP_PROBLEM_MAX,
29 } // namespace
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) {
42 RunState s;
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_;
49 state_ = &s;
51 DoRunLoop();
53 state_ = previous_state;
56 void MessagePumpWin::Run(Delegate* delegate) {
57 RunWithDispatcher(delegate, NULL);
60 void MessagePumpWin::Quit() {
61 DCHECK(state_);
62 state_->should_quit = true;
65 //-----------------------------------------------------------------------------
66 // MessagePumpWin protected:
68 int MessagePumpWin::GetCurrentDelay() const {
69 if (delayed_work_time_.is_null())
70 return -1;
72 // Be careful here. TimeDelta has a precision of microseconds, but we want a
73 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
74 // 6? It should be 6 to avoid executing delayed work too early.
75 double timeout =
76 ceil((delayed_work_time_ - TimeTicks::Now()).InMillisecondsF());
78 // Range check the |timeout| while converting to an integer. If the |timeout|
79 // is negative, then we need to run delayed work soon. If the |timeout| is
80 // "overflowingly" large, that means a delayed task was posted with a
81 // super-long delay.
82 return timeout < 0 ? 0 :
83 (timeout > std::numeric_limits<int>::max() ?
84 std::numeric_limits<int>::max() : static_cast<int>(timeout));
87 //-----------------------------------------------------------------------------
88 // MessagePumpForUI public:
90 MessagePumpForUI::MessagePumpForUI()
91 : atom_(0) {
92 InitMessageWnd();
95 MessagePumpForUI::~MessagePumpForUI() {
96 DestroyWindow(message_hwnd_);
97 UnregisterClass(MAKEINTATOM(atom_),
98 GetModuleFromAddress(&WndProcThunk));
101 void MessagePumpForUI::ScheduleWork() {
102 if (InterlockedExchange(&have_work_, 1))
103 return; // Someone else continued the pumping.
105 // Make sure the MessagePump does some work for us.
106 BOOL ret = PostMessage(message_hwnd_, kMsgHaveWork,
107 reinterpret_cast<WPARAM>(this), 0);
108 if (ret)
109 return; // There was room in the Window Message queue.
111 // We have failed to insert a have-work message, so there is a chance that we
112 // will starve tasks/timers while sitting in a nested message loop. Nested
113 // loops only look at Windows Message queues, and don't look at *our* task
114 // queues, etc., so we might not get a time slice in such. :-(
115 // We could abort here, but the fear is that this failure mode is plausibly
116 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
117 // recovery. Nested loops are pretty transient (we think), so this will
118 // probably be recoverable.
119 InterlockedExchange(&have_work_, 0); // Clarify that we didn't really insert.
120 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR,
121 MESSAGE_LOOP_PROBLEM_MAX);
124 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
126 // We would *like* to provide high resolution timers. Windows timers using
127 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
128 // mechanism because the application can enter modal windows loops where it
129 // is not running our MessageLoop; the only way to have our timers fire in
130 // these cases is to post messages there.
132 // To provide sub-10ms timers, we process timers directly from our run loop.
133 // For the common case, timers will be processed there as the run loop does
134 // its normal work. However, we *also* set the system timer so that WM_TIMER
135 // events fire. This mops up the case of timers not being able to work in
136 // modal message loops. It is possible for the SetTimer to pop and have no
137 // pending timers, because they could have already been processed by the
138 // run loop itself.
140 // We use a single SetTimer corresponding to the timer that will expire
141 // soonest. As new timers are created and destroyed, we update SetTimer.
142 // Getting a spurrious SetTimer event firing is benign, as we'll just be
143 // processing an empty timer queue.
145 delayed_work_time_ = delayed_work_time;
147 int delay_msec = GetCurrentDelay();
148 DCHECK_GE(delay_msec, 0);
149 if (delay_msec < USER_TIMER_MINIMUM)
150 delay_msec = USER_TIMER_MINIMUM;
152 // Create a WM_TIMER event that will wake us up to check for any pending
153 // timers (in case we are running within a nested, external sub-pump).
154 BOOL ret = SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this),
155 delay_msec, NULL);
156 if (ret)
157 return;
158 // If we can't set timers, we are in big trouble... but cross our fingers for
159 // now.
160 // TODO(jar): If we don't see this error, use a CHECK() here instead.
161 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR,
162 MESSAGE_LOOP_PROBLEM_MAX);
165 //-----------------------------------------------------------------------------
166 // MessagePumpForUI private:
168 // static
169 LRESULT CALLBACK MessagePumpForUI::WndProcThunk(
170 HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
171 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
172 tracked_objects::ScopedTracker tracking_profile1(
173 FROM_HERE_WITH_EXPLICIT_FUNCTION(
174 "440919 MessagePumpForUI::WndProcThunk1"));
176 switch (message) {
177 case kMsgHaveWork:
178 reinterpret_cast<MessagePumpForUI*>(wparam)->HandleWorkMessage();
179 break;
180 case WM_TIMER:
181 reinterpret_cast<MessagePumpForUI*>(wparam)->HandleTimerMessage();
182 break;
185 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
186 tracked_objects::ScopedTracker tracking_profile2(
187 FROM_HERE_WITH_EXPLICIT_FUNCTION(
188 "440919 MessagePumpForUI::WndProcThunk2"));
190 return DefWindowProc(hwnd, message, wparam, lparam);
193 void MessagePumpForUI::DoRunLoop() {
194 // IF this was just a simple PeekMessage() loop (servicing all possible work
195 // queues), then Windows would try to achieve the following order according
196 // to MSDN documentation about PeekMessage with no filter):
197 // * Sent messages
198 // * Posted messages
199 // * Sent messages (again)
200 // * WM_PAINT messages
201 // * WM_TIMER messages
203 // Summary: none of the above classes is starved, and sent messages has twice
204 // the chance of being processed (i.e., reduced service time).
206 for (;;) {
207 // If we do any work, we may create more messages etc., and more work may
208 // possibly be waiting in another task group. When we (for example)
209 // ProcessNextWindowsMessage(), there is a good chance there are still more
210 // messages waiting. On the other hand, when any of these methods return
211 // having done no work, then it is pretty unlikely that calling them again
212 // quickly will find any work to do. Finally, if they all say they had no
213 // work, then it is a good time to consider sleeping (waiting) for more
214 // work.
216 bool more_work_is_plausible = ProcessNextWindowsMessage();
217 if (state_->should_quit)
218 break;
220 more_work_is_plausible |= state_->delegate->DoWork();
221 if (state_->should_quit)
222 break;
224 more_work_is_plausible |=
225 state_->delegate->DoDelayedWork(&delayed_work_time_);
226 // If we did not process any delayed work, then we can assume that our
227 // existing WM_TIMER if any will fire when delayed work should run. We
228 // don't want to disturb that timer if it is already in flight. However,
229 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
230 if (more_work_is_plausible && delayed_work_time_.is_null())
231 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
232 if (state_->should_quit)
233 break;
235 if (more_work_is_plausible)
236 continue;
238 more_work_is_plausible = state_->delegate->DoIdleWork();
239 if (state_->should_quit)
240 break;
242 if (more_work_is_plausible)
243 continue;
245 WaitForWork(); // Wait (sleep) until we have work to do again.
249 void MessagePumpForUI::InitMessageWnd() {
250 // Generate a unique window class name.
251 string16 class_name = StringPrintf(kWndClassFormat, this);
253 HINSTANCE instance = GetModuleFromAddress(&WndProcThunk);
254 WNDCLASSEX wc = {0};
255 wc.cbSize = sizeof(wc);
256 wc.lpfnWndProc = base::win::WrappedWindowProc<WndProcThunk>;
257 wc.hInstance = instance;
258 wc.lpszClassName = class_name.c_str();
259 atom_ = RegisterClassEx(&wc);
260 DCHECK(atom_);
262 message_hwnd_ = CreateWindow(MAKEINTATOM(atom_), 0, 0, 0, 0, 0, 0,
263 HWND_MESSAGE, 0, instance, 0);
264 DCHECK(message_hwnd_);
267 void MessagePumpForUI::WaitForWork() {
268 // Wait until a message is available, up to the time needed by the timer
269 // manager to fire the next set of timers.
270 int delay = GetCurrentDelay();
271 if (delay < 0) // Negative value means no timers waiting.
272 delay = INFINITE;
274 DWORD result;
275 result = MsgWaitForMultipleObjectsEx(0, NULL, delay, QS_ALLINPUT,
276 MWMO_INPUTAVAILABLE);
278 if (WAIT_OBJECT_0 == result) {
279 // A WM_* message is available.
280 // If a parent child relationship exists between windows across threads
281 // then their thread inputs are implicitly attached.
282 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
283 // that messages are ready for processing (Specifically, mouse messages
284 // intended for the child window may appear if the child window has
285 // capture).
286 // The subsequent PeekMessages call may fail to return any messages thus
287 // causing us to enter a tight loop at times.
288 // The WaitMessage call below is a workaround to give the child window
289 // some time to process its input messages.
290 MSG msg = {0};
291 DWORD queue_status = GetQueueStatus(QS_MOUSE);
292 if (HIWORD(queue_status) & QS_MOUSE &&
293 !PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_NOREMOVE)) {
294 WaitMessage();
296 return;
299 DCHECK_NE(WAIT_FAILED, result) << GetLastError();
302 void MessagePumpForUI::HandleWorkMessage() {
303 // If we are being called outside of the context of Run, then don't try to do
304 // any work. This could correspond to a MessageBox call or something of that
305 // sort.
306 if (!state_) {
307 // Since we handled a kMsgHaveWork message, we must still update this flag.
308 InterlockedExchange(&have_work_, 0);
309 return;
312 // Let whatever would have run had we not been putting messages in the queue
313 // run now. This is an attempt to make our dummy message not starve other
314 // messages that may be in the Windows message queue.
315 ProcessPumpReplacementMessage();
317 // Now give the delegate a chance to do some work. He'll let us know if he
318 // needs to do more work.
319 if (state_->delegate->DoWork())
320 ScheduleWork();
323 void MessagePumpForUI::HandleTimerMessage() {
324 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
326 // If we are being called outside of the context of Run, then don't do
327 // anything. This could correspond to a MessageBox call or something of
328 // that sort.
329 if (!state_)
330 return;
332 state_->delegate->DoDelayedWork(&delayed_work_time_);
333 if (!delayed_work_time_.is_null()) {
334 // A bit gratuitous to set delayed_work_time_ again, but oh well.
335 ScheduleDelayedWork(delayed_work_time_);
339 bool MessagePumpForUI::ProcessNextWindowsMessage() {
340 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
341 tracked_objects::ScopedTracker tracking_profile1(
342 FROM_HERE_WITH_EXPLICIT_FUNCTION(
343 "440919 MessagePumpForUI::ProcessNextWindowsMessage1"));
345 // If there are sent messages in the queue then PeekMessage internally
346 // dispatches the message and returns false. We return true in this
347 // case to ensure that the message loop peeks again instead of calling
348 // MsgWaitForMultipleObjectsEx again.
349 bool sent_messages_in_queue = false;
350 DWORD queue_status = GetQueueStatus(QS_SENDMESSAGE);
351 if (HIWORD(queue_status) & QS_SENDMESSAGE)
352 sent_messages_in_queue = true;
354 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
355 tracked_objects::ScopedTracker tracking_profile2(
356 FROM_HERE_WITH_EXPLICIT_FUNCTION(
357 "440919 MessagePumpForUI::ProcessNextWindowsMessage2"));
359 MSG msg;
360 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE)
361 return ProcessMessageHelper(msg);
363 return sent_messages_in_queue;
366 bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg) {
367 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
368 tracked_objects::ScopedTracker tracking_profile1(
369 FROM_HERE_WITH_EXPLICIT_FUNCTION(
370 "440919 MessagePumpForUI::ProcessMessageHelper1"));
372 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
373 "message", msg.message);
374 if (WM_QUIT == msg.message) {
375 // Repost the QUIT message so that it will be retrieved by the primary
376 // GetMessage() loop.
377 state_->should_quit = true;
378 PostQuitMessage(static_cast<int>(msg.wParam));
379 return false;
382 // While running our main message pump, we discard kMsgHaveWork messages.
383 if (msg.message == kMsgHaveWork && msg.hwnd == message_hwnd_)
384 return ProcessPumpReplacementMessage();
386 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
387 tracked_objects::ScopedTracker tracking_profile2(
388 FROM_HERE_WITH_EXPLICIT_FUNCTION(
389 "440919 MessagePumpForUI::ProcessMessageHelper2"));
391 if (CallMsgFilter(const_cast<MSG*>(&msg), kMessageFilterCode))
392 return true;
394 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
395 tracked_objects::ScopedTracker tracking_profile3(
396 FROM_HERE_WITH_EXPLICIT_FUNCTION(
397 "440919 MessagePumpForUI::ProcessMessageHelper3"));
399 uint32_t action = MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT;
400 if (state_->dispatcher) {
401 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
402 tracked_objects::ScopedTracker tracking_profile4(
403 FROM_HERE_WITH_EXPLICIT_FUNCTION(
404 "440919 MessagePumpForUI::ProcessMessageHelper4"));
406 action = state_->dispatcher->Dispatch(msg);
408 if (action & MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP)
409 state_->should_quit = true;
410 if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) {
411 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
412 tracked_objects::ScopedTracker tracking_profile5(
413 FROM_HERE_WITH_EXPLICIT_FUNCTION(
414 "440919 MessagePumpForUI::ProcessMessageHelper5"));
416 TranslateMessage(&msg);
418 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
419 tracked_objects::ScopedTracker tracking_profile6(
420 FROM_HERE_WITH_EXPLICIT_FUNCTION(
421 "440919 MessagePumpForUI::ProcessMessageHelper6"));
423 DispatchMessage(&msg);
426 return true;
429 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
430 // When we encounter a kMsgHaveWork message, this method is called to peek
431 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
432 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
433 // a continuous stream of such messages are posted. This method carefully
434 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
435 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
436 // possibly be posted), and finally dispatches that peeked replacement. Note
437 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
439 bool have_message = false;
440 MSG msg;
441 // We should not process all window messages if we are in the context of an
442 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
443 // This is to ensure that these messages are peeked out by the OS modal loop.
444 if (MessageLoop::current()->os_modal_loop()) {
445 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
446 have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) ||
447 PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
448 } else {
449 have_message = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE;
452 DCHECK(!have_message || kMsgHaveWork != msg.message ||
453 msg.hwnd != message_hwnd_);
455 // Since we discarded a kMsgHaveWork message, we must update the flag.
456 int old_have_work = InterlockedExchange(&have_work_, 0);
457 DCHECK(old_have_work);
459 // We don't need a special time slice if we didn't have_message to process.
460 if (!have_message)
461 return false;
463 // Guarantee we'll get another time slice in the case where we go into native
464 // windows code. This ScheduleWork() may hurt performance a tiny bit when
465 // tasks appear very infrequently, but when the event queue is busy, the
466 // kMsgHaveWork events get (percentage wise) rarer and rarer.
467 ScheduleWork();
468 return ProcessMessageHelper(msg);
471 //-----------------------------------------------------------------------------
472 // MessagePumpForIO public:
474 MessagePumpForIO::MessagePumpForIO() {
475 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1));
476 DCHECK(port_.IsValid());
479 MessagePumpForIO::~MessagePumpForIO() {
482 void MessagePumpForIO::ScheduleWork() {
483 if (InterlockedExchange(&have_work_, 1))
484 return; // Someone else continued the pumping.
486 // Make sure the MessagePump does some work for us.
487 BOOL ret = PostQueuedCompletionStatus(port_.Get(), 0,
488 reinterpret_cast<ULONG_PTR>(this),
489 reinterpret_cast<OVERLAPPED*>(this));
490 if (ret)
491 return; // Post worked perfectly.
493 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
494 InterlockedExchange(&have_work_, 0); // Clarify that we didn't succeed.
495 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR,
496 MESSAGE_LOOP_PROBLEM_MAX);
499 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
500 // We know that we can't be blocked right now since this method can only be
501 // called on the same thread as Run, so we only need to update our record of
502 // how long to sleep when we do sleep.
503 delayed_work_time_ = delayed_work_time;
506 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle,
507 IOHandler* handler) {
508 ULONG_PTR key = HandlerToKey(handler, true);
509 HANDLE port = CreateIoCompletionPort(file_handle, port_.Get(), key, 1);
510 DPCHECK(port);
513 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle,
514 IOHandler* handler) {
515 // Job object notifications use the OVERLAPPED pointer to carry the message
516 // data. Mark the completion key correspondingly, so we will not try to
517 // convert OVERLAPPED* to IOContext*.
518 ULONG_PTR key = HandlerToKey(handler, false);
519 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info;
520 info.CompletionKey = reinterpret_cast<void*>(key);
521 info.CompletionPort = port_.Get();
522 return SetInformationJobObject(job_handle,
523 JobObjectAssociateCompletionPortInformation,
524 &info,
525 sizeof(info)) != FALSE;
528 //-----------------------------------------------------------------------------
529 // MessagePumpForIO private:
531 void MessagePumpForIO::DoRunLoop() {
532 for (;;) {
533 // If we do any work, we may create more messages etc., and more work may
534 // possibly be waiting in another task group. When we (for example)
535 // WaitForIOCompletion(), there is a good chance there are still more
536 // messages waiting. On the other hand, when any of these methods return
537 // having done no work, then it is pretty unlikely that calling them
538 // again quickly will find any work to do. Finally, if they all say they
539 // had no work, then it is a good time to consider sleeping (waiting) for
540 // more work.
542 bool more_work_is_plausible = state_->delegate->DoWork();
543 if (state_->should_quit)
544 break;
546 more_work_is_plausible |= WaitForIOCompletion(0, NULL);
547 if (state_->should_quit)
548 break;
550 more_work_is_plausible |=
551 state_->delegate->DoDelayedWork(&delayed_work_time_);
552 if (state_->should_quit)
553 break;
555 if (more_work_is_plausible)
556 continue;
558 more_work_is_plausible = state_->delegate->DoIdleWork();
559 if (state_->should_quit)
560 break;
562 if (more_work_is_plausible)
563 continue;
565 WaitForWork(); // Wait (sleep) until we have work to do again.
569 // Wait until IO completes, up to the time needed by the timer manager to fire
570 // the next set of timers.
571 void MessagePumpForIO::WaitForWork() {
572 // We do not support nested IO message loops. This is to avoid messy
573 // recursion problems.
574 DCHECK_EQ(1, state_->run_depth) << "Cannot nest an IO message loop!";
576 int timeout = GetCurrentDelay();
577 if (timeout < 0) // Negative value means no timers waiting.
578 timeout = INFINITE;
580 WaitForIOCompletion(timeout, NULL);
583 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
584 IOItem item;
585 if (completed_io_.empty() || !MatchCompletedIOItem(filter, &item)) {
586 // We have to ask the system for another IO completion.
587 if (!GetIOItem(timeout, &item))
588 return false;
590 if (ProcessInternalIOItem(item))
591 return true;
594 // If |item.has_valid_io_context| is false then |item.context| does not point
595 // to a context structure, and so should not be dereferenced, although it may
596 // still hold valid non-pointer data.
597 if (!item.has_valid_io_context || item.context->handler) {
598 if (filter && item.handler != filter) {
599 // Save this item for later
600 completed_io_.push_back(item);
601 } else {
602 DCHECK(!item.has_valid_io_context ||
603 (item.context->handler == item.handler));
604 WillProcessIOEvent();
605 item.handler->OnIOCompleted(item.context, item.bytes_transfered,
606 item.error);
607 DidProcessIOEvent();
609 } else {
610 // The handler must be gone by now, just cleanup the mess.
611 delete item.context;
613 return true;
616 // Asks the OS for another IO completion result.
617 bool MessagePumpForIO::GetIOItem(DWORD timeout, IOItem* item) {
618 memset(item, 0, sizeof(*item));
619 ULONG_PTR key = NULL;
620 OVERLAPPED* overlapped = NULL;
621 if (!GetQueuedCompletionStatus(port_.Get(), &item->bytes_transfered, &key,
622 &overlapped, timeout)) {
623 if (!overlapped)
624 return false; // Nothing in the queue.
625 item->error = GetLastError();
626 item->bytes_transfered = 0;
629 item->handler = KeyToHandler(key, &item->has_valid_io_context);
630 item->context = reinterpret_cast<IOContext*>(overlapped);
631 return true;
634 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem& item) {
635 if (this == reinterpret_cast<MessagePumpForIO*>(item.context) &&
636 this == reinterpret_cast<MessagePumpForIO*>(item.handler)) {
637 // This is our internal completion.
638 DCHECK(!item.bytes_transfered);
639 InterlockedExchange(&have_work_, 0);
640 return true;
642 return false;
645 // Returns a completion item that was previously received.
646 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler* filter, IOItem* item) {
647 DCHECK(!completed_io_.empty());
648 for (std::list<IOItem>::iterator it = completed_io_.begin();
649 it != completed_io_.end(); ++it) {
650 if (!filter || it->handler == filter) {
651 *item = *it;
652 completed_io_.erase(it);
653 return true;
656 return false;
659 void MessagePumpForIO::AddIOObserver(IOObserver *obs) {
660 io_observers_.AddObserver(obs);
663 void MessagePumpForIO::RemoveIOObserver(IOObserver *obs) {
664 io_observers_.RemoveObserver(obs);
667 void MessagePumpForIO::WillProcessIOEvent() {
668 FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
671 void MessagePumpForIO::DidProcessIOEvent() {
672 FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
675 // static
676 ULONG_PTR MessagePumpForIO::HandlerToKey(IOHandler* handler,
677 bool has_valid_io_context) {
678 ULONG_PTR key = reinterpret_cast<ULONG_PTR>(handler);
680 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
681 // always cleared. We use the lowest bit to distinguish completion keys with
682 // and without the associated |IOContext|.
683 DCHECK_EQ(key & 1, 0u);
685 // Mark the completion key as context-less.
686 if (!has_valid_io_context)
687 key = key | 1;
688 return key;
691 // static
692 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler(
693 ULONG_PTR key,
694 bool* has_valid_io_context) {
695 *has_valid_io_context = ((key & 1) == 0);
696 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1));
699 } // namespace base