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