blob: 99258953427a85048377f647c6065d9d78b80140 [file] [log] [blame]
[email protected]522cc10d2012-01-11 22:39:541// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]946d1b22009-07-22 23:57:215#include "ipc/ipc_sync_channel.h"
initial.commit09911bf2008-07-26 23:55:296
avi246998d82015-12-22 02:39:047#include <stddef.h>
8#include <stdint.h>
danakj03de39b22016-04-23 04:21:099
dchenge48600452015-12-28 02:24:5010#include <utility>
avi246998d82015-12-22 02:39:0411
[email protected]72b6f8e22011-11-12 21:16:4112#include "base/bind.h"
[email protected]f886b7bf2008-09-10 10:54:0613#include "base/lazy_instance.h"
[email protected]c62dd9d2011-09-21 18:05:4114#include "base/location.h"
initial.commit09911bf2008-07-26 23:55:2915#include "base/logging.h"
rockot64e65de2016-06-21 20:17:4916#include "base/macros.h"
danakj03de39b22016-04-23 04:21:0917#include "base/memory/ptr_util.h"
rockot64e65de2016-06-21 20:17:4918#include "base/run_loop.h"
[email protected]44f9c952011-01-02 06:05:3919#include "base/synchronization/waitable_event.h"
[email protected]b2432302012-07-02 21:15:5220#include "base/threading/thread_local.h"
gabf08ccc02016-05-11 18:51:1121#include "base/threading/thread_task_runner_handle.h"
primiano7182d7b2015-01-30 18:02:0322#include "base/trace_event/trace_event.h"
[email protected]64860882014-08-04 23:44:1723#include "ipc/ipc_channel_factory.h"
[email protected]60b2c61f2012-08-22 22:39:5724#include "ipc/ipc_logging.h"
25#include "ipc/ipc_message_macros.h"
[email protected]946d1b22009-07-22 23:57:2126#include "ipc/ipc_sync_message.h"
rockot64e65de2016-06-21 20:17:4927#include "ipc/mojo_event.h"
28#include "mojo/public/cpp/bindings/sync_handle_registry.h"
initial.commit09911bf2008-07-26 23:55:2929
[email protected]1c4947f2009-01-15 22:25:1130using base::WaitableEvent;
initial.commit09911bf2008-07-26 23:55:2931
32namespace IPC {
rockot64e65de2016-06-21 20:17:4933
34namespace {
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.
38void 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|.
46void RunOnHandleReady(const base::Closure& callback, MojoResult result) {
47 DCHECK(result == MOJO_RESULT_OK || result == MOJO_RESULT_ABORTED);
48 if (result == MOJO_RESULT_OK)
49 callback.Run();
50}
51
52} // namespace
53
54// A lazy thread-local Mojo Event which is always signaled. Used to wake up the
55// sync waiter when a SyncMessage requires the MessageLoop to be pumped while
56// waiting for a reply. This object is created lazily and ref-counted so it can
57// be cleaned up when no longer in use.
58class SyncChannel::PumpMessagesEvent
59 : public base::RefCountedThreadSafe<PumpMessagesEvent> {
60 public:
61 static scoped_refptr<PumpMessagesEvent> current() {
62 scoped_refptr<PumpMessagesEvent> current = current_event_.Pointer()->Get();
63 if (!current) {
64 current = new PumpMessagesEvent;
65 current_event_.Pointer()->Set(current.get());
66 }
67 return current;
68 }
69
70 const MojoEvent* event() const { return &event_; }
71
72 private:
73 friend class base::RefCountedThreadSafe<PumpMessagesEvent>;
74
75 PumpMessagesEvent() { event_.Signal(); }
76
77 ~PumpMessagesEvent() {
78 DCHECK_EQ(current_event_.Pointer()->Get(), this);
79 current_event_.Pointer()->Set(nullptr);
80 }
81
82 MojoEvent event_;
83
84 static base::LazyInstance<base::ThreadLocalPointer<
85 SyncChannel::PumpMessagesEvent>> current_event_;
86
87 DISALLOW_COPY_AND_ASSIGN(PumpMessagesEvent);
88};
89
90base::LazyInstance<base::ThreadLocalPointer<SyncChannel::PumpMessagesEvent>>
91 SyncChannel::PumpMessagesEvent::current_event_ =
92 LAZY_INSTANCE_INITIALIZER;
93
94
initial.commit09911bf2008-07-26 23:55:2995// When we're blocked in a Send(), we need to process incoming synchronous
96// messages right away because it could be blocking our reply (either
97// directly from the same object we're calling, or indirectly through one or
98// more other channels). That means that in SyncContext's OnMessageReceived,
99// we need to process sync message right away if we're blocked. However a
100// simple check isn't sufficient, because the listener thread can be in the
101// process of calling Send.
102// To work around this, when SyncChannel filters a sync message, it sets
103// an event that the listener thread waits on during its Send() call. This
104// allows us to dispatch incoming sync messages when blocked. The race
105// condition is handled because if Send is in the process of being called, it
106// will check the event. In case the listener thread isn't sending a message,
107// we queue a task on the listener thread to dispatch the received messages.
108// The messages are stored in this queue object that's shared among all
109// SyncChannel objects on the same thread (since one object can receive a
110// sync message while another one is blocked).
111
initial.commit09911bf2008-07-26 23:55:29112class SyncChannel::ReceivedSyncMsgQueue :
113 public base::RefCountedThreadSafe<ReceivedSyncMsgQueue> {
114 public:
[email protected]3cdb7af812008-10-24 19:21:13115 // Returns the ReceivedSyncMsgQueue instance for this thread, creating one
[email protected]d3ae7a072008-12-05 20:27:20116 // if necessary. Call RemoveContext on the same thread when done.
117 static ReceivedSyncMsgQueue* AddContext() {
[email protected]3cdb7af812008-10-24 19:21:13118 // We want one ReceivedSyncMsgQueue per listener thread (i.e. since multiple
119 // SyncChannel objects can block the same thread).
120 ReceivedSyncMsgQueue* rv = lazy_tls_ptr_.Pointer()->Get();
121 if (!rv) {
122 rv = new ReceivedSyncMsgQueue();
123 ReceivedSyncMsgQueue::lazy_tls_ptr_.Pointer()->Set(rv);
124 }
125 rv->listener_count_++;
126 return rv;
initial.commit09911bf2008-07-26 23:55:29127 }
128
initial.commit09911bf2008-07-26 23:55:29129 // Called on IPC thread when a synchronous message or reply arrives.
[email protected]d3ae7a072008-12-05 20:27:20130 void QueueMessage(const Message& msg, SyncChannel::SyncContext* context) {
initial.commit09911bf2008-07-26 23:55:29131 bool was_task_pending;
132 {
[email protected]20305ec2011-01-21 04:55:52133 base::AutoLock auto_lock(message_lock_);
initial.commit09911bf2008-07-26 23:55:29134
135 was_task_pending = task_pending_;
136 task_pending_ = true;
137
138 // We set the event in case the listener thread is blocked (or is about
139 // to). In case it's not, the PostTask dispatches the messages.
[email protected]d3ae7a072008-12-05 20:27:20140 message_queue_.push_back(QueuedMessage(new Message(msg), context));
[email protected]522cc10d2012-01-11 22:39:54141 message_queue_version_++;
initial.commit09911bf2008-07-26 23:55:29142 }
143
[email protected]1c4947f2009-01-15 22:25:11144 dispatch_event_.Signal();
initial.commit09911bf2008-07-26 23:55:29145 if (!was_task_pending) {
[email protected]b2432302012-07-02 21:15:52146 listener_task_runner_->PostTask(
[email protected]72b6f8e22011-11-12 21:16:41147 FROM_HERE, base::Bind(&ReceivedSyncMsgQueue::DispatchMessagesTask,
vmpstra34d11322016-03-21 20:28:47148 this, base::RetainedRef(context)));
initial.commit09911bf2008-07-26 23:55:29149 }
150 }
151
152 void QueueReply(const Message &msg, SyncChannel::SyncContext* context) {
[email protected]d3ae7a072008-12-05 20:27:20153 received_replies_.push_back(QueuedMessage(new Message(msg), context));
initial.commit09911bf2008-07-26 23:55:29154 }
155
[email protected]d3ae7a072008-12-05 20:27:20156 // Called on the listener's thread to process any queues synchronous
initial.commit09911bf2008-07-26 23:55:29157 // messages.
[email protected]54af05f2011-04-08 03:38:21158 void DispatchMessagesTask(SyncContext* context) {
initial.commit09911bf2008-07-26 23:55:29159 {
[email protected]20305ec2011-01-21 04:55:52160 base::AutoLock auto_lock(message_lock_);
initial.commit09911bf2008-07-26 23:55:29161 task_pending_ = false;
162 }
[email protected]54af05f2011-04-08 03:38:21163 context->DispatchMessages();
initial.commit09911bf2008-07-26 23:55:29164 }
165
[email protected]54af05f2011-04-08 03:38:21166 void DispatchMessages(SyncContext* dispatching_context) {
[email protected]522cc10d2012-01-11 22:39:54167 bool first_time = true;
tfarina10a5c062015-09-04 18:47:57168 uint32_t expected_version = 0;
[email protected]522cc10d2012-01-11 22:39:54169 SyncMessageQueue::iterator it;
initial.commit09911bf2008-07-26 23:55:29170 while (true) {
[email protected]522cc10d2012-01-11 22:39:54171 Message* message = NULL;
[email protected]d3ae7a072008-12-05 20:27:20172 scoped_refptr<SyncChannel::SyncContext> context;
initial.commit09911bf2008-07-26 23:55:29173 {
[email protected]20305ec2011-01-21 04:55:52174 base::AutoLock auto_lock(message_lock_);
[email protected]522cc10d2012-01-11 22:39:54175 if (first_time || message_queue_version_ != expected_version) {
176 it = message_queue_.begin();
177 first_time = false;
[email protected]54af05f2011-04-08 03:38:21178 }
[email protected]522cc10d2012-01-11 22:39:54179 for (; it != message_queue_.end(); it++) {
[email protected]298ee7d2012-03-30 21:29:30180 int message_group = it->context->restrict_dispatch_group();
181 if (message_group == kRestrictDispatchGroup_None ||
182 message_group == dispatching_context->restrict_dispatch_group()) {
[email protected]522cc10d2012-01-11 22:39:54183 message = it->message;
184 context = it->context;
185 it = message_queue_.erase(it);
186 message_queue_version_++;
187 expected_version = message_queue_version_;
188 break;
189 }
190 }
191 }
initial.commit09911bf2008-07-26 23:55:29192
[email protected]522cc10d2012-01-11 22:39:54193 if (message == NULL)
194 break;
195 context->OnDispatchMessage(*message);
196 delete message;
initial.commit09911bf2008-07-26 23:55:29197 }
198 }
199
initial.commit09911bf2008-07-26 23:55:29200 // SyncChannel calls this in its destructor.
[email protected]d3ae7a072008-12-05 20:27:20201 void RemoveContext(SyncContext* context) {
[email protected]20305ec2011-01-21 04:55:52202 base::AutoLock auto_lock(message_lock_);
initial.commit09911bf2008-07-26 23:55:29203
[email protected]d3ae7a072008-12-05 20:27:20204 SyncMessageQueue::iterator iter = message_queue_.begin();
205 while (iter != message_queue_.end()) {
[email protected]17571642013-06-01 04:11:27206 if (iter->context.get() == context) {
[email protected]d3ae7a072008-12-05 20:27:20207 delete iter->message;
208 iter = message_queue_.erase(iter);
[email protected]522cc10d2012-01-11 22:39:54209 message_queue_version_++;
initial.commit09911bf2008-07-26 23:55:29210 } else {
[email protected]d3ae7a072008-12-05 20:27:20211 iter++;
initial.commit09911bf2008-07-26 23:55:29212 }
initial.commit09911bf2008-07-26 23:55:29213 }
[email protected]3cdb7af812008-10-24 19:21:13214
215 if (--listener_count_ == 0) {
216 DCHECK(lazy_tls_ptr_.Pointer()->Get());
217 lazy_tls_ptr_.Pointer()->Set(NULL);
218 }
initial.commit09911bf2008-07-26 23:55:29219 }
220
rockot64e65de2016-06-21 20:17:49221 MojoEvent* dispatch_event() { return &dispatch_event_; }
[email protected]b2432302012-07-02 21:15:52222 base::SingleThreadTaskRunner* listener_task_runner() {
[email protected]17571642013-06-01 04:11:27223 return listener_task_runner_.get();
[email protected]92bf9062011-05-02 18:00:49224 }
initial.commit09911bf2008-07-26 23:55:29225
[email protected]f886b7bf2008-09-10 10:54:06226 // Holds a pointer to the per-thread ReceivedSyncMsgQueue object.
227 static base::LazyInstance<base::ThreadLocalPointer<ReceivedSyncMsgQueue> >
228 lazy_tls_ptr_;
229
initial.commit09911bf2008-07-26 23:55:29230 // Called on the ipc thread to check if we can unblock any current Send()
231 // calls based on a queued reply.
232 void DispatchReplies() {
initial.commit09911bf2008-07-26 23:55:29233 for (size_t i = 0; i < received_replies_.size(); ++i) {
234 Message* message = received_replies_[i].message;
[email protected]3cdb7af812008-10-24 19:21:13235 if (received_replies_[i].context->TryToUnblockListener(message)) {
initial.commit09911bf2008-07-26 23:55:29236 delete message;
237 received_replies_.erase(received_replies_.begin() + i);
238 return;
239 }
240 }
241 }
242
rockot64e65de2016-06-21 20:17:49243 mojo::Watcher* top_send_done_watcher() {
[email protected]ac0efda2009-10-14 16:22:02244 return top_send_done_watcher_;
245 }
246
rockot64e65de2016-06-21 20:17:49247 void set_top_send_done_watcher(mojo::Watcher* watcher) {
[email protected]ac0efda2009-10-14 16:22:02248 top_send_done_watcher_ = watcher;
249 }
250
[email protected]63a7bb82008-10-25 00:46:00251 private:
[email protected]877d55d2009-11-05 21:53:08252 friend class base::RefCountedThreadSafe<ReceivedSyncMsgQueue>;
253
[email protected]4df10d612008-11-12 00:38:26254 // See the comment in SyncChannel::SyncChannel for why this event is created
255 // as manual reset.
gab90c2c5c2016-06-01 20:34:06256 ReceivedSyncMsgQueue()
257 : message_queue_version_(0),
gab90c2c5c2016-06-01 20:34:06258 listener_task_runner_(base::ThreadTaskRunnerHandle::Get()),
259 task_pending_(false),
260 listener_count_(0),
261 top_send_done_watcher_(NULL) {}
[email protected]63a7bb82008-10-25 00:46:00262
[email protected]877d55d2009-11-05 21:53:08263 ~ReceivedSyncMsgQueue() {}
264
[email protected]d3ae7a072008-12-05 20:27:20265 // Holds information about a queued synchronous message or reply.
266 struct QueuedMessage {
267 QueuedMessage(Message* m, SyncContext* c) : message(m), context(c) { }
initial.commit09911bf2008-07-26 23:55:29268 Message* message;
269 scoped_refptr<SyncChannel::SyncContext> context;
270 };
271
[email protected]522cc10d2012-01-11 22:39:54272 typedef std::list<QueuedMessage> SyncMessageQueue;
[email protected]1c4947f2009-01-15 22:25:11273 SyncMessageQueue message_queue_;
tfarina10a5c062015-09-04 18:47:57274 uint32_t message_queue_version_; // Used to signal DispatchMessages to rescan
[email protected]d3ae7a072008-12-05 20:27:20275
276 std::vector<QueuedMessage> received_replies_;
[email protected]3cdb7af812008-10-24 19:21:13277
rockot64e65de2016-06-21 20:17:49278 // Signaled when we get a synchronous message that we must respond to, as the
[email protected]3cdb7af812008-10-24 19:21:13279 // sender needs its reply before it can reply to our original synchronous
280 // message.
rockot64e65de2016-06-21 20:17:49281 MojoEvent dispatch_event_;
[email protected]b2432302012-07-02 21:15:52282 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner_;
[email protected]20305ec2011-01-21 04:55:52283 base::Lock message_lock_;
[email protected]3cdb7af812008-10-24 19:21:13284 bool task_pending_;
285 int listener_count_;
[email protected]ac0efda2009-10-14 16:22:02286
rockot64e65de2016-06-21 20:17:49287 // The current send done handle watcher for this thread. Used to maintain
288 // a thread-local stack of send done watchers to ensure that nested sync
[email protected]ac0efda2009-10-14 16:22:02289 // message loops complete correctly.
rockot64e65de2016-06-21 20:17:49290 mojo::Watcher* top_send_done_watcher_;
initial.commit09911bf2008-07-26 23:55:29291};
292
[email protected]f886b7bf2008-09-10 10:54:06293base::LazyInstance<base::ThreadLocalPointer<SyncChannel::ReceivedSyncMsgQueue> >
[email protected]6de0fd1d2011-11-15 13:31:49294 SyncChannel::ReceivedSyncMsgQueue::lazy_tls_ptr_ =
295 LAZY_INSTANCE_INITIALIZER;
initial.commit09911bf2008-07-26 23:55:29296
297SyncChannel::SyncContext::SyncContext(
[email protected]b7f59e822012-06-29 22:05:26298 Listener* listener,
dchengfd033702014-08-28 16:59:29299 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
[email protected]1c4947f2009-01-15 22:25:11300 WaitableEvent* shutdown_event)
[email protected]b2432302012-07-02 21:15:52301 : ChannelProxy::Context(listener, ipc_task_runner),
[email protected]1c4947f2009-01-15 22:25:11302 received_sync_msgs_(ReceivedSyncMsgQueue::AddContext()),
[email protected]54af05f2011-04-08 03:38:21303 shutdown_event_(shutdown_event),
[email protected]298ee7d2012-03-30 21:29:30304 restrict_dispatch_group_(kRestrictDispatchGroup_None) {
initial.commit09911bf2008-07-26 23:55:29305}
306
307SyncChannel::SyncContext::~SyncContext() {
308 while (!deserializers_.empty())
[email protected]3cdb7af812008-10-24 19:21:13309 Pop();
initial.commit09911bf2008-07-26 23:55:29310}
311
312// Adds information about an outgoing sync message to the context so that
rockot64e65de2016-06-21 20:17:49313// we know how to deserialize the reply. Returns |true| if the message was added
314// to the context or |false| if it was rejected (e.g. due to shutdown.)
315bool SyncChannel::SyncContext::Push(SyncMessage* sync_msg) {
[email protected]4a180a52011-04-15 19:07:43316 // Create the tracking information for this message. This object is stored
317 // by value since all members are pointers that are cheap to copy. These
318 // pointers are cleaned up in the Pop() function.
319 //
[email protected]1c4947f2009-01-15 22:25:11320 // The event is created as manual reset because in between Signal and
[email protected]4df10d612008-11-12 00:38:26321 // OnObjectSignalled, another Send can happen which would stop the watcher
322 // from being called. The event would get watched later, when the nested
323 // Send completes, so the event will need to remain set.
rockot64e65de2016-06-21 20:17:49324 base::AutoLock auto_lock(deserializers_lock_);
325 if (reject_new_deserializers_)
326 return false;
gab90c2c5c2016-06-01 20:34:06327 PendingSyncMsg pending(
328 SyncMessage::GetMessageId(*sync_msg), sync_msg->GetReplyDeserializer(),
rockot64e65de2016-06-21 20:17:49329 new MojoEvent);
[email protected]3cdb7af812008-10-24 19:21:13330 deserializers_.push_back(pending);
rockot64e65de2016-06-21 20:17:49331 return true;
initial.commit09911bf2008-07-26 23:55:29332}
333
[email protected]3cdb7af812008-10-24 19:21:13334bool SyncChannel::SyncContext::Pop() {
[email protected]63a7bb82008-10-25 00:46:00335 bool result;
336 {
[email protected]20305ec2011-01-21 04:55:52337 base::AutoLock auto_lock(deserializers_lock_);
[email protected]63a7bb82008-10-25 00:46:00338 PendingSyncMsg msg = deserializers_.back();
339 delete msg.deserializer;
[email protected]1c4947f2009-01-15 22:25:11340 delete msg.done_event;
rockot64e65de2016-06-21 20:17:49341 msg.done_event = nullptr;
[email protected]63a7bb82008-10-25 00:46:00342 deserializers_.pop_back();
343 result = msg.send_result;
344 }
345
346 // We got a reply to a synchronous Send() call that's blocking the listener
347 // thread. However, further down the call stack there could be another
348 // blocking Send() call, whose reply we received after we made this last
349 // Send() call. So check if we have any queued replies available that
350 // can now unblock the listener thread.
[email protected]b2432302012-07-02 21:15:52351 ipc_task_runner()->PostTask(
[email protected]72b6f8e22011-11-12 21:16:41352 FROM_HERE, base::Bind(&ReceivedSyncMsgQueue::DispatchReplies,
353 received_sync_msgs_.get()));
[email protected]63a7bb82008-10-25 00:46:00354
355 return result;
[email protected]3cdb7af812008-10-24 19:21:13356}
357
rockot64e65de2016-06-21 20:17:49358MojoEvent* SyncChannel::SyncContext::GetSendDoneEvent() {
[email protected]20305ec2011-01-21 04:55:52359 base::AutoLock auto_lock(deserializers_lock_);
[email protected]3cdb7af812008-10-24 19:21:13360 return deserializers_.back().done_event;
361}
362
rockot64e65de2016-06-21 20:17:49363MojoEvent* SyncChannel::SyncContext::GetDispatchEvent() {
[email protected]3cdb7af812008-10-24 19:21:13364 return received_sync_msgs_->dispatch_event();
initial.commit09911bf2008-07-26 23:55:29365}
366
367void SyncChannel::SyncContext::DispatchMessages() {
[email protected]54af05f2011-04-08 03:38:21368 received_sync_msgs_->DispatchMessages(this);
initial.commit09911bf2008-07-26 23:55:29369}
370
[email protected]3cdb7af812008-10-24 19:21:13371bool SyncChannel::SyncContext::TryToUnblockListener(const Message* msg) {
[email protected]20305ec2011-01-21 04:55:52372 base::AutoLock auto_lock(deserializers_lock_);
[email protected]63a7bb82008-10-25 00:46:00373 if (deserializers_.empty() ||
374 !SyncMessage::IsMessageReplyTo(*msg, deserializers_.back().id)) {
375 return false;
[email protected]3cdb7af812008-10-24 19:21:13376 }
initial.commit09911bf2008-07-26 23:55:29377
[email protected]63a7bb82008-10-25 00:46:00378 if (!msg->is_reply_error()) {
[email protected]211142cd2012-08-13 09:41:19379 bool send_result = deserializers_.back().deserializer->
[email protected]63a7bb82008-10-25 00:46:00380 SerializeOutputParameters(*msg);
[email protected]211142cd2012-08-13 09:41:19381 deserializers_.back().send_result = send_result;
bauerb3e9be732015-11-03 18:17:47382 DVLOG_IF(1, !send_result) << "Couldn't deserialize reply message";
[email protected]211142cd2012-08-13 09:41:19383 } else {
bauerb3e9be732015-11-03 18:17:47384 DVLOG(1) << "Received error reply";
[email protected]63a7bb82008-10-25 00:46:00385 }
tzika08b2fd2016-03-30 02:32:59386
rockot64e65de2016-06-21 20:17:49387 MojoEvent* done_event = deserializers_.back().done_event;
tzika08b2fd2016-03-30 02:32:59388 TRACE_EVENT_FLOW_BEGIN0(
389 TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
390 "SyncChannel::SyncContext::TryToUnblockListener", done_event);
391
392 done_event->Signal();
initial.commit09911bf2008-07-26 23:55:29393
[email protected]3cdb7af812008-10-24 19:21:13394 return true;
initial.commit09911bf2008-07-26 23:55:29395}
396
[email protected]3cdb7af812008-10-24 19:21:13397void SyncChannel::SyncContext::Clear() {
398 CancelPendingSends();
[email protected]d3ae7a072008-12-05 20:27:20399 received_sync_msgs_->RemoveContext(this);
[email protected]3cdb7af812008-10-24 19:21:13400 Context::Clear();
401}
402
[email protected]a95986a82010-12-24 06:19:28403bool SyncChannel::SyncContext::OnMessageReceived(const Message& msg) {
[email protected]d65cab7a2008-08-12 01:25:41404 // Give the filters a chance at processing this message.
405 if (TryFilters(msg))
[email protected]a95986a82010-12-24 06:19:28406 return true;
[email protected]d65cab7a2008-08-12 01:25:41407
[email protected]3cdb7af812008-10-24 19:21:13408 if (TryToUnblockListener(&msg))
[email protected]a95986a82010-12-24 06:19:28409 return true;
initial.commit09911bf2008-07-26 23:55:29410
[email protected]9134cce6d2012-04-10 20:07:53411 if (msg.is_reply()) {
412 received_sync_msgs_->QueueReply(msg, this);
[email protected]a95986a82010-12-24 06:19:28413 return true;
initial.commit09911bf2008-07-26 23:55:29414 }
415
[email protected]9134cce6d2012-04-10 20:07:53416 if (msg.should_unblock()) {
417 received_sync_msgs_->QueueMessage(msg, this);
[email protected]a95986a82010-12-24 06:19:28418 return true;
initial.commit09911bf2008-07-26 23:55:29419 }
420
[email protected]3cdb7af812008-10-24 19:21:13421 return Context::OnMessageReceivedNoFilter(msg);
initial.commit09911bf2008-07-26 23:55:29422}
423
initial.commit09911bf2008-07-26 23:55:29424void SyncChannel::SyncContext::OnChannelError() {
[email protected]3cdb7af812008-10-24 19:21:13425 CancelPendingSends();
[email protected]a4f822702009-02-06 00:44:53426 shutdown_watcher_.StopWatching();
initial.commit09911bf2008-07-26 23:55:29427 Context::OnChannelError();
428}
429
[email protected]3cdb7af812008-10-24 19:21:13430void SyncChannel::SyncContext::OnChannelOpened() {
[email protected]329be052013-02-04 18:14:28431 shutdown_watcher_.StartWatching(
432 shutdown_event_,
rockot64e65de2016-06-21 20:17:49433 base::Bind(&SyncChannel::SyncContext::OnShutdownEventSignaled,
[email protected]329be052013-02-04 18:14:28434 base::Unretained(this)));
[email protected]3cdb7af812008-10-24 19:21:13435 Context::OnChannelOpened();
initial.commit09911bf2008-07-26 23:55:29436}
437
[email protected]3cdb7af812008-10-24 19:21:13438void SyncChannel::SyncContext::OnChannelClosed() {
[email protected]87339f02010-09-02 21:45:50439 CancelPendingSends();
[email protected]3cdb7af812008-10-24 19:21:13440 shutdown_watcher_.StopWatching();
441 Context::OnChannelClosed();
442}
443
[email protected]3cdb7af812008-10-24 19:21:13444void SyncChannel::SyncContext::CancelPendingSends() {
[email protected]20305ec2011-01-21 04:55:52445 base::AutoLock auto_lock(deserializers_lock_);
rockot64e65de2016-06-21 20:17:49446 reject_new_deserializers_ = true;
[email protected]3cdb7af812008-10-24 19:21:13447 PendingSyncMessageQueue::iterator iter;
bauerb3e9be732015-11-03 18:17:47448 DVLOG(1) << "Canceling pending sends";
tzika08b2fd2016-03-30 02:32:59449 for (iter = deserializers_.begin(); iter != deserializers_.end(); iter++) {
450 TRACE_EVENT_FLOW_BEGIN0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
451 "SyncChannel::SyncContext::CancelPendingSends",
452 iter->done_event);
[email protected]1c4947f2009-01-15 22:25:11453 iter->done_event->Signal();
tzika08b2fd2016-03-30 02:32:59454 }
[email protected]3cdb7af812008-10-24 19:21:13455}
456
rockot64e65de2016-06-21 20:17:49457void SyncChannel::SyncContext::OnShutdownEventSignaled(WaitableEvent* event) {
458 DCHECK_EQ(event, shutdown_event_);
[email protected]3cdb7af812008-10-24 19:21:13459
rockot64e65de2016-06-21 20:17:49460 // Process shut down before we can get a reply to a synchronous message.
461 // Cancel pending Send calls, which will end up setting the send done event.
462 CancelPendingSends();
[email protected]329be052013-02-04 18:14:28463}
[email protected]3cdb7af812008-10-24 19:21:13464
[email protected]fca876a12014-06-05 16:15:38465// static
danakj03de39b22016-04-23 04:21:09466std::unique_ptr<SyncChannel> SyncChannel::Create(
[email protected]42ce94e2010-12-08 19:28:09467 const IPC::ChannelHandle& channel_handle,
[email protected]3b0e4662014-06-02 20:29:30468 Channel::Mode mode,
[email protected]b7f59e822012-06-29 22:05:26469 Listener* listener,
dchengfd033702014-08-28 16:59:29470 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
[email protected]4b580bf2010-12-02 19:16:07471 bool create_pipe_now,
erikchen30dc2812015-09-24 03:26:38472 base::WaitableEvent* shutdown_event) {
danakj03de39b22016-04-23 04:21:09473 std::unique_ptr<SyncChannel> channel =
[email protected]fca876a12014-06-05 16:15:38474 Create(listener, ipc_task_runner, shutdown_event);
erikchen30dc2812015-09-24 03:26:38475 channel->Init(channel_handle, mode, create_pipe_now);
dchenge48600452015-12-28 02:24:50476 return channel;
[email protected]fca876a12014-06-05 16:15:38477}
478
479// static
danakj03de39b22016-04-23 04:21:09480std::unique_ptr<SyncChannel> SyncChannel::Create(
481 std::unique_ptr<ChannelFactory> factory,
[email protected]64860882014-08-04 23:44:17482 Listener* listener,
dchengfd033702014-08-28 16:59:29483 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
[email protected]64860882014-08-04 23:44:17484 bool create_pipe_now,
485 base::WaitableEvent* shutdown_event) {
danakj03de39b22016-04-23 04:21:09486 std::unique_ptr<SyncChannel> channel =
[email protected]64860882014-08-04 23:44:17487 Create(listener, ipc_task_runner, shutdown_event);
dchenge48600452015-12-28 02:24:50488 channel->Init(std::move(factory), create_pipe_now);
489 return channel;
[email protected]64860882014-08-04 23:44:17490}
491
492// static
danakj03de39b22016-04-23 04:21:09493std::unique_ptr<SyncChannel> SyncChannel::Create(
[email protected]fca876a12014-06-05 16:15:38494 Listener* listener,
dchengfd033702014-08-28 16:59:29495 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
[email protected]fca876a12014-06-05 16:15:38496 WaitableEvent* shutdown_event) {
danakj03de39b22016-04-23 04:21:09497 return base::WrapUnique(
[email protected]fca876a12014-06-05 16:15:38498 new SyncChannel(listener, ipc_task_runner, shutdown_event));
[email protected]952394af2011-11-16 01:06:46499}
500
501SyncChannel::SyncChannel(
[email protected]b7f59e822012-06-29 22:05:26502 Listener* listener,
dchengfd033702014-08-28 16:59:29503 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
[email protected]952394af2011-11-16 01:06:46504 WaitableEvent* shutdown_event)
rockot64e65de2016-06-21 20:17:49505 : ChannelProxy(new SyncContext(listener, ipc_task_runner, shutdown_event)),
506 pump_messages_event_(PumpMessagesEvent::current()),
507 sync_handle_registry_(mojo::SyncHandleRegistry::current()) {
[email protected]1f9cf472014-04-17 05:07:18508 // The current (listener) thread must be distinct from the IPC thread, or else
509 // sending synchronous messages will deadlock.
dchengff04843f2014-09-03 18:01:16510 DCHECK_NE(ipc_task_runner.get(), base::ThreadTaskRunnerHandle::Get().get());
[email protected]952394af2011-11-16 01:06:46511 StartWatching();
initial.commit09911bf2008-07-26 23:55:29512}
513
514SyncChannel::~SyncChannel() {
initial.commit09911bf2008-07-26 23:55:29515}
516
[email protected]298ee7d2012-03-30 21:29:30517void SyncChannel::SetRestrictDispatchChannelGroup(int group) {
518 sync_context()->set_restrict_dispatch_group(group);
[email protected]54af05f2011-04-08 03:38:21519}
520
rockotac64ae92f2015-08-06 00:32:29521scoped_refptr<SyncMessageFilter> SyncChannel::CreateSyncMessageFilter() {
522 scoped_refptr<SyncMessageFilter> filter = new SyncMessageFilter(
523 sync_context()->shutdown_event(),
524 sync_context()->IsChannelSendThreadSafe());
525 AddFilter(filter.get());
rockot29ade1b2015-08-07 06:23:59526 if (!did_init())
527 pre_init_sync_message_filters_.push_back(filter);
rockotac64ae92f2015-08-06 00:32:29528 return filter;
529}
530
[email protected]3cdb7af812008-10-24 19:21:13531bool SyncChannel::Send(Message* message) {
[email protected]60b2c61f2012-08-22 22:39:57532#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]60b2c61f2012-08-22 22:39:57533 std::string name;
pkasting7bc277b2014-10-13 20:58:39534 Logging::GetInstance()->GetMessageText(message->type(), &name, message, NULL);
[email protected]d6cbf052014-05-02 21:29:24535 TRACE_EVENT1("ipc", "SyncChannel::Send", "name", name);
[email protected]60b2c61f2012-08-22 22:39:57536#else
[email protected]d6cbf052014-05-02 21:29:24537 TRACE_EVENT2("ipc", "SyncChannel::Send",
[email protected]60b2c61f2012-08-22 22:39:57538 "class", IPC_MESSAGE_ID_CLASS(message->type()),
539 "line", IPC_MESSAGE_ID_LINE(message->type()));
540#endif
[email protected]3cdb7af812008-10-24 19:21:13541 if (!message->is_sync()) {
542 ChannelProxy::Send(message);
543 return true;
initial.commit09911bf2008-07-26 23:55:29544 }
545
rockot64e65de2016-06-21 20:17:49546 SyncMessage* sync_msg = static_cast<SyncMessage*>(message);
547 bool pump_messages = sync_msg->ShouldPumpMessages();
548
[email protected]3cdb7af812008-10-24 19:21:13549 // *this* might get deleted in WaitForReply.
550 scoped_refptr<SyncContext> context(sync_context());
rockot64e65de2016-06-21 20:17:49551 if (!context->Push(sync_msg)) {
552 DVLOG(1) << "Channel is shutting down. Dropping sync message.";
[email protected]3cdb7af812008-10-24 19:21:13553 delete message;
554 return false;
555 }
556
initial.commit09911bf2008-07-26 23:55:29557 ChannelProxy::Send(message);
initial.commit09911bf2008-07-26 23:55:29558
[email protected]3cdb7af812008-10-24 19:21:13559 // Wait for reply, or for any other incoming synchronous messages.
[email protected]9eec2252009-12-01 02:34:18560 // *this* might get deleted, so only call static functions at this point.
rockot64e65de2016-06-21 20:17:49561 scoped_refptr<mojo::SyncHandleRegistry> registry = sync_handle_registry_;
562 scoped_refptr<PumpMessagesEvent> pump_messages_event = pump_messages_event_;
563 WaitForReply(registry.get(), context.get(),
564 pump_messages ? pump_messages_event->event() : nullptr);
initial.commit09911bf2008-07-26 23:55:29565
tzika08b2fd2016-03-30 02:32:59566 TRACE_EVENT_FLOW_END0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
567 "SyncChannel::Send", context->GetSendDoneEvent());
568
[email protected]3cdb7af812008-10-24 19:21:13569 return context->Pop();
initial.commit09911bf2008-07-26 23:55:29570}
571
rockot64e65de2016-06-21 20:17:49572void SyncChannel::WaitForReply(mojo::SyncHandleRegistry* registry,
573 SyncContext* context,
574 const MojoEvent* pump_messages_event) {
[email protected]54af05f2011-04-08 03:38:21575 context->DispatchMessages();
rockot6d7be622016-06-15 18:25:19576
rockot64e65de2016-06-21 20:17:49577 while (true) {
578 bool dispatch = false;
579 bool send_done = false;
580 bool should_pump_messages = false;
581 bool error = false;
582 registry->RegisterHandle(context->GetDispatchEvent()->GetHandle(),
583 MOJO_HANDLE_SIGNAL_READABLE,
584 base::Bind(&OnSyncHandleReady, &dispatch, &error));
585 registry->RegisterHandle(
586 context->GetSendDoneEvent()->GetHandle(),
587 MOJO_HANDLE_SIGNAL_READABLE,
588 base::Bind(&OnSyncHandleReady, &send_done, &error));
589 if (pump_messages_event) {
590 registry->RegisterHandle(
591 pump_messages_event->GetHandle(), MOJO_HANDLE_SIGNAL_READABLE,
592 base::Bind(&OnSyncHandleReady, &should_pump_messages, &error));
593 }
594
595 const bool* stop_flags[] = { &dispatch, &send_done, &should_pump_messages };
596 registry->WatchAllHandles(stop_flags, 3);
597 DCHECK(!error);
598
599 registry->UnregisterHandle(context->GetDispatchEvent()->GetHandle());
600 registry->UnregisterHandle(context->GetSendDoneEvent()->GetHandle());
601 if (pump_messages_event)
602 registry->UnregisterHandle(pump_messages_event->GetHandle());
603
604 if (dispatch) {
[email protected]3cdb7af812008-10-24 19:21:13605 // We're waiting for a reply, but we received a blocking synchronous
606 // call. We must process it or otherwise a deadlock might occur.
[email protected]9eec2252009-12-01 02:34:18607 context->GetDispatchEvent()->Reset();
608 context->DispatchMessages();
[email protected]3cdb7af812008-10-24 19:21:13609 continue;
610 }
611
rockot64e65de2016-06-21 20:17:49612 if (should_pump_messages)
[email protected]9eec2252009-12-01 02:34:18613 WaitForReplyWithNestedMessageLoop(context); // Run a nested message loop.
[email protected]3cdb7af812008-10-24 19:21:13614
615 break;
616 }
617}
618
[email protected]9eec2252009-12-01 02:34:18619void SyncChannel::WaitForReplyWithNestedMessageLoop(SyncContext* context) {
rockot64e65de2016-06-21 20:17:49620 mojo::Watcher send_done_watcher;
[email protected]ac0efda2009-10-14 16:22:02621
[email protected]9eec2252009-12-01 02:34:18622 ReceivedSyncMsgQueue* sync_msg_queue = context->received_sync_msgs();
rockot64e65de2016-06-21 20:17:49623 DCHECK_NE(sync_msg_queue, nullptr);
[email protected]ac0efda2009-10-14 16:22:02624
rockot64e65de2016-06-21 20:17:49625 mojo::Watcher* old_watcher = sync_msg_queue->top_send_done_watcher();
626 mojo::Handle old_handle(mojo::kInvalidHandleValue);
627 mojo::Watcher::ReadyCallback old_callback;
[email protected]ac0efda2009-10-14 16:22:02628
rockot64e65de2016-06-21 20:17:49629 // Maintain a thread-local stack of watchers to ensure nested calls complete
630 // in the correct sequence, i.e. the outermost call completes first, etc.
631 if (old_watcher) {
632 old_callback = old_watcher->ready_callback();
633 old_handle = old_watcher->handle();
634 old_watcher->Cancel();
[email protected]ac0efda2009-10-14 16:22:02635 }
636
637 sync_msg_queue->set_top_send_done_watcher(&send_done_watcher);
638
rockot7b7e60f2016-06-16 23:14:40639 {
rockot64e65de2016-06-21 20:17:49640 base::RunLoop nested_loop;
641 send_done_watcher.Start(
642 context->GetSendDoneEvent()->GetHandle(), MOJO_HANDLE_SIGNAL_READABLE,
643 base::Bind(&RunOnHandleReady, nested_loop.QuitClosure()));
644
[email protected]fd0a773a2013-04-30 20:55:03645 base::MessageLoop::ScopedNestableTaskAllower allow(
646 base::MessageLoop::current());
rockot64e65de2016-06-21 20:17:49647 nested_loop.Run();
648 send_done_watcher.Cancel();
[email protected]b5717a42012-02-14 19:33:52649 }
[email protected]ac0efda2009-10-14 16:22:02650
rockot64e65de2016-06-21 20:17:49651 sync_msg_queue->set_top_send_done_watcher(old_watcher);
652 if (old_watcher)
653 old_watcher->Start(old_handle, MOJO_HANDLE_SIGNAL_READABLE, old_callback);
[email protected]3cdb7af812008-10-24 19:21:13654}
655
rockot64e65de2016-06-21 20:17:49656void SyncChannel::OnDispatchHandleReady(MojoResult result) {
657 DCHECK(result == MOJO_RESULT_OK || result == MOJO_RESULT_ABORTED);
658 if (result == MOJO_RESULT_OK) {
659 sync_context()->GetDispatchEvent()->Reset();
660 sync_context()->DispatchMessages();
661 }
initial.commit09911bf2008-07-26 23:55:29662}
663
[email protected]952394af2011-11-16 01:06:46664void SyncChannel::StartWatching() {
665 // Ideally we only want to watch this object when running a nested message
666 // loop. However, we don't know when it exits if there's another nested
667 // message loop running under it or not, so we wouldn't know whether to
rockot64e65de2016-06-21 20:17:49668 // stop or keep watching. So we always watch it.
669 dispatch_watcher_.Start(sync_context()->GetDispatchEvent()->GetHandle(),
670 MOJO_HANDLE_SIGNAL_READABLE,
671 base::Bind(&SyncChannel::OnDispatchHandleReady,
672 base::Unretained(this)));
[email protected]952394af2011-11-16 01:06:46673}
674
rockot29ade1b2015-08-07 06:23:59675void SyncChannel::OnChannelInit() {
676 for (const auto& filter : pre_init_sync_message_filters_) {
677 filter->set_is_channel_send_thread_safe(
678 context()->IsChannelSendThreadSafe());
679 }
680 pre_init_sync_message_filters_.clear();
681}
682
initial.commit09911bf2008-07-26 23:55:29683} // namespace IPC