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