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.
5 #ifndef IPC_IPC_SYNC_CHANNEL_H_
6 #define IPC_IPC_SYNC_CHANNEL_H_
12 #include "base/basictypes.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/synchronization/lock.h"
15 #include "base/synchronization/waitable_event_watcher.h"
16 #include "ipc/ipc_channel_handle.h"
17 #include "ipc/ipc_channel_proxy.h"
18 #include "ipc/ipc_sync_message.h"
19 #include "ipc/ipc_sync_message_filter.h"
30 // This is similar to ChannelProxy, with the added feature of supporting sending
31 // synchronous messages.
33 // Overview of how the sync channel works
34 // --------------------------------------
35 // When the sending thread sends a synchronous message, we create a bunch
36 // of tracking info (created in Send, stored in the PendingSyncMsg
37 // structure) associated with the message that we identify by the unique
38 // "MessageId" on the SyncMessage. Among the things we save is the
39 // "Deserializer" which is provided by the sync message. This object is in
40 // charge of reading the parameters from the reply message and putting them in
41 // the output variables provided by its caller.
43 // The info gets stashed in a queue since we could have a nested stack of sync
44 // messages (each side could send sync messages in response to sync messages,
45 // so it works like calling a function). The message is sent to the I/O thread
46 // for dispatch and the original thread blocks waiting for the reply.
48 // SyncContext maintains the queue in a threadsafe way and listens for replies
49 // on the I/O thread. When a reply comes in that matches one of the messages
50 // it's looking for (using the unique message ID), it will execute the
51 // deserializer stashed from before, and unblock the original thread.
54 // Significant complexity results from the fact that messages are still coming
55 // in while the original thread is blocked. Normal async messages are queued
56 // and dispatched after the blocking call is complete. Sync messages must
57 // be dispatched in a reentrant manner to avoid deadlock.
60 // Note that care must be taken that the lifetime of the ipc_thread argument
61 // is more than this object. If the message loop goes away while this object
62 // is running and it's used to send a message, then it will use the invalid
63 // message loop pointer to proxy it to the ipc thread.
64 class IPC_EXPORT SyncChannel
: public ChannelProxy
{
66 enum RestrictDispatchGroup
{
67 kRestrictDispatchGroup_None
= 0,
70 // Creates and initializes a sync channel. If create_pipe_now is specified,
71 // the channel will be initialized synchronously.
72 // The naming pattern follows IPC::Channel.
73 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
74 // make the upcoming refactor decomposable into smaller CLs.
75 // http://crbug.com/493414.
76 static scoped_ptr
<SyncChannel
> Create(
77 const IPC::ChannelHandle
& channel_handle
,
78 IPC::Channel::Mode mode
,
80 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
,
82 base::WaitableEvent
* shutdown_event
,
83 AttachmentBroker
* broker
= nullptr);
85 static scoped_ptr
<SyncChannel
> Create(
86 scoped_ptr
<ChannelFactory
> factory
,
88 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
,
90 base::WaitableEvent
* shutdown_event
);
92 // Creates an uninitialized sync channel. Call ChannelProxy::Init to
93 // initialize the channel. This two-step setup allows message filters to be
94 // added before any messages are sent or received.
95 static scoped_ptr
<SyncChannel
> Create(
97 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
,
98 base::WaitableEvent
* shutdown_event
);
100 ~SyncChannel() override
;
102 bool Send(Message
* message
) override
;
104 // Sets the dispatch group for this channel, to only allow re-entrant dispatch
105 // of messages to other channels in the same group.
107 // Normally, any unblocking message coming from any channel can be dispatched
108 // when any (possibly other) channel is blocked on sending a message. This is
109 // needed in some cases to unblock certain loops (e.g. necessary when some
110 // processes share a window hierarchy), but may cause re-entrancy issues in
111 // some cases where such loops are not possible. This flags allows the tagging
112 // of some particular channels to only re-enter in known correct cases.
114 // Incoming messages on channels belonging to a group that is not
115 // kRestrictDispatchGroup_None will only be dispatched while a sync message is
116 // being sent on a channel of the *same* group.
117 // Incoming messages belonging to the kRestrictDispatchGroup_None group (the
118 // default) will be dispatched in any case.
119 void SetRestrictDispatchChannelGroup(int group
);
121 // Creates a new IPC::SyncMessageFilter and adds it to this SyncChannel.
122 // This should be used instead of directly constructing a new
123 // SyncMessageFilter.
124 scoped_refptr
<IPC::SyncMessageFilter
> CreateSyncMessageFilter();
127 class ReceivedSyncMsgQueue
;
128 friend class ReceivedSyncMsgQueue
;
130 // SyncContext holds the per object data for SyncChannel, so that SyncChannel
131 // can be deleted while it's being used in a different thread. See
132 // ChannelProxy::Context for more information.
133 class SyncContext
: public Context
{
137 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
,
138 base::WaitableEvent
* shutdown_event
);
140 // Adds information about an outgoing sync message to the context so that
141 // we know how to deserialize the reply.
142 void Push(SyncMessage
* sync_msg
);
144 // Cleanly remove the top deserializer (and throw it away). Returns the
145 // result of the Send call for that message.
148 // Returns an event that's set when the send is complete, timed out or the
149 // process shut down.
150 base::WaitableEvent
* GetSendDoneEvent();
152 // Returns an event that's set when an incoming message that's not the reply
153 // needs to get dispatched (by calling SyncContext::DispatchMessages).
154 base::WaitableEvent
* GetDispatchEvent();
156 void DispatchMessages();
158 // Checks if the given message is blocking the listener thread because of a
159 // synchronous send. If it is, the thread is unblocked and true is
160 // returned. Otherwise the function returns false.
161 bool TryToUnblockListener(const Message
* msg
);
163 // Called on the IPC thread when a sync send that runs a nested message loop
165 void OnSendTimeout(int message_id
);
167 base::WaitableEvent
* shutdown_event() { return shutdown_event_
; }
169 ReceivedSyncMsgQueue
* received_sync_msgs() {
170 return received_sync_msgs_
.get();
173 void set_restrict_dispatch_group(int group
) {
174 restrict_dispatch_group_
= group
;
177 int restrict_dispatch_group() const {
178 return restrict_dispatch_group_
;
181 base::WaitableEventWatcher::EventCallback
MakeWaitableEventCallback();
184 ~SyncContext() override
;
185 // ChannelProxy methods that we override.
187 // Called on the listener thread.
188 void Clear() override
;
190 // Called on the IPC thread.
191 bool OnMessageReceived(const Message
& msg
) override
;
192 void OnChannelError() override
;
193 void OnChannelOpened() override
;
194 void OnChannelClosed() override
;
196 // Cancels all pending Send calls.
197 void CancelPendingSends();
199 void OnWaitableEventSignaled(base::WaitableEvent
* event
);
201 typedef std::deque
<PendingSyncMsg
> PendingSyncMessageQueue
;
202 PendingSyncMessageQueue deserializers_
;
203 base::Lock deserializers_lock_
;
205 scoped_refptr
<ReceivedSyncMsgQueue
> received_sync_msgs_
;
207 base::WaitableEvent
* shutdown_event_
;
208 base::WaitableEventWatcher shutdown_watcher_
;
209 base::WaitableEventWatcher::EventCallback shutdown_watcher_callback_
;
210 int restrict_dispatch_group_
;
216 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
,
217 base::WaitableEvent
* shutdown_event
);
219 void OnWaitableEventSignaled(base::WaitableEvent
* arg
);
221 SyncContext
* sync_context() {
222 return reinterpret_cast<SyncContext
*>(context());
225 // Both these functions wait for a reply, timeout or process shutdown. The
226 // latter one also runs a nested message loop in the meantime.
227 static void WaitForReply(
228 SyncContext
* context
, base::WaitableEvent
* pump_messages_event
);
230 // Runs a nested message loop until a reply arrives, times out, or the process
232 static void WaitForReplyWithNestedMessageLoop(SyncContext
* context
);
234 // Starts the dispatch watcher.
235 void StartWatching();
237 // ChannelProxy overrides:
238 void OnChannelInit() override
;
240 // Used to signal events between the IPC and listener threads.
241 base::WaitableEventWatcher dispatch_watcher_
;
242 base::WaitableEventWatcher::EventCallback dispatch_watcher_callback_
;
244 // Tracks SyncMessageFilters created before complete channel initialization.
245 std::vector
<scoped_refptr
<SyncMessageFilter
>> pre_init_sync_message_filters_
;
247 DISALLOW_COPY_AND_ASSIGN(SyncChannel
);
252 #endif // IPC_IPC_SYNC_CHANNEL_H_