xref: /aosp_15_r20/external/cronet/ipc/ipc_sync_channel.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #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/memory/raw_ptr.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/synchronization/lock.h"
17 #include "base/synchronization/waitable_event_watcher.h"
18 #include "base/task/single_thread_task_runner.h"
19 #include "ipc/ipc_channel_handle.h"
20 #include "ipc/ipc_channel_proxy.h"
21 #include "ipc/ipc_sync_message.h"
22 #include "ipc/ipc_sync_message_filter.h"
23 #include "mojo/public/c/system/types.h"
24 #include "mojo/public/cpp/system/simple_watcher.h"
25 
26 namespace base {
27 class RunLoop;
28 class WaitableEvent;
29 }  // namespace base
30 
31 namespace mojo {
32 class SyncHandleRegistry;
33 }
34 
35 namespace IPC {
36 
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   class ReceivedSyncMsgQueue;
76 
77   enum RestrictDispatchGroup {
78     kRestrictDispatchGroup_None = 0,
79   };
80 
81   // Creates and initializes a sync channel. If create_pipe_now is specified,
82   // the channel will be initialized synchronously.
83   // The naming pattern follows IPC::Channel.
84   static std::unique_ptr<SyncChannel> Create(
85       const IPC::ChannelHandle& channel_handle,
86       IPC::Channel::Mode mode,
87       Listener* listener,
88       const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
89       const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
90       bool create_pipe_now,
91       base::WaitableEvent* shutdown_event);
92 
93   // Creates an uninitialized sync channel. Call ChannelProxy::Init to
94   // initialize the channel. This two-step setup allows message filters to be
95   // added before any messages are sent or received.
96   static std::unique_ptr<SyncChannel> Create(
97       Listener* listener,
98       const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
99       const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
100       base::WaitableEvent* shutdown_event);
101 
102   void AddListenerTaskRunner(
103       int32_t routing_id,
104       scoped_refptr<base::SingleThreadTaskRunner> task_runner);
105 
106   void RemoveListenerTaskRunner(int32_t routing_id);
107 
108   SyncChannel(const SyncChannel&) = delete;
109   SyncChannel& operator=(const SyncChannel&) = delete;
110 
111   ~SyncChannel() override;
112 
113   bool Send(Message* message) override;
114 
115   // Sets the dispatch group for this channel, to only allow re-entrant dispatch
116   // of messages to other channels in the same group.
117   //
118   // Normally, any unblocking message coming from any channel can be dispatched
119   // when any (possibly other) channel is blocked on sending a message. This is
120   // needed in some cases to unblock certain loops (e.g. necessary when some
121   // processes share a window hierarchy), but may cause re-entrancy issues in
122   // some cases where such loops are not possible. This flags allows the tagging
123   // of some particular channels to only re-enter in known correct cases.
124   //
125   // Incoming messages on channels belonging to a group that is not
126   // kRestrictDispatchGroup_None will only be dispatched while a sync message is
127   // being sent on a channel of the *same* group.
128   // Incoming messages belonging to the kRestrictDispatchGroup_None group (the
129   // default) will be dispatched in any case.
130   void SetRestrictDispatchChannelGroup(int group);
131 
132   // Creates a new IPC::SyncMessageFilter and adds it to this SyncChannel.
133   // This should be used instead of directly constructing a new
134   // SyncMessageFilter.
135   scoped_refptr<IPC::SyncMessageFilter> CreateSyncMessageFilter();
136 
137  protected:
138   friend class ReceivedSyncMsgQueue;
139 
140   // SyncContext holds the per object data for SyncChannel, so that SyncChannel
141   // can be deleted while it's being used in a different thread.  See
142   // ChannelProxy::Context for more information.
143   class SyncContext : public Context {
144    public:
145     SyncContext(
146         Listener* listener,
147         const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
148         const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
149         base::WaitableEvent* shutdown_event);
150 
151     // Adds information about an outgoing sync message to the context so that
152     // we know how to deserialize the reply.
153     bool Push(SyncMessage* sync_msg);
154 
155     // Cleanly remove the top deserializer (and throw it away).  Returns the
156     // result of the Send call for that message.
157     bool Pop();
158 
159     // Returns a Mojo Event that signals when a sync send is complete or timed
160     // out or the process shut down.
161     base::WaitableEvent* GetSendDoneEvent();
162 
163     // Returns a Mojo Event that signals when an incoming message that's not the
164     // pending reply needs to get dispatched (by calling DispatchMessages.)
165     base::WaitableEvent* GetDispatchEvent();
166 
167     void DispatchMessages();
168 
169     // Checks if the given message is blocking the listener thread because of a
170     // synchronous send.  If it is, the thread is unblocked and true is
171     // returned. Otherwise the function returns false.
172     bool TryToUnblockListener(const Message* msg);
173 
174     base::WaitableEvent* shutdown_event() { return shutdown_event_; }
175 
176     ReceivedSyncMsgQueue* received_sync_msgs() {
177       return received_sync_msgs_.get();
178     }
179 
180     void set_restrict_dispatch_group(int group) {
181       restrict_dispatch_group_ = group;
182     }
183 
184     int restrict_dispatch_group() const {
185       return restrict_dispatch_group_;
186     }
187 
188     void OnSendDoneEventSignaled(base::RunLoop* nested_loop,
189                                  base::WaitableEvent* event);
190 
191    private:
192     ~SyncContext() override;
193     // ChannelProxy methods that we override.
194 
195     // Called on the listener thread.
196     void Clear() override;
197 
198     // Called on the IPC thread.
199     bool OnMessageReceived(const Message& msg) override;
200     void OnChannelError() override;
201     void OnChannelOpened() override;
202     void OnChannelClosed() override;
203 
204     // Cancels all pending Send calls.
205     void CancelPendingSends();
206 
207     void OnShutdownEventSignaled(base::WaitableEvent* event);
208 
209     using PendingSyncMessageQueue = base::circular_deque<PendingSyncMsg>;
210     PendingSyncMessageQueue deserializers_;
211     bool reject_new_deserializers_ = false;
212     base::Lock deserializers_lock_;
213 
214     scoped_refptr<ReceivedSyncMsgQueue> received_sync_msgs_;
215 
216     raw_ptr<base::WaitableEvent, AcrossTasksDanglingUntriaged> shutdown_event_;
217     base::WaitableEventWatcher shutdown_watcher_;
218     base::WaitableEventWatcher::EventCallback shutdown_watcher_callback_;
219     int restrict_dispatch_group_;
220   };
221 
222  private:
223   SyncChannel(
224       Listener* listener,
225       const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
226       const scoped_refptr<base::SingleThreadTaskRunner>& listener_task_runner,
227       base::WaitableEvent* shutdown_event);
228 
229   void OnDispatchEventSignaled(base::WaitableEvent* event);
230 
231   SyncContext* sync_context() {
232     return reinterpret_cast<SyncContext*>(context());
233   }
234 
235   // Waits for a reply, timeout or process shutdown.
236   static void WaitForReply(mojo::SyncHandleRegistry* registry,
237                            SyncContext* context);
238 
239   // Starts the dispatch watcher.
240   void StartWatching();
241 
242   // ChannelProxy overrides:
243   void OnChannelInit() override;
244 
245   scoped_refptr<mojo::SyncHandleRegistry> sync_handle_registry_;
246 
247   // Used to signal events between the IPC and listener threads.
248   base::WaitableEventWatcher dispatch_watcher_;
249   base::WaitableEventWatcher::EventCallback dispatch_watcher_callback_;
250 
251   // Tracks SyncMessageFilters created before complete channel initialization.
252   std::vector<scoped_refptr<SyncMessageFilter>> pre_init_sync_message_filters_;
253 };
254 
255 }  // namespace IPC
256 
257 #endif  // IPC_IPC_SYNC_CHANNEL_H_
258