1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef IPC_IPC_SYNC_CHANNEL_H_
6 #define IPC_IPC_SYNC_CHANNEL_H_
7
8 #include <memory>
9 #include <string>
10 #include <vector>
11
12 #include "base/component_export.h"
13 #include "base/containers/circular_deque.h"
14 #include "base/macros.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/synchronization/lock.h"
17 #include "base/synchronization/waitable_event_watcher.h"
18 #include "ipc/ipc_channel_handle.h"
19 #include "ipc/ipc_channel_proxy.h"
20 #include "ipc/ipc_sync_message.h"
21 #include "ipc/ipc_sync_message_filter.h"
22 #include "mojo/public/c/system/types.h"
23 #include "mojo/public/cpp/system/simple_watcher.h"
24
25 namespace base {
26 class RunLoop;
27 class WaitableEvent;
28 };
29
30 namespace mojo {
31 class SyncHandleRegistry;
32 }
33
34 namespace IPC {
35
36 class ChannelFactory;
37 class SyncMessage;
38
39 // This is similar to ChannelProxy, with the added feature of supporting sending
40 // synchronous messages.
41 //
42 // Overview of how the sync channel works
43 // --------------------------------------
44 // When the sending thread sends a synchronous message, we create a bunch
45 // of tracking info (created in Send, stored in the PendingSyncMsg
46 // structure) associated with the message that we identify by the unique
47 // "MessageId" on the SyncMessage. Among the things we save is the
48 // "Deserializer" which is provided by the sync message. This object is in
49 // charge of reading the parameters from the reply message and putting them in
50 // the output variables provided by its caller.
51 //
52 // The info gets stashed in a queue since we could have a nested stack of sync
53 // messages (each side could send sync messages in response to sync messages,
54 // so it works like calling a function). The message is sent to the I/O thread
55 // for dispatch and the original thread blocks waiting for the reply.
56 //
57 // SyncContext maintains the queue in a threadsafe way and listens for replies
58 // on the I/O thread. When a reply comes in that matches one of the messages
59 // it's looking for (using the unique message ID), it will execute the
60 // deserializer stashed from before, and unblock the original thread.
61 //
62 //
63 // Significant complexity results from the fact that messages are still coming
64 // in while the original thread is blocked. Normal async messages are queued
65 // and dispatched after the blocking call is complete. Sync messages must
66 // be dispatched in a reentrant manner to avoid deadlock.
67 //
68 //
69 // Note that care must be taken that the lifetime of the ipc_thread argument
70 // is more than this object. If the message loop goes away while this object
71 // is running and it's used to send a message, then it will use the invalid
72 // message loop pointer to proxy it to the ipc thread.
COMPONENT_EXPORT(IPC)73 class COMPONENT_EXPORT(IPC) SyncChannel : public ChannelProxy {
74 public:
75 enum RestrictDispatchGroup {
76 kRestrictDispatchGroup_None = 0,
77 };
78
79 // Creates and initializes a sync channel. If create_pipe_now is specified,
80 // the channel will be initialized synchronously.
81 // The naming pattern follows IPC::Channel.
82 static std::unique_ptr<SyncChannel> Create(
83 const IPC::ChannelHandle& channel_handle,
84 IPC::Channel::Mode mode,
85 Listener* listener,
86 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
87 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
88 bool create_pipe_now,
89 base::WaitableEvent* shutdown_event);
90
91 static std::unique_ptr<SyncChannel> Create(
92 std::unique_ptr<ChannelFactory> factory,
93 Listener* listener,
94 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
95 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
96 bool create_pipe_now,
97 base::WaitableEvent* shutdown_event);
98
99 // Creates an uninitialized sync channel. Call ChannelProxy::Init to
100 // initialize the channel. This two-step setup allows message filters to be
101 // added before any messages are sent or received.
102 static std::unique_ptr<SyncChannel> Create(
103 Listener* listener,
104 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
105 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
106 base::WaitableEvent* shutdown_event);
107
108 ~SyncChannel() override;
109
110 bool Send(Message* message) override;
111
112 // Sets the dispatch group for this channel, to only allow re-entrant dispatch
113 // of messages to other channels in the same group.
114 //
115 // Normally, any unblocking message coming from any channel can be dispatched
116 // when any (possibly other) channel is blocked on sending a message. This is
117 // needed in some cases to unblock certain loops (e.g. necessary when some
118 // processes share a window hierarchy), but may cause re-entrancy issues in
119 // some cases where such loops are not possible. This flags allows the tagging
120 // of some particular channels to only re-enter in known correct cases.
121 //
122 // Incoming messages on channels belonging to a group that is not
123 // kRestrictDispatchGroup_None will only be dispatched while a sync message is
124 // being sent on a channel of the *same* group.
125 // Incoming messages belonging to the kRestrictDispatchGroup_None group (the
126 // default) will be dispatched in any case.
127 void SetRestrictDispatchChannelGroup(int group);
128
129 // Creates a new IPC::SyncMessageFilter and adds it to this SyncChannel.
130 // This should be used instead of directly constructing a new
131 // SyncMessageFilter.
132 scoped_refptr<IPC::SyncMessageFilter> CreateSyncMessageFilter();
133
134 protected:
135 class ReceivedSyncMsgQueue;
136 friend class ReceivedSyncMsgQueue;
137
138 // SyncContext holds the per object data for SyncChannel, so that SyncChannel
139 // can be deleted while it's being used in a different thread. See
140 // ChannelProxy::Context for more information.
141 class SyncContext : public Context {
142 public:
143 SyncContext(
144 Listener* listener,
145 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
146 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
147 base::WaitableEvent* shutdown_event);
148
149 // Adds information about an outgoing sync message to the context so that
150 // we know how to deserialize the reply.
151 bool Push(SyncMessage* sync_msg);
152
153 // Cleanly remove the top deserializer (and throw it away). Returns the
154 // result of the Send call for that message.
155 bool Pop();
156
157 // Returns a Mojo Event that signals when a sync send is complete or timed
158 // out or the process shut down.
159 base::WaitableEvent* GetSendDoneEvent();
160
161 // Returns a Mojo Event that signals when an incoming message that's not the
162 // pending reply needs to get dispatched (by calling DispatchMessages.)
163 base::WaitableEvent* GetDispatchEvent();
164
165 void DispatchMessages();
166
167 // Checks if the given message is blocking the listener thread because of a
168 // synchronous send. If it is, the thread is unblocked and true is
169 // returned. Otherwise the function returns false.
170 bool TryToUnblockListener(const Message* msg);
171
172 base::WaitableEvent* shutdown_event() { return shutdown_event_; }
173
174 ReceivedSyncMsgQueue* received_sync_msgs() {
175 return received_sync_msgs_.get();
176 }
177
178 void set_restrict_dispatch_group(int group) {
179 restrict_dispatch_group_ = group;
180 }
181
182 int restrict_dispatch_group() const {
183 return restrict_dispatch_group_;
184 }
185
186 void OnSendDoneEventSignaled(base::RunLoop* nested_loop,
187 base::WaitableEvent* event);
188
189 private:
190 ~SyncContext() override;
191 // ChannelProxy methods that we override.
192
193 // Called on the listener thread.
194 void Clear() override;
195
196 // Called on the IPC thread.
197 bool OnMessageReceived(const Message& msg) override;
198 void OnChannelError() override;
199 void OnChannelOpened() override;
200 void OnChannelClosed() override;
201
202 // Cancels all pending Send calls.
203 void CancelPendingSends();
204
205 void OnShutdownEventSignaled(base::WaitableEvent* event);
206
207 using PendingSyncMessageQueue = base::circular_deque<PendingSyncMsg>;
208 PendingSyncMessageQueue deserializers_;
209 bool reject_new_deserializers_ = false;
210 base::Lock deserializers_lock_;
211
212 scoped_refptr<ReceivedSyncMsgQueue> received_sync_msgs_;
213
214 base::WaitableEvent* shutdown_event_;
215 base::WaitableEventWatcher shutdown_watcher_;
216 base::WaitableEventWatcher::EventCallback shutdown_watcher_callback_;
217 int restrict_dispatch_group_;
218 };
219
220 private:
221 SyncChannel(
222 Listener* listener,
223 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
224 const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
225 base::WaitableEvent* shutdown_event);
226
227 void OnDispatchEventSignaled(base::WaitableEvent* event);
228
229 SyncContext* sync_context() {
230 return reinterpret_cast<SyncContext*>(context());
231 }
232
233 // Both these functions wait for a reply, timeout or process shutdown. The
234 // latter one also runs a nested run loop in the meantime.
235 static void WaitForReply(mojo::SyncHandleRegistry* registry,
236 SyncContext* context,
237 bool pump_messages);
238
239 // Runs a nested run loop until a reply arrives, times out, or the process
240 // shuts down.
241 static void WaitForReplyWithNestedMessageLoop(SyncContext* context);
242
243 // Starts the dispatch watcher.
244 void StartWatching();
245
246 // ChannelProxy overrides:
247 void OnChannelInit() override;
248
249 scoped_refptr<mojo::SyncHandleRegistry> sync_handle_registry_;
250
251 // Used to signal events between the IPC and listener threads.
252 base::WaitableEventWatcher dispatch_watcher_;
253 base::WaitableEventWatcher::EventCallback dispatch_watcher_callback_;
254
255 // Tracks SyncMessageFilters created before complete channel initialization.
256 std::vector<scoped_refptr<SyncMessageFilter>> pre_init_sync_message_filters_;
257
258 DISALLOW_COPY_AND_ASSIGN(SyncChannel);
259 };
260
261 } // namespace IPC
262
263 #endif // IPC_IPC_SYNC_CHANNEL_H_
264