1 // Copyright 2012 The Chromium Authors
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 "ipc/ipc_sync_channel.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <memory>
11 #include <utility>
12
13 #include "base/functional/bind.h"
14 #include "base/location.h"
15 #include "base/logging.h"
16 #include "base/memory/ptr_util.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/run_loop.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "base/task/sequenced_task_runner.h"
21 #include "base/task/single_thread_task_runner.h"
22 #include "base/trace_event/trace_event.h"
23 #include "build/build_config.h"
24 #include "ipc/ipc_channel_factory.h"
25 #include "ipc/ipc_logging.h"
26 #include "ipc/ipc_message.h"
27 #include "ipc/ipc_message_macros.h"
28 #include "ipc/ipc_sync_message.h"
29 #include "mojo/public/cpp/bindings/sync_event_watcher.h"
30 #include "third_party/abseil-cpp/absl/base/attributes.h"
31
32 #if !BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
33 #include "ipc/trace_ipc_message.h"
34 #endif
35
36 using base::WaitableEvent;
37
38 namespace IPC {
39
40 namespace {
41
42 // A generic callback used when watching handles synchronously. Sets |*signal|
43 // to true.
OnEventReady(bool * signal)44 void OnEventReady(bool* signal) {
45 *signal = true;
46 }
47
48 // Holds a pointer to the per-thread ReceivedSyncMsgQueue object.
49 ABSL_CONST_INIT thread_local SyncChannel::ReceivedSyncMsgQueue* received_queue =
50 nullptr;
51
52 } // namespace
53
54 // When we're blocked in a Send(), we need to process incoming synchronous
55 // messages right away because it could be blocking our reply (either
56 // directly from the same object we're calling, or indirectly through one or
57 // more other channels). That means that in SyncContext's OnMessageReceived,
58 // we need to process sync message right away if we're blocked. However a
59 // simple check isn't sufficient, because the listener thread can be in the
60 // process of calling Send.
61 // To work around this, when SyncChannel filters a sync message, it sets
62 // an event that the listener thread waits on during its Send() call. This
63 // allows us to dispatch incoming sync messages when blocked. The race
64 // condition is handled because if Send is in the process of being called, it
65 // will check the event. In case the listener thread isn't sending a message,
66 // we queue a task on the listener thread to dispatch the received messages.
67 // The messages are stored in this queue object that's shared among all
68 // SyncChannel objects on the same thread (since one object can receive a
69 // sync message while another one is blocked).
70
71 class SyncChannel::ReceivedSyncMsgQueue :
72 public base::RefCountedThreadSafe<ReceivedSyncMsgQueue> {
73 public:
74 // Returns the ReceivedSyncMsgQueue instance for this thread, creating one
75 // if necessary. Call RemoveContext on the same thread when done.
AddContext()76 static ReceivedSyncMsgQueue* AddContext() {
77 // We want one ReceivedSyncMsgQueue per listener thread (i.e. since multiple
78 // SyncChannel objects can block the same thread).
79 if (!received_queue) {
80 received_queue = new ReceivedSyncMsgQueue();
81 }
82 ++received_queue->listener_count_;
83 return received_queue;
84 }
85
86 // Prevents messages from being dispatched immediately when the dispatch event
87 // is signaled. Instead, |*dispatch_flag| will be set.
BlockDispatch(bool * dispatch_flag)88 void BlockDispatch(bool* dispatch_flag) { dispatch_flag_ = dispatch_flag; }
89
90 // Allows messages to be dispatched immediately when the dispatch event is
91 // signaled.
UnblockDispatch()92 void UnblockDispatch() { dispatch_flag_ = nullptr; }
93
94 // Called on IPC thread when a synchronous message or reply arrives.
QueueMessage(const Message & msg,SyncChannel::SyncContext * context)95 void QueueMessage(const Message& msg, SyncChannel::SyncContext* context) {
96 bool was_task_pending;
97 {
98 base::AutoLock auto_lock(message_lock_);
99
100 was_task_pending = task_pending_;
101 task_pending_ = true;
102
103 // We set the event in case the listener thread is blocked (or is about
104 // to). In case it's not, the PostTask dispatches the messages.
105 message_queue_.push_back({std::make_unique<Message>(msg), context});
106 message_queue_version_++;
107 }
108
109 dispatch_event_.Signal();
110 if (!was_task_pending) {
111 listener_task_runner_->PostTask(
112 FROM_HERE, base::BindOnce(&ReceivedSyncMsgQueue::DispatchMessagesTask,
113 this, base::RetainedRef(context)));
114 }
115 }
116
QueueReply(const Message & msg,SyncChannel::SyncContext * context)117 void QueueReply(const Message &msg, SyncChannel::SyncContext* context) {
118 received_replies_.push_back({std::make_unique<Message>(msg), context});
119 }
120
121 // Called on the listener's thread to process any queues synchronous
122 // messages.
DispatchMessagesTask(SyncContext * context)123 void DispatchMessagesTask(SyncContext* context) {
124 {
125 base::AutoLock auto_lock(message_lock_);
126 task_pending_ = false;
127 }
128 context->DispatchMessages();
129 }
130
131 // Dispatches any queued incoming sync messages. If |dispatching_context| is
132 // not null, messages which target a restricted dispatch channel will only be
133 // dispatched if |dispatching_context| belongs to the same restricted dispatch
134 // group as that channel. If |dispatching_context| is null, all queued
135 // messages are dispatched.
DispatchMessages(SyncContext * dispatching_context)136 void DispatchMessages(SyncContext* dispatching_context) {
137 bool first_time = true;
138 uint32_t expected_version = 0;
139 SyncMessageQueue::iterator it;
140 while (true) {
141 std::unique_ptr<Message> message;
142 scoped_refptr<SyncChannel::SyncContext> context;
143 {
144 base::AutoLock auto_lock(message_lock_);
145 if (first_time || message_queue_version_ != expected_version) {
146 it = message_queue_.begin();
147 first_time = false;
148 }
149 for (; it != message_queue_.end(); it++) {
150 int message_group = it->context->restrict_dispatch_group();
151 if (message_group == kRestrictDispatchGroup_None ||
152 (dispatching_context &&
153 message_group ==
154 dispatching_context->restrict_dispatch_group())) {
155 message = std::move(it->message);
156 context = std::move(it->context);
157 it = message_queue_.erase(it);
158 message_queue_version_++;
159 expected_version = message_queue_version_;
160 break;
161 }
162 }
163 }
164 if (!message) {
165 break;
166 }
167 context->OnDispatchMessage(*message);
168 }
169 }
170
171 // SyncChannel calls this in its destructor.
RemoveContext(SyncContext * context)172 void RemoveContext(SyncContext* context) {
173 base::AutoLock auto_lock(message_lock_);
174
175 SyncMessageQueue::iterator iter = message_queue_.begin();
176 while (iter != message_queue_.end()) {
177 if (iter->context.get() == context) {
178 iter = message_queue_.erase(iter);
179 message_queue_version_++;
180 } else {
181 iter++;
182 }
183 }
184
185 if (--listener_count_ == 0) {
186 DCHECK(received_queue);
187 received_queue = nullptr;
188 sync_dispatch_watcher_.reset();
189 }
190 }
191
dispatch_event()192 base::WaitableEvent* dispatch_event() { return &dispatch_event_; }
listener_task_runner()193 base::SingleThreadTaskRunner* listener_task_runner() {
194 return listener_task_runner_.get();
195 }
196
197 // Called on the ipc thread to check if we can unblock any current Send()
198 // calls based on a queued reply.
DispatchReplies()199 void DispatchReplies() {
200 for (size_t i = 0; i < received_replies_.size(); ++i) {
201 Message* message = received_replies_[i].message.get();
202 if (received_replies_[i].context->TryToUnblockListener(message)) {
203 received_replies_.erase(received_replies_.begin() + i);
204 return;
205 }
206 }
207 }
208
209 private:
210 friend class base::RefCountedThreadSafe<ReceivedSyncMsgQueue>;
211
212 // See the comment in SyncChannel::SyncChannel for why this event is created
213 // as manual reset.
ReceivedSyncMsgQueue()214 ReceivedSyncMsgQueue()
215 : message_queue_version_(0),
216 dispatch_event_(base::WaitableEvent::ResetPolicy::MANUAL,
217 base::WaitableEvent::InitialState::NOT_SIGNALED),
218 listener_task_runner_(
219 base::SingleThreadTaskRunner::GetCurrentDefault()),
220 sync_dispatch_watcher_(std::make_unique<mojo::SyncEventWatcher>(
221 &dispatch_event_,
222 base::BindRepeating(&ReceivedSyncMsgQueue::OnDispatchEventReady,
223 base::Unretained(this)))) {
224 sync_dispatch_watcher_->AllowWokenUpBySyncWatchOnSameThread();
225 }
226
227 ~ReceivedSyncMsgQueue() = default;
228
OnDispatchEventReady()229 void OnDispatchEventReady() {
230 if (dispatch_flag_) {
231 *dispatch_flag_ = true;
232 return;
233 }
234
235 // We were woken up during a sync wait, but no specific SyncChannel is
236 // currently waiting. i.e., some other Mojo interface on this thread is
237 // waiting for a response. Since we don't support anything analogous to
238 // restricted dispatch on Mojo interfaces, in this case it's safe to
239 // dispatch sync messages for any context.
240 DispatchMessages(nullptr);
241 }
242
243 // Holds information about a queued synchronous message or reply.
244 struct QueuedMessage {
245 std::unique_ptr<Message> message;
246 scoped_refptr<SyncChannel::SyncContext> context;
247 };
248
249 typedef std::list<QueuedMessage> SyncMessageQueue;
250 SyncMessageQueue message_queue_;
251
252 // Used to signal DispatchMessages to rescan
253 uint32_t message_queue_version_ = 0;
254
255 std::vector<QueuedMessage> received_replies_;
256
257 // Signaled when we get a synchronous message that we must respond to, as the
258 // sender needs its reply before it can reply to our original synchronous
259 // message.
260 base::WaitableEvent dispatch_event_;
261 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner_;
262 base::Lock message_lock_;
263 bool task_pending_ = false;
264 int listener_count_ = 0;
265
266 // If not null, the address of a flag to set when the dispatch event signals,
267 // in lieu of actually dispatching messages. This is used by
268 // SyncChannel::WaitForReply to restrict the scope of queued messages we're
269 // allowed to process while it's waiting.
270 raw_ptr<bool> dispatch_flag_ = nullptr;
271
272 // Watches |dispatch_event_| during all sync handle watches on this thread.
273 std::unique_ptr<mojo::SyncEventWatcher> sync_dispatch_watcher_;
274 };
275
SyncContext(Listener * listener,const scoped_refptr<base::SingleThreadTaskRunner> & ipc_task_runner,const scoped_refptr<base::SingleThreadTaskRunner> & listener_task_runner,WaitableEvent * shutdown_event)276 SyncChannel::SyncContext::SyncContext(
277 Listener* listener,
278 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
279 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
280 WaitableEvent* shutdown_event)
281 : ChannelProxy::Context(listener, ipc_task_runner, listener_task_runner),
282 received_sync_msgs_(ReceivedSyncMsgQueue::AddContext()),
283 shutdown_event_(shutdown_event),
284 restrict_dispatch_group_(kRestrictDispatchGroup_None) {}
285
OnSendDoneEventSignaled(base::RunLoop * nested_loop,base::WaitableEvent * event)286 void SyncChannel::SyncContext::OnSendDoneEventSignaled(
287 base::RunLoop* nested_loop,
288 base::WaitableEvent* event) {
289 DCHECK_EQ(GetSendDoneEvent(), event);
290 nested_loop->Quit();
291 }
292
~SyncContext()293 SyncChannel::SyncContext::~SyncContext() {
294 while (!deserializers_.empty())
295 Pop();
296 }
297
298 // Adds information about an outgoing sync message to the context so that
299 // we know how to deserialize the reply. Returns |true| if the message was added
300 // to the context or |false| if it was rejected (e.g. due to shutdown.)
Push(SyncMessage * sync_msg)301 bool SyncChannel::SyncContext::Push(SyncMessage* sync_msg) {
302 // Create the tracking information for this message. This object is stored
303 // by value since all members are pointers that are cheap to copy. These
304 // pointers are cleaned up in the Pop() function.
305 //
306 // The event is created as manual reset because in between Signal and
307 // OnObjectSignalled, another Send can happen which would stop the watcher
308 // from being called. The event would get watched later, when the nested
309 // Send completes, so the event will need to remain set.
310 base::AutoLock auto_lock(deserializers_lock_);
311 if (reject_new_deserializers_)
312 return false;
313
314 PendingSyncMsg pending(SyncMessage::GetMessageId(*sync_msg),
315 sync_msg->TakeReplyDeserializer(),
316 std::make_unique<base::WaitableEvent>(
317 base::WaitableEvent::ResetPolicy::MANUAL,
318 base::WaitableEvent::InitialState::NOT_SIGNALED));
319 deserializers_.push_back(std::move(pending));
320 return true;
321 }
322
Pop()323 bool SyncChannel::SyncContext::Pop() {
324 bool result;
325 {
326 base::AutoLock auto_lock(deserializers_lock_);
327 result = deserializers_.back().send_result;
328 deserializers_.pop_back();
329 }
330
331 // We got a reply to a synchronous Send() call that's blocking the listener
332 // thread. However, further down the call stack there could be another
333 // blocking Send() call, whose reply we received after we made this last
334 // Send() call. So check if we have any queued replies available that
335 // can now unblock the listener thread.
336 ipc_task_runner()->PostTask(
337 FROM_HERE, base::BindOnce(&ReceivedSyncMsgQueue::DispatchReplies,
338 received_sync_msgs_));
339
340 return result;
341 }
342
GetSendDoneEvent()343 base::WaitableEvent* SyncChannel::SyncContext::GetSendDoneEvent() {
344 base::AutoLock auto_lock(deserializers_lock_);
345 return deserializers_.back().done_event.get();
346 }
347
GetDispatchEvent()348 base::WaitableEvent* SyncChannel::SyncContext::GetDispatchEvent() {
349 return received_sync_msgs_->dispatch_event();
350 }
351
DispatchMessages()352 void SyncChannel::SyncContext::DispatchMessages() {
353 received_sync_msgs_->DispatchMessages(this);
354 }
355
TryToUnblockListener(const Message * msg)356 bool SyncChannel::SyncContext::TryToUnblockListener(const Message* msg) {
357 base::AutoLock auto_lock(deserializers_lock_);
358 if (deserializers_.empty() ||
359 !SyncMessage::IsMessageReplyTo(*msg, deserializers_.back().id)) {
360 return false;
361 }
362
363 if (!msg->is_reply_error()) {
364 bool send_result = deserializers_.back().deserializer->
365 SerializeOutputParameters(*msg);
366 deserializers_.back().send_result = send_result;
367 DVLOG_IF(1, !send_result) << "Couldn't deserialize reply message";
368 } else {
369 DVLOG(1) << "Received error reply";
370 }
371
372 base::WaitableEvent* done_event = deserializers_.back().done_event.get();
373 TRACE_EVENT_WITH_FLOW0("toplevel.flow",
374 "SyncChannel::SyncContext::TryToUnblockListener",
375 done_event, TRACE_EVENT_FLAG_FLOW_OUT);
376
377 done_event->Signal();
378
379 return true;
380 }
381
Clear()382 void SyncChannel::SyncContext::Clear() {
383 CancelPendingSends();
384 received_sync_msgs_->RemoveContext(this);
385 Context::Clear();
386 }
387
OnMessageReceived(const Message & msg)388 bool SyncChannel::SyncContext::OnMessageReceived(const Message& msg) {
389 // Give the filters a chance at processing this message.
390 if (TryFilters(msg))
391 return true;
392
393 if (TryToUnblockListener(&msg))
394 return true;
395
396 if (msg.is_reply()) {
397 received_sync_msgs_->QueueReply(msg, this);
398 return true;
399 }
400
401 if (msg.should_unblock()) {
402 received_sync_msgs_->QueueMessage(msg, this);
403 return true;
404 }
405
406 return Context::OnMessageReceivedNoFilter(msg);
407 }
408
OnChannelError()409 void SyncChannel::SyncContext::OnChannelError() {
410 CancelPendingSends();
411 shutdown_watcher_.StopWatching();
412 Context::OnChannelError();
413 }
414
OnChannelOpened()415 void SyncChannel::SyncContext::OnChannelOpened() {
416 if (shutdown_event_) {
417 shutdown_watcher_.StartWatching(
418 shutdown_event_,
419 base::BindOnce(&SyncChannel::SyncContext::OnShutdownEventSignaled,
420 base::Unretained(this)),
421 base::SequencedTaskRunner::GetCurrentDefault());
422 }
423 Context::OnChannelOpened();
424 }
425
OnChannelClosed()426 void SyncChannel::SyncContext::OnChannelClosed() {
427 CancelPendingSends();
428 shutdown_watcher_.StopWatching();
429 Context::OnChannelClosed();
430 }
431
CancelPendingSends()432 void SyncChannel::SyncContext::CancelPendingSends() {
433 base::AutoLock auto_lock(deserializers_lock_);
434 reject_new_deserializers_ = true;
435 PendingSyncMessageQueue::iterator iter;
436 DVLOG(1) << "Canceling pending sends";
437 for (iter = deserializers_.begin(); iter != deserializers_.end(); iter++) {
438 TRACE_EVENT_WITH_FLOW0("toplevel.flow",
439 "SyncChannel::SyncContext::CancelPendingSends",
440 iter->done_event.get(), TRACE_EVENT_FLAG_FLOW_OUT);
441 iter->done_event->Signal();
442 }
443 }
444
OnShutdownEventSignaled(WaitableEvent * event)445 void SyncChannel::SyncContext::OnShutdownEventSignaled(WaitableEvent* event) {
446 DCHECK_EQ(event, shutdown_event_);
447
448 // Process shut down before we can get a reply to a synchronous message.
449 // Cancel pending Send calls, which will end up setting the send done event.
450 CancelPendingSends();
451 }
452
453 // static
Create(const IPC::ChannelHandle & channel_handle,Channel::Mode mode,Listener * listener,const scoped_refptr<base::SingleThreadTaskRunner> & ipc_task_runner,const scoped_refptr<base::SingleThreadTaskRunner> & listener_task_runner,bool create_pipe_now,base::WaitableEvent * shutdown_event)454 std::unique_ptr<SyncChannel> SyncChannel::Create(
455 const IPC::ChannelHandle& channel_handle,
456 Channel::Mode mode,
457 Listener* listener,
458 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
459 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
460 bool create_pipe_now,
461 base::WaitableEvent* shutdown_event) {
462 // TODO(tobiasjs): The shutdown_event object is passed to a refcounted
463 // Context object, and as a result it is not easy to ensure that it
464 // outlives the Context. There should be some way to either reset
465 // the shutdown_event when it is destroyed, or allow the Context to
466 // control the lifetime of shutdown_event.
467 std::unique_ptr<SyncChannel> channel =
468 Create(listener, ipc_task_runner, listener_task_runner, shutdown_event);
469 channel->Init(channel_handle, mode, create_pipe_now);
470 return channel;
471 }
472
473 // static
Create(Listener * listener,const scoped_refptr<base::SingleThreadTaskRunner> & ipc_task_runner,const scoped_refptr<base::SingleThreadTaskRunner> & listener_task_runner,WaitableEvent * shutdown_event)474 std::unique_ptr<SyncChannel> SyncChannel::Create(
475 Listener* listener,
476 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
477 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
478 WaitableEvent* shutdown_event) {
479 return base::WrapUnique(new SyncChannel(
480 listener, ipc_task_runner, listener_task_runner, shutdown_event));
481 }
482
SyncChannel(Listener * listener,const scoped_refptr<base::SingleThreadTaskRunner> & ipc_task_runner,const scoped_refptr<base::SingleThreadTaskRunner> & listener_task_runner,WaitableEvent * shutdown_event)483 SyncChannel::SyncChannel(
484 Listener* listener,
485 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
486 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
487 WaitableEvent* shutdown_event)
488 : ChannelProxy(new SyncContext(listener,
489 ipc_task_runner,
490 listener_task_runner,
491 shutdown_event)),
492 sync_handle_registry_(mojo::SyncHandleRegistry::current()) {
493 // The current (listener) thread must be distinct from the IPC thread, or else
494 // sending synchronous messages will deadlock.
495 DCHECK_NE(ipc_task_runner.get(),
496 base::SingleThreadTaskRunner::GetCurrentDefault().get());
497 StartWatching();
498 }
499
AddListenerTaskRunner(int32_t routing_id,scoped_refptr<base::SingleThreadTaskRunner> task_runner)500 void SyncChannel::AddListenerTaskRunner(
501 int32_t routing_id,
502 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
503 context()->AddListenerTaskRunner(routing_id, std::move(task_runner));
504 }
505
RemoveListenerTaskRunner(int32_t routing_id)506 void SyncChannel::RemoveListenerTaskRunner(int32_t routing_id) {
507 context()->RemoveListenerTaskRunner(routing_id);
508 }
509
510 SyncChannel::~SyncChannel() = default;
511
SetRestrictDispatchChannelGroup(int group)512 void SyncChannel::SetRestrictDispatchChannelGroup(int group) {
513 sync_context()->set_restrict_dispatch_group(group);
514 }
515
CreateSyncMessageFilter()516 scoped_refptr<SyncMessageFilter> SyncChannel::CreateSyncMessageFilter() {
517 scoped_refptr<SyncMessageFilter> filter = new SyncMessageFilter(
518 sync_context()->shutdown_event());
519 AddFilter(filter.get());
520 if (!did_init())
521 pre_init_sync_message_filters_.push_back(filter);
522 return filter;
523 }
524
Send(Message * message)525 bool SyncChannel::Send(Message* message) {
526 #if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
527 std::string name;
528 Logging::GetInstance()->GetMessageText(
529 message->type(), &name, message, nullptr);
530 TRACE_EVENT1("ipc", "SyncChannel::Send", "name", name);
531 #else
532 TRACE_IPC_MESSAGE_SEND("ipc", "SyncChannel::Send", message);
533 #endif
534 if (!message->is_sync()) {
535 ChannelProxy::SendInternal(message);
536 return true;
537 }
538
539 SyncMessage* sync_msg = static_cast<SyncMessage*>(message);
540
541 // *this* might get deleted in WaitForReply.
542 scoped_refptr<SyncContext> context(sync_context());
543 if (!context->Push(sync_msg)) {
544 DVLOG(1) << "Channel is shutting down. Dropping sync message.";
545 delete message;
546 return false;
547 }
548
549 ChannelProxy::SendInternal(message);
550
551 // Wait for reply, or for any other incoming synchronous messages.
552 // |this| might get deleted, so only call static functions at this point.
553 scoped_refptr<mojo::SyncHandleRegistry> registry = sync_handle_registry_;
554 WaitForReply(registry.get(), context.get());
555
556 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "SyncChannel::Send",
557 context->GetSendDoneEvent(), TRACE_EVENT_FLAG_FLOW_IN);
558
559 return context->Pop();
560 }
561
WaitForReply(mojo::SyncHandleRegistry * registry,SyncContext * context)562 void SyncChannel::WaitForReply(mojo::SyncHandleRegistry* registry,
563 SyncContext* context) {
564 context->DispatchMessages();
565
566 while (true) {
567 bool dispatch = false;
568 {
569 bool send_done = false;
570 mojo::SyncHandleRegistry::EventCallbackSubscription
571 send_done_subscription = registry->RegisterEvent(
572 context->GetSendDoneEvent(),
573 base::BindRepeating(&OnEventReady, &send_done));
574
575 const bool* stop_flags[] = {&dispatch, &send_done};
576 context->received_sync_msgs()->BlockDispatch(&dispatch);
577 registry->Wait(stop_flags, 2);
578 context->received_sync_msgs()->UnblockDispatch();
579 }
580
581 if (dispatch) {
582 // We're waiting for a reply, but we received a blocking synchronous call.
583 // We must process it to avoid potential deadlocks.
584 context->GetDispatchEvent()->Reset();
585 context->DispatchMessages();
586 continue;
587 }
588 break;
589 }
590 }
591
OnDispatchEventSignaled(base::WaitableEvent * event)592 void SyncChannel::OnDispatchEventSignaled(base::WaitableEvent* event) {
593 DCHECK_EQ(sync_context()->GetDispatchEvent(), event);
594 sync_context()->GetDispatchEvent()->Reset();
595
596 StartWatching();
597
598 // NOTE: May delete |this|.
599 sync_context()->DispatchMessages();
600 }
601
StartWatching()602 void SyncChannel::StartWatching() {
603 // |dispatch_watcher_| watches the event asynchronously, only dispatching
604 // messages once the listener thread is unblocked and pumping its task queue.
605 // The ReceivedSyncMsgQueue also watches this event and may dispatch
606 // immediately if woken up by a message which it's allowed to dispatch.
607 dispatch_watcher_.StartWatching(
608 sync_context()->GetDispatchEvent(),
609 base::BindOnce(&SyncChannel::OnDispatchEventSignaled,
610 base::Unretained(this)),
611 sync_context()->listener_task_runner());
612 }
613
OnChannelInit()614 void SyncChannel::OnChannelInit() {
615 pre_init_sync_message_filters_.clear();
616 }
617
618 } // namespace IPC
619