OLD | NEW |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "ipc/ipc_sync_channel.h" | 5 #include "ipc/ipc_sync_channel.h" |
6 | 6 |
7 #include <stddef.h> | 7 #include <stddef.h> |
8 #include <stdint.h> | 8 #include <stdint.h> |
9 | 9 |
10 #include <utility> | 10 #include <utility> |
11 | 11 |
12 #include "base/bind.h" | 12 #include "base/bind.h" |
13 #include "base/lazy_instance.h" | 13 #include "base/lazy_instance.h" |
14 #include "base/location.h" | 14 #include "base/location.h" |
15 #include "base/logging.h" | 15 #include "base/logging.h" |
16 #include "base/memory/ptr_util.h" | 16 #include "base/memory/ptr_util.h" |
| 17 #include "base/run_loop.h" |
17 #include "base/synchronization/waitable_event.h" | 18 #include "base/synchronization/waitable_event.h" |
18 #include "base/synchronization/waitable_event_watcher.h" | |
19 #include "base/threading/thread_local.h" | 19 #include "base/threading/thread_local.h" |
20 #include "base/threading/thread_task_runner_handle.h" | 20 #include "base/threading/thread_task_runner_handle.h" |
21 #include "base/trace_event/trace_event.h" | 21 #include "base/trace_event/trace_event.h" |
22 #include "ipc/ipc_channel_factory.h" | 22 #include "ipc/ipc_channel_factory.h" |
23 #include "ipc/ipc_logging.h" | 23 #include "ipc/ipc_logging.h" |
24 #include "ipc/ipc_message_macros.h" | 24 #include "ipc/ipc_message_macros.h" |
25 #include "ipc/ipc_sync_message.h" | 25 #include "ipc/ipc_sync_message.h" |
| 26 #include "mojo/public/cpp/bindings/sync_handle_registry.h" |
26 | 27 |
27 using base::TimeDelta; | 28 using base::TimeDelta; |
28 using base::TimeTicks; | 29 using base::TimeTicks; |
29 using base::WaitableEvent; | 30 using base::WaitableEvent; |
30 | 31 |
31 namespace IPC { | 32 namespace IPC { |
| 33 |
| 34 namespace { |
| 35 |
| 36 // A generic callback used when watching handles synchronously. Sets |*signal| |
| 37 // to true. Also sets |*error| to true in case of an error. |
| 38 void OnSyncHandleReady(bool* signal, bool* error, MojoResult result) { |
| 39 *signal = true; |
| 40 *error = result != MOJO_RESULT_OK; |
| 41 } |
| 42 |
| 43 // A ReadyCallback for use with mojo::Watcher. Ignores the result (DCHECKs, but |
| 44 // is only used in cases where failure should be impossible) and runs |
| 45 // |callback|. |
| 46 void RunOnHandleReady(const base::Closure& callback, MojoResult result) { |
| 47 DCHECK_EQ(result, MOJO_RESULT_OK); |
| 48 callback.Run(); |
| 49 } |
| 50 |
| 51 } // namespace |
| 52 |
| 53 // A lazy thread-local Mojo Event which is always signaled. Used to wake up the |
| 54 // sync waiter when a SyncMessage requires the MessageLoop to be pumped while |
| 55 // waiting for a reply. |
| 56 base::LazyInstance<base::ThreadLocalPointer<mojo::Event>>::Leaky |
| 57 g_pump_messages_event_tls_ptr = LAZY_INSTANCE_INITIALIZER; |
| 58 |
32 // When we're blocked in a Send(), we need to process incoming synchronous | 59 // When we're blocked in a Send(), we need to process incoming synchronous |
33 // messages right away because it could be blocking our reply (either | 60 // messages right away because it could be blocking our reply (either |
34 // directly from the same object we're calling, or indirectly through one or | 61 // directly from the same object we're calling, or indirectly through one or |
35 // more other channels). That means that in SyncContext's OnMessageReceived, | 62 // more other channels). That means that in SyncContext's OnMessageReceived, |
36 // we need to process sync message right away if we're blocked. However a | 63 // we need to process sync message right away if we're blocked. However a |
37 // simple check isn't sufficient, because the listener thread can be in the | 64 // simple check isn't sufficient, because the listener thread can be in the |
38 // process of calling Send. | 65 // process of calling Send. |
39 // To work around this, when SyncChannel filters a sync message, it sets | 66 // To work around this, when SyncChannel filters a sync message, it sets |
40 // an event that the listener thread waits on during its Send() call. This | 67 // an event that the listener thread waits on during its Send() call. This |
41 // allows us to dispatch incoming sync messages when blocked. The race | 68 // allows us to dispatch incoming sync messages when blocked. The race |
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
148 iter++; | 175 iter++; |
149 } | 176 } |
150 } | 177 } |
151 | 178 |
152 if (--listener_count_ == 0) { | 179 if (--listener_count_ == 0) { |
153 DCHECK(lazy_tls_ptr_.Pointer()->Get()); | 180 DCHECK(lazy_tls_ptr_.Pointer()->Get()); |
154 lazy_tls_ptr_.Pointer()->Set(NULL); | 181 lazy_tls_ptr_.Pointer()->Set(NULL); |
155 } | 182 } |
156 } | 183 } |
157 | 184 |
158 WaitableEvent* dispatch_event() { return &dispatch_event_; } | 185 mojo::Event* dispatch_event() { return &dispatch_event_; } |
159 base::SingleThreadTaskRunner* listener_task_runner() { | 186 base::SingleThreadTaskRunner* listener_task_runner() { |
160 return listener_task_runner_.get(); | 187 return listener_task_runner_.get(); |
161 } | 188 } |
162 | 189 |
163 // Holds a pointer to the per-thread ReceivedSyncMsgQueue object. | 190 // Holds a pointer to the per-thread ReceivedSyncMsgQueue object. |
164 static base::LazyInstance<base::ThreadLocalPointer<ReceivedSyncMsgQueue> > | 191 static base::LazyInstance<base::ThreadLocalPointer<ReceivedSyncMsgQueue> > |
165 lazy_tls_ptr_; | 192 lazy_tls_ptr_; |
166 | 193 |
167 // Called on the ipc thread to check if we can unblock any current Send() | 194 // Called on the ipc thread to check if we can unblock any current Send() |
168 // calls based on a queued reply. | 195 // calls based on a queued reply. |
169 void DispatchReplies() { | 196 void DispatchReplies() { |
170 for (size_t i = 0; i < received_replies_.size(); ++i) { | 197 for (size_t i = 0; i < received_replies_.size(); ++i) { |
171 Message* message = received_replies_[i].message; | 198 Message* message = received_replies_[i].message; |
172 if (received_replies_[i].context->TryToUnblockListener(message)) { | 199 if (received_replies_[i].context->TryToUnblockListener(message)) { |
173 delete message; | 200 delete message; |
174 received_replies_.erase(received_replies_.begin() + i); | 201 received_replies_.erase(received_replies_.begin() + i); |
175 return; | 202 return; |
176 } | 203 } |
177 } | 204 } |
178 } | 205 } |
179 | 206 |
180 base::WaitableEventWatcher* top_send_done_watcher() { | 207 mojo::Watcher* top_send_done_watcher() { |
181 return top_send_done_watcher_; | 208 return top_send_done_watcher_; |
182 } | 209 } |
183 | 210 |
184 void set_top_send_done_watcher(base::WaitableEventWatcher* watcher) { | 211 void set_top_send_done_watcher(mojo::Watcher* watcher) { |
185 top_send_done_watcher_ = watcher; | 212 top_send_done_watcher_ = watcher; |
186 } | 213 } |
187 | 214 |
188 private: | 215 private: |
189 friend class base::RefCountedThreadSafe<ReceivedSyncMsgQueue>; | 216 friend class base::RefCountedThreadSafe<ReceivedSyncMsgQueue>; |
190 | 217 |
191 // See the comment in SyncChannel::SyncChannel for why this event is created | 218 // See the comment in SyncChannel::SyncChannel for why this event is created |
192 // as manual reset. | 219 // as manual reset. |
193 ReceivedSyncMsgQueue() | 220 ReceivedSyncMsgQueue() |
194 : message_queue_version_(0), | 221 : message_queue_version_(0), |
195 dispatch_event_(base::WaitableEvent::ResetPolicy::MANUAL, | |
196 base::WaitableEvent::InitialState::NOT_SIGNALED), | |
197 listener_task_runner_(base::ThreadTaskRunnerHandle::Get()), | 222 listener_task_runner_(base::ThreadTaskRunnerHandle::Get()), |
198 task_pending_(false), | 223 task_pending_(false), |
199 listener_count_(0), | 224 listener_count_(0), |
200 top_send_done_watcher_(NULL) {} | 225 top_send_done_watcher_(NULL) {} |
201 | 226 |
202 ~ReceivedSyncMsgQueue() {} | 227 ~ReceivedSyncMsgQueue() {} |
203 | 228 |
204 // Holds information about a queued synchronous message or reply. | 229 // Holds information about a queued synchronous message or reply. |
205 struct QueuedMessage { | 230 struct QueuedMessage { |
206 QueuedMessage(Message* m, SyncContext* c) : message(m), context(c) { } | 231 QueuedMessage(Message* m, SyncContext* c) : message(m), context(c) { } |
207 Message* message; | 232 Message* message; |
208 scoped_refptr<SyncChannel::SyncContext> context; | 233 scoped_refptr<SyncChannel::SyncContext> context; |
209 }; | 234 }; |
210 | 235 |
211 typedef std::list<QueuedMessage> SyncMessageQueue; | 236 typedef std::list<QueuedMessage> SyncMessageQueue; |
212 SyncMessageQueue message_queue_; | 237 SyncMessageQueue message_queue_; |
213 uint32_t message_queue_version_; // Used to signal DispatchMessages to rescan | 238 uint32_t message_queue_version_; // Used to signal DispatchMessages to rescan |
214 | 239 |
215 std::vector<QueuedMessage> received_replies_; | 240 std::vector<QueuedMessage> received_replies_; |
216 | 241 |
217 // Set when we got a synchronous message that we must respond to as the | 242 // Signaled when we get a synchronous message that we must respond to, as the |
218 // sender needs its reply before it can reply to our original synchronous | 243 // sender needs its reply before it can reply to our original synchronous |
219 // message. | 244 // message. |
220 WaitableEvent dispatch_event_; | 245 mojo::Event dispatch_event_; |
221 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner_; | 246 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner_; |
222 base::Lock message_lock_; | 247 base::Lock message_lock_; |
223 bool task_pending_; | 248 bool task_pending_; |
224 int listener_count_; | 249 int listener_count_; |
225 | 250 |
226 // The current send done event watcher for this thread. Used to maintain | 251 // The current send done handle watcher for this thread. Used to maintain |
227 // a local global stack of send done watchers to ensure that nested sync | 252 // a thread-local stack of send done watchers to ensure that nested sync |
228 // message loops complete correctly. | 253 // message loops complete correctly. |
229 base::WaitableEventWatcher* top_send_done_watcher_; | 254 mojo::Watcher* top_send_done_watcher_; |
230 }; | 255 }; |
231 | 256 |
232 base::LazyInstance<base::ThreadLocalPointer<SyncChannel::ReceivedSyncMsgQueue> > | 257 base::LazyInstance<base::ThreadLocalPointer<SyncChannel::ReceivedSyncMsgQueue> > |
233 SyncChannel::ReceivedSyncMsgQueue::lazy_tls_ptr_ = | 258 SyncChannel::ReceivedSyncMsgQueue::lazy_tls_ptr_ = |
234 LAZY_INSTANCE_INITIALIZER; | 259 LAZY_INSTANCE_INITIALIZER; |
235 | 260 |
236 SyncChannel::SyncContext::SyncContext( | 261 SyncChannel::SyncContext::SyncContext( |
237 Listener* listener, | 262 Listener* listener, |
238 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner, | 263 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner, |
239 WaitableEvent* shutdown_event) | 264 WaitableEvent* shutdown_event) |
(...skipping 15 matching lines...) Expand all Loading... |
255 // Create the tracking information for this message. This object is stored | 280 // Create the tracking information for this message. This object is stored |
256 // by value since all members are pointers that are cheap to copy. These | 281 // by value since all members are pointers that are cheap to copy. These |
257 // pointers are cleaned up in the Pop() function. | 282 // pointers are cleaned up in the Pop() function. |
258 // | 283 // |
259 // The event is created as manual reset because in between Signal and | 284 // The event is created as manual reset because in between Signal and |
260 // OnObjectSignalled, another Send can happen which would stop the watcher | 285 // OnObjectSignalled, another Send can happen which would stop the watcher |
261 // from being called. The event would get watched later, when the nested | 286 // from being called. The event would get watched later, when the nested |
262 // Send completes, so the event will need to remain set. | 287 // Send completes, so the event will need to remain set. |
263 PendingSyncMsg pending( | 288 PendingSyncMsg pending( |
264 SyncMessage::GetMessageId(*sync_msg), sync_msg->GetReplyDeserializer(), | 289 SyncMessage::GetMessageId(*sync_msg), sync_msg->GetReplyDeserializer(), |
265 new WaitableEvent(base::WaitableEvent::ResetPolicy::MANUAL, | 290 new mojo::Event); |
266 base::WaitableEvent::InitialState::NOT_SIGNALED)); | |
267 base::AutoLock auto_lock(deserializers_lock_); | 291 base::AutoLock auto_lock(deserializers_lock_); |
268 deserializers_.push_back(pending); | 292 deserializers_.push_back(pending); |
269 } | 293 } |
270 | 294 |
271 bool SyncChannel::SyncContext::Pop() { | 295 bool SyncChannel::SyncContext::Pop() { |
272 bool result; | 296 bool result; |
273 { | 297 { |
274 base::AutoLock auto_lock(deserializers_lock_); | 298 base::AutoLock auto_lock(deserializers_lock_); |
275 PendingSyncMsg msg = deserializers_.back(); | 299 PendingSyncMsg msg = deserializers_.back(); |
276 delete msg.deserializer; | 300 delete msg.deserializer; |
277 delete msg.done_event; | 301 delete msg.done_event; |
278 msg.done_event = NULL; | 302 msg.done_event = nullptr; |
279 deserializers_.pop_back(); | 303 deserializers_.pop_back(); |
280 result = msg.send_result; | 304 result = msg.send_result; |
281 } | 305 } |
282 | 306 |
283 // We got a reply to a synchronous Send() call that's blocking the listener | 307 // We got a reply to a synchronous Send() call that's blocking the listener |
284 // thread. However, further down the call stack there could be another | 308 // thread. However, further down the call stack there could be another |
285 // blocking Send() call, whose reply we received after we made this last | 309 // blocking Send() call, whose reply we received after we made this last |
286 // Send() call. So check if we have any queued replies available that | 310 // Send() call. So check if we have any queued replies available that |
287 // can now unblock the listener thread. | 311 // can now unblock the listener thread. |
288 ipc_task_runner()->PostTask( | 312 ipc_task_runner()->PostTask( |
289 FROM_HERE, base::Bind(&ReceivedSyncMsgQueue::DispatchReplies, | 313 FROM_HERE, base::Bind(&ReceivedSyncMsgQueue::DispatchReplies, |
290 received_sync_msgs_.get())); | 314 received_sync_msgs_.get())); |
291 | 315 |
292 return result; | 316 return result; |
293 } | 317 } |
294 | 318 |
295 WaitableEvent* SyncChannel::SyncContext::GetSendDoneEvent() { | 319 mojo::Event* SyncChannel::SyncContext::GetSendDoneEvent() { |
296 base::AutoLock auto_lock(deserializers_lock_); | 320 base::AutoLock auto_lock(deserializers_lock_); |
297 return deserializers_.back().done_event; | 321 return deserializers_.back().done_event; |
298 } | 322 } |
299 | 323 |
300 WaitableEvent* SyncChannel::SyncContext::GetDispatchEvent() { | 324 mojo::Event* SyncChannel::SyncContext::GetDispatchEvent() { |
301 return received_sync_msgs_->dispatch_event(); | 325 return received_sync_msgs_->dispatch_event(); |
302 } | 326 } |
303 | 327 |
304 void SyncChannel::SyncContext::DispatchMessages() { | 328 void SyncChannel::SyncContext::DispatchMessages() { |
305 received_sync_msgs_->DispatchMessages(this); | 329 received_sync_msgs_->DispatchMessages(this); |
306 } | 330 } |
307 | 331 |
308 bool SyncChannel::SyncContext::TryToUnblockListener(const Message* msg) { | 332 bool SyncChannel::SyncContext::TryToUnblockListener(const Message* msg) { |
309 base::AutoLock auto_lock(deserializers_lock_); | 333 base::AutoLock auto_lock(deserializers_lock_); |
310 if (deserializers_.empty() || | 334 if (deserializers_.empty() || |
311 !SyncMessage::IsMessageReplyTo(*msg, deserializers_.back().id)) { | 335 !SyncMessage::IsMessageReplyTo(*msg, deserializers_.back().id)) { |
312 return false; | 336 return false; |
313 } | 337 } |
314 | 338 |
315 if (!msg->is_reply_error()) { | 339 if (!msg->is_reply_error()) { |
316 bool send_result = deserializers_.back().deserializer-> | 340 bool send_result = deserializers_.back().deserializer-> |
317 SerializeOutputParameters(*msg); | 341 SerializeOutputParameters(*msg); |
318 deserializers_.back().send_result = send_result; | 342 deserializers_.back().send_result = send_result; |
319 DVLOG_IF(1, !send_result) << "Couldn't deserialize reply message"; | 343 DVLOG_IF(1, !send_result) << "Couldn't deserialize reply message"; |
320 } else { | 344 } else { |
321 DVLOG(1) << "Received error reply"; | 345 DVLOG(1) << "Received error reply"; |
322 } | 346 } |
323 | 347 |
324 base::WaitableEvent* done_event = deserializers_.back().done_event; | 348 mojo::Event* done_event = deserializers_.back().done_event; |
325 TRACE_EVENT_FLOW_BEGIN0( | 349 TRACE_EVENT_FLOW_BEGIN0( |
326 TRACE_DISABLED_BY_DEFAULT("ipc.flow"), | 350 TRACE_DISABLED_BY_DEFAULT("ipc.flow"), |
327 "SyncChannel::SyncContext::TryToUnblockListener", done_event); | 351 "SyncChannel::SyncContext::TryToUnblockListener", done_event); |
328 | 352 |
329 done_event->Signal(); | 353 done_event->Signal(); |
330 | 354 |
331 return true; | 355 return true; |
332 } | 356 } |
333 | 357 |
334 void SyncChannel::SyncContext::Clear() { | 358 void SyncChannel::SyncContext::Clear() { |
(...skipping 25 matching lines...) Expand all Loading... |
360 | 384 |
361 void SyncChannel::SyncContext::OnChannelError() { | 385 void SyncChannel::SyncContext::OnChannelError() { |
362 CancelPendingSends(); | 386 CancelPendingSends(); |
363 shutdown_watcher_.StopWatching(); | 387 shutdown_watcher_.StopWatching(); |
364 Context::OnChannelError(); | 388 Context::OnChannelError(); |
365 } | 389 } |
366 | 390 |
367 void SyncChannel::SyncContext::OnChannelOpened() { | 391 void SyncChannel::SyncContext::OnChannelOpened() { |
368 shutdown_watcher_.StartWatching( | 392 shutdown_watcher_.StartWatching( |
369 shutdown_event_, | 393 shutdown_event_, |
370 base::Bind(&SyncChannel::SyncContext::OnWaitableEventSignaled, | 394 base::Bind(&SyncChannel::SyncContext::OnShutdownEventSignaled, |
371 base::Unretained(this))); | 395 base::Unretained(this))); |
372 Context::OnChannelOpened(); | 396 Context::OnChannelOpened(); |
373 } | 397 } |
374 | 398 |
375 void SyncChannel::SyncContext::OnChannelClosed() { | 399 void SyncChannel::SyncContext::OnChannelClosed() { |
376 CancelPendingSends(); | 400 CancelPendingSends(); |
377 shutdown_watcher_.StopWatching(); | 401 shutdown_watcher_.StopWatching(); |
378 Context::OnChannelClosed(); | 402 Context::OnChannelClosed(); |
379 } | 403 } |
380 | 404 |
381 void SyncChannel::SyncContext::CancelPendingSends() { | 405 void SyncChannel::SyncContext::CancelPendingSends() { |
382 base::AutoLock auto_lock(deserializers_lock_); | 406 base::AutoLock auto_lock(deserializers_lock_); |
383 PendingSyncMessageQueue::iterator iter; | 407 PendingSyncMessageQueue::iterator iter; |
384 DVLOG(1) << "Canceling pending sends"; | 408 DVLOG(1) << "Canceling pending sends"; |
385 for (iter = deserializers_.begin(); iter != deserializers_.end(); iter++) { | 409 for (iter = deserializers_.begin(); iter != deserializers_.end(); iter++) { |
386 TRACE_EVENT_FLOW_BEGIN0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), | 410 TRACE_EVENT_FLOW_BEGIN0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), |
387 "SyncChannel::SyncContext::CancelPendingSends", | 411 "SyncChannel::SyncContext::CancelPendingSends", |
388 iter->done_event); | 412 iter->done_event); |
389 iter->done_event->Signal(); | 413 iter->done_event->Signal(); |
390 } | 414 } |
391 } | 415 } |
392 | 416 |
393 void SyncChannel::SyncContext::OnWaitableEventSignaled(WaitableEvent* event) { | 417 void SyncChannel::SyncContext::OnShutdownEventSignaled(WaitableEvent* event) { |
394 if (event == shutdown_event_) { | 418 DCHECK_EQ(event, shutdown_event_); |
395 // Process shut down before we can get a reply to a synchronous message. | |
396 // Cancel pending Send calls, which will end up setting the send done event. | |
397 CancelPendingSends(); | |
398 } else { | |
399 // We got the reply, timed out or the process shutdown. | |
400 DCHECK_EQ(GetSendDoneEvent(), event); | |
401 base::MessageLoop::current()->QuitNow(); | |
402 } | |
403 } | |
404 | 419 |
405 base::WaitableEventWatcher::EventCallback | 420 // Process shut down before we can get a reply to a synchronous message. |
406 SyncChannel::SyncContext::MakeWaitableEventCallback() { | 421 // Cancel pending Send calls, which will end up setting the send done event. |
407 return base::Bind(&SyncChannel::SyncContext::OnWaitableEventSignaled, this); | 422 CancelPendingSends(); |
408 } | 423 } |
409 | 424 |
410 // static | 425 // static |
411 std::unique_ptr<SyncChannel> SyncChannel::Create( | 426 std::unique_ptr<SyncChannel> SyncChannel::Create( |
412 const IPC::ChannelHandle& channel_handle, | 427 const IPC::ChannelHandle& channel_handle, |
413 Channel::Mode mode, | 428 Channel::Mode mode, |
414 Listener* listener, | 429 Listener* listener, |
415 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner, | 430 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner, |
416 bool create_pipe_now, | 431 bool create_pipe_now, |
417 base::WaitableEvent* shutdown_event) { | 432 base::WaitableEvent* shutdown_event) { |
(...skipping 23 matching lines...) Expand all Loading... |
441 WaitableEvent* shutdown_event) { | 456 WaitableEvent* shutdown_event) { |
442 return base::WrapUnique( | 457 return base::WrapUnique( |
443 new SyncChannel(listener, ipc_task_runner, shutdown_event)); | 458 new SyncChannel(listener, ipc_task_runner, shutdown_event)); |
444 } | 459 } |
445 | 460 |
446 SyncChannel::SyncChannel( | 461 SyncChannel::SyncChannel( |
447 Listener* listener, | 462 Listener* listener, |
448 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner, | 463 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner, |
449 WaitableEvent* shutdown_event) | 464 WaitableEvent* shutdown_event) |
450 : ChannelProxy(new SyncContext(listener, ipc_task_runner, shutdown_event)) { | 465 : ChannelProxy(new SyncContext(listener, ipc_task_runner, shutdown_event)) { |
| 466 if (!g_pump_messages_event_tls_ptr.Pointer()->Get()) { |
| 467 mojo::Event* pump_messages_event = new mojo::Event; |
| 468 pump_messages_event->Signal(); |
| 469 g_pump_messages_event_tls_ptr.Pointer()->Set(pump_messages_event); |
| 470 } |
| 471 |
451 // The current (listener) thread must be distinct from the IPC thread, or else | 472 // The current (listener) thread must be distinct from the IPC thread, or else |
452 // sending synchronous messages will deadlock. | 473 // sending synchronous messages will deadlock. |
453 DCHECK_NE(ipc_task_runner.get(), base::ThreadTaskRunnerHandle::Get().get()); | 474 DCHECK_NE(ipc_task_runner.get(), base::ThreadTaskRunnerHandle::Get().get()); |
454 StartWatching(); | 475 StartWatching(); |
455 } | 476 } |
456 | 477 |
457 SyncChannel::~SyncChannel() { | 478 SyncChannel::~SyncChannel() { |
458 } | 479 } |
459 | 480 |
460 void SyncChannel::SetRestrictDispatchChannelGroup(int group) { | 481 void SyncChannel::SetRestrictDispatchChannelGroup(int group) { |
(...skipping 27 matching lines...) Expand all Loading... |
488 | 509 |
489 // *this* might get deleted in WaitForReply. | 510 // *this* might get deleted in WaitForReply. |
490 scoped_refptr<SyncContext> context(sync_context()); | 511 scoped_refptr<SyncContext> context(sync_context()); |
491 if (context->shutdown_event()->IsSignaled()) { | 512 if (context->shutdown_event()->IsSignaled()) { |
492 DVLOG(1) << "shutdown event is signaled"; | 513 DVLOG(1) << "shutdown event is signaled"; |
493 delete message; | 514 delete message; |
494 return false; | 515 return false; |
495 } | 516 } |
496 | 517 |
497 SyncMessage* sync_msg = static_cast<SyncMessage*>(message); | 518 SyncMessage* sync_msg = static_cast<SyncMessage*>(message); |
| 519 bool pump_messages = sync_msg->ShouldPumpMessages(); |
498 context->Push(sync_msg); | 520 context->Push(sync_msg); |
499 WaitableEvent* pump_messages_event = sync_msg->pump_messages_event(); | |
500 | 521 |
501 ChannelProxy::Send(message); | 522 ChannelProxy::Send(message); |
502 | 523 |
503 // Wait for reply, or for any other incoming synchronous messages. | 524 // Wait for reply, or for any other incoming synchronous messages. |
504 // *this* might get deleted, so only call static functions at this point. | 525 // *this* might get deleted, so only call static functions at this point. |
505 WaitForReply(context.get(), pump_messages_event); | 526 WaitForReply(context.get(), pump_messages); |
506 | 527 |
507 TRACE_EVENT_FLOW_END0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), | 528 TRACE_EVENT_FLOW_END0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), |
508 "SyncChannel::Send", context->GetSendDoneEvent()); | 529 "SyncChannel::Send", context->GetSendDoneEvent()); |
509 | 530 |
510 return context->Pop(); | 531 return context->Pop(); |
511 } | 532 } |
512 | 533 |
513 void SyncChannel::WaitForReply( | 534 void SyncChannel::WaitForReply(SyncContext* context, bool pump_messages) { |
514 SyncContext* context, WaitableEvent* pump_messages_event) { | |
515 context->DispatchMessages(); | 535 context->DispatchMessages(); |
| 536 |
| 537 mojo::Event* pump_messages_event = nullptr; |
| 538 if (pump_messages) { |
| 539 pump_messages_event = g_pump_messages_event_tls_ptr.Pointer()->Get(); |
| 540 DCHECK(pump_messages_event); |
| 541 } |
| 542 |
| 543 scoped_refptr<mojo::SyncHandleRegistry> registry = |
| 544 mojo::SyncHandleRegistry::current(); |
| 545 |
516 while (true) { | 546 while (true) { |
517 WaitableEvent* objects[] = { | 547 bool dispatch = false; |
518 context->GetDispatchEvent(), | 548 bool send_done = false; |
519 context->GetSendDoneEvent(), | 549 bool should_pump_messages = false; |
520 pump_messages_event | 550 bool error = false; |
521 }; | 551 registry->RegisterHandle(context->GetDispatchEvent()->GetHandle(), |
| 552 MOJO_HANDLE_SIGNAL_READABLE, |
| 553 base::Bind(&OnSyncHandleReady, &dispatch, &error)); |
| 554 registry->RegisterHandle( |
| 555 context->GetSendDoneEvent()->GetHandle(), |
| 556 MOJO_HANDLE_SIGNAL_READABLE, |
| 557 base::Bind(&OnSyncHandleReady, &send_done, &error)); |
| 558 if (pump_messages_event) { |
| 559 registry->RegisterHandle( |
| 560 pump_messages_event->GetHandle(), MOJO_HANDLE_SIGNAL_READABLE, |
| 561 base::Bind(&OnSyncHandleReady, &should_pump_messages, &error)); |
| 562 } |
522 | 563 |
523 unsigned count = pump_messages_event ? 3: 2; | 564 const bool* stop_flags[] = { &dispatch, &send_done, &should_pump_messages }; |
524 size_t result = WaitableEvent::WaitMany(objects, count); | 565 bool result = registry->WatchAllHandles(stop_flags, 3); |
525 if (result == 0 /* dispatch event */) { | 566 DCHECK(result); |
| 567 DCHECK(!error); |
| 568 |
| 569 registry->UnregisterHandle(context->GetDispatchEvent()->GetHandle()); |
| 570 registry->UnregisterHandle(context->GetSendDoneEvent()->GetHandle()); |
| 571 if (pump_messages_event) |
| 572 registry->UnregisterHandle(pump_messages_event->GetHandle()); |
| 573 |
| 574 if (dispatch) { |
526 // We're waiting for a reply, but we received a blocking synchronous | 575 // We're waiting for a reply, but we received a blocking synchronous |
527 // call. We must process it or otherwise a deadlock might occur. | 576 // call. We must process it or otherwise a deadlock might occur. |
528 context->GetDispatchEvent()->Reset(); | 577 context->GetDispatchEvent()->Reset(); |
529 context->DispatchMessages(); | 578 context->DispatchMessages(); |
530 continue; | 579 continue; |
531 } | 580 } |
532 | 581 |
533 if (result == 2 /* pump_messages_event */) | 582 DCHECK(send_done || should_pump_messages); |
| 583 |
| 584 if (should_pump_messages) |
534 WaitForReplyWithNestedMessageLoop(context); // Run a nested message loop. | 585 WaitForReplyWithNestedMessageLoop(context); // Run a nested message loop. |
535 | 586 |
536 break; | 587 break; |
537 } | 588 } |
538 } | 589 } |
539 | 590 |
540 void SyncChannel::WaitForReplyWithNestedMessageLoop(SyncContext* context) { | 591 void SyncChannel::WaitForReplyWithNestedMessageLoop(SyncContext* context) { |
541 base::WaitableEventWatcher send_done_watcher; | 592 mojo::Watcher send_done_watcher; |
542 | 593 |
543 ReceivedSyncMsgQueue* sync_msg_queue = context->received_sync_msgs(); | 594 ReceivedSyncMsgQueue* sync_msg_queue = context->received_sync_msgs(); |
544 DCHECK(sync_msg_queue != NULL); | 595 DCHECK_NE(sync_msg_queue, nullptr); |
545 | 596 |
546 base::WaitableEventWatcher* old_send_done_event_watcher = | 597 mojo::Watcher* old_watcher = sync_msg_queue->top_send_done_watcher(); |
547 sync_msg_queue->top_send_done_watcher(); | 598 mojo::Handle old_handle(mojo::kInvalidHandleValue); |
| 599 mojo::Watcher::ReadyCallback old_callback; |
548 | 600 |
549 base::WaitableEventWatcher::EventCallback old_callback; | 601 // Maintain a thread-local stack of watchers to ensure nested calls complete |
550 base::WaitableEvent* old_event = NULL; | 602 // in the correct sequence, i.e. the outermost call completes first, etc. |
551 | 603 if (old_watcher) { |
552 // Maintain a local global stack of send done delegates to ensure that | 604 old_callback = old_watcher->ready_callback(); |
553 // nested sync calls complete in the correct sequence, i.e. the | 605 old_handle = old_watcher->handle(); |
554 // outermost call completes first, etc. | 606 old_watcher->Cancel(); |
555 if (old_send_done_event_watcher) { | |
556 old_callback = old_send_done_event_watcher->callback(); | |
557 old_event = old_send_done_event_watcher->GetWatchedEvent(); | |
558 old_send_done_event_watcher->StopWatching(); | |
559 } | 607 } |
560 | 608 |
561 sync_msg_queue->set_top_send_done_watcher(&send_done_watcher); | 609 sync_msg_queue->set_top_send_done_watcher(&send_done_watcher); |
562 | 610 |
563 send_done_watcher.StartWatching(context->GetSendDoneEvent(), | 611 { |
564 context->MakeWaitableEventCallback()); | 612 base::RunLoop nested_loop; |
| 613 send_done_watcher.Start( |
| 614 context->GetSendDoneEvent()->GetHandle(), MOJO_HANDLE_SIGNAL_READABLE, |
| 615 base::Bind(&RunOnHandleReady, nested_loop.QuitClosure())); |
565 | 616 |
566 { | |
567 base::MessageLoop::ScopedNestableTaskAllower allow( | 617 base::MessageLoop::ScopedNestableTaskAllower allow( |
568 base::MessageLoop::current()); | 618 base::MessageLoop::current()); |
569 base::MessageLoop::current()->Run(); | 619 nested_loop.Run(); |
| 620 send_done_watcher.Cancel(); |
570 } | 621 } |
571 | 622 |
572 sync_msg_queue->set_top_send_done_watcher(old_send_done_event_watcher); | 623 sync_msg_queue->set_top_send_done_watcher(old_watcher); |
573 if (old_send_done_event_watcher && old_event) { | 624 if (old_watcher) |
574 old_send_done_event_watcher->StartWatching(old_event, old_callback); | 625 old_watcher->Start(old_handle, MOJO_HANDLE_SIGNAL_READABLE, old_callback); |
575 } | |
576 } | 626 } |
577 | 627 |
578 void SyncChannel::OnWaitableEventSignaled(WaitableEvent* event) { | 628 void SyncChannel::OnDispatchHandleReady(MojoResult result) { |
579 DCHECK(event == sync_context()->GetDispatchEvent()); | 629 DCHECK_EQ(result, MOJO_RESULT_OK); |
580 // The call to DispatchMessages might delete this object, so reregister | 630 sync_context()->GetDispatchEvent()->Reset(); |
581 // the object watcher first. | |
582 event->Reset(); | |
583 dispatch_watcher_.StartWatching(event, dispatch_watcher_callback_); | |
584 sync_context()->DispatchMessages(); | 631 sync_context()->DispatchMessages(); |
585 } | 632 } |
586 | 633 |
587 void SyncChannel::StartWatching() { | 634 void SyncChannel::StartWatching() { |
588 // Ideally we only want to watch this object when running a nested message | 635 // Ideally we only want to watch this object when running a nested message |
589 // loop. However, we don't know when it exits if there's another nested | 636 // loop. However, we don't know when it exits if there's another nested |
590 // message loop running under it or not, so we wouldn't know whether to | 637 // message loop running under it or not, so we wouldn't know whether to |
591 // stop or keep watching. So we always watch it, and create the event as | 638 // stop or keep watching. So we always watch it. |
592 // manual reset since the object watcher might otherwise reset the event | 639 dispatch_watcher_.Start(sync_context()->GetDispatchEvent()->GetHandle(), |
593 // when we're doing a WaitMany. | 640 MOJO_HANDLE_SIGNAL_READABLE, |
594 dispatch_watcher_callback_ = | 641 base::Bind(&SyncChannel::OnDispatchHandleReady, |
595 base::Bind(&SyncChannel::OnWaitableEventSignaled, | 642 base::Unretained(this))); |
596 base::Unretained(this)); | |
597 dispatch_watcher_.StartWatching(sync_context()->GetDispatchEvent(), | |
598 dispatch_watcher_callback_); | |
599 } | 643 } |
600 | 644 |
601 void SyncChannel::OnChannelInit() { | 645 void SyncChannel::OnChannelInit() { |
602 for (const auto& filter : pre_init_sync_message_filters_) { | 646 for (const auto& filter : pre_init_sync_message_filters_) { |
603 filter->set_is_channel_send_thread_safe( | 647 filter->set_is_channel_send_thread_safe( |
604 context()->IsChannelSendThreadSafe()); | 648 context()->IsChannelSendThreadSafe()); |
605 } | 649 } |
606 pre_init_sync_message_filters_.clear(); | 650 pre_init_sync_message_filters_.clear(); |
607 } | 651 } |
608 | 652 |
(...skipping 23 matching lines...) Expand all Loading... |
632 TRACE_EVENT2("ipc", "SyncChannel::SendOnIPCThread", | 676 TRACE_EVENT2("ipc", "SyncChannel::SendOnIPCThread", |
633 "class", IPC_MESSAGE_ID_CLASS(message->type()), | 677 "class", IPC_MESSAGE_ID_CLASS(message->type()), |
634 "line", IPC_MESSAGE_ID_LINE(message->type())); | 678 "line", IPC_MESSAGE_ID_LINE(message->type())); |
635 #endif | 679 #endif |
636 if (!message->is_sync()) | 680 if (!message->is_sync()) |
637 return ChannelProxy::SendOnIPCThread(std::move(message)); | 681 return ChannelProxy::SendOnIPCThread(std::move(message)); |
638 return Send(message.release()); | 682 return Send(message.release()); |
639 } | 683 } |
640 | 684 |
641 } // namespace IPC | 685 } // namespace IPC |
OLD | NEW |