• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 MOJO_PUBLIC_CPP_BINDINGS_CONNECTOR_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_CONNECTOR_H_
7 
8 #include <memory>
9 
10 #include "base/callback.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/threading/thread_checker.h"
15 #include "mojo/public/cpp/bindings/message.h"
16 #include "mojo/public/cpp/bindings/sync_handle_watcher.h"
17 #include "mojo/public/cpp/system/core.h"
18 #include "mojo/public/cpp/system/watcher.h"
19 
20 namespace base {
21 class Lock;
22 }
23 
24 namespace mojo {
25 
26 // The Connector class is responsible for performing read/write operations on a
27 // MessagePipe. It writes messages it receives through the MessageReceiver
28 // interface that it subclasses, and it forwards messages it reads through the
29 // MessageReceiver interface assigned as its incoming receiver.
30 //
31 // NOTE:
32 //   - MessagePipe I/O is non-blocking.
33 //   - Sending messages can be configured to be thread safe (please see comments
34 //     of the constructor). Other than that, the object should only be accessed
35 //     on the creating thread.
36 class Connector : public MessageReceiver {
37  public:
38   enum ConnectorConfig {
39     // Connector::Accept() is only called from a single thread.
40     SINGLE_THREADED_SEND,
41     // Connector::Accept() is allowed to be called from multiple threads.
42     MULTI_THREADED_SEND
43   };
44 
45   // The Connector takes ownership of |message_pipe|.
46   Connector(ScopedMessagePipeHandle message_pipe,
47             ConnectorConfig config,
48             scoped_refptr<base::SingleThreadTaskRunner> runner);
49   ~Connector() override;
50 
51   // Sets the receiver to handle messages read from the message pipe.  The
52   // Connector will read messages from the pipe regardless of whether or not an
53   // incoming receiver has been set.
set_incoming_receiver(MessageReceiver * receiver)54   void set_incoming_receiver(MessageReceiver* receiver) {
55     DCHECK(thread_checker_.CalledOnValidThread());
56     incoming_receiver_ = receiver;
57   }
58 
59   // Errors from incoming receivers will force the connector into an error
60   // state, where no more messages will be processed. This method is used
61   // during testing to prevent that from happening.
set_enforce_errors_from_incoming_receiver(bool enforce)62   void set_enforce_errors_from_incoming_receiver(bool enforce) {
63     DCHECK(thread_checker_.CalledOnValidThread());
64     enforce_errors_from_incoming_receiver_ = enforce;
65   }
66 
67   // Sets the error handler to receive notifications when an error is
68   // encountered while reading from the pipe or waiting to read from the pipe.
set_connection_error_handler(const base::Closure & error_handler)69   void set_connection_error_handler(const base::Closure& error_handler) {
70     DCHECK(thread_checker_.CalledOnValidThread());
71     connection_error_handler_ = error_handler;
72   }
73 
74   // Returns true if an error was encountered while reading from the pipe or
75   // waiting to read from the pipe.
encountered_error()76   bool encountered_error() const {
77     DCHECK(thread_checker_.CalledOnValidThread());
78     return error_;
79   }
80 
81   // Closes the pipe. The connector is put into a quiescent state.
82   //
83   // Please note that this method shouldn't be called unless it results from an
84   // explicit request of the user of bindings (e.g., the user sets an
85   // InterfacePtr to null or closes a Binding).
86   void CloseMessagePipe();
87 
88   // Releases the pipe. Connector is put into a quiescent state.
89   ScopedMessagePipeHandle PassMessagePipe();
90 
91   // Enters the error state. The upper layer may do this for unrecoverable
92   // issues such as invalid messages are received. If a connection error handler
93   // has been set, it will be called asynchronously.
94   //
95   // It is a no-op if the connector is already in the error state or there isn't
96   // a bound message pipe. Otherwise, it closes the message pipe, which notifies
97   // the other end and also prevents potential danger (say, the caller raises
98   // an error because it believes the other end is malicious). In order to
99   // appear to the user that the connector still binds to a message pipe, it
100   // creates a new message pipe, closes one end and binds to the other.
101   void RaiseError();
102 
103   // Is the connector bound to a MessagePipe handle?
is_valid()104   bool is_valid() const {
105     DCHECK(thread_checker_.CalledOnValidThread());
106     return message_pipe_.is_valid();
107   }
108 
109   // Waits for the next message on the pipe, blocking until one arrives,
110   // |deadline| elapses, or an error happens. Returns |true| if a message has
111   // been delivered, |false| otherwise.
112   bool WaitForIncomingMessage(MojoDeadline deadline);
113 
114   // See Binding for details of pause/resume.
115   void PauseIncomingMethodCallProcessing();
116   void ResumeIncomingMethodCallProcessing();
117 
118   // MessageReceiver implementation:
119   bool Accept(Message* message) override;
120 
handle()121   MessagePipeHandle handle() const {
122     DCHECK(thread_checker_.CalledOnValidThread());
123     return message_pipe_.get();
124   }
125 
126   // Allows |message_pipe_| to be watched while others perform sync handle
127   // watching on the same thread. Please see comments of
128   // SyncHandleWatcher::AllowWokenUpBySyncWatchOnSameThread().
129   void AllowWokenUpBySyncWatchOnSameThread();
130 
131   // Watches |message_pipe_| (as well as other handles registered to be watched
132   // together) synchronously.
133   // This method:
134   //   - returns true when |should_stop| is set to true;
135   //   - return false when any error occurs, including |message_pipe_| being
136   //     closed.
137   bool SyncWatch(const bool* should_stop);
138 
139   // Whether currently the control flow is inside the sync handle watcher
140   // callback.
during_sync_handle_watcher_callback()141   bool during_sync_handle_watcher_callback() const {
142     return sync_handle_watcher_callback_count_ > 0;
143   }
144 
task_runner()145   base::SingleThreadTaskRunner* task_runner() const {
146     return task_runner_.get();
147   }
148 
149  private:
150   // Callback of mojo::Watcher.
151   void OnWatcherHandleReady(MojoResult result);
152   // Callback of SyncHandleWatcher.
153   void OnSyncHandleWatcherHandleReady(MojoResult result);
154   void OnHandleReadyInternal(MojoResult result);
155 
156   void WaitToReadMore();
157 
158   // Returns false if |this| was destroyed during message dispatch.
159   WARN_UNUSED_RESULT bool ReadSingleMessage(MojoResult* read_result);
160 
161   // |this| can be destroyed during message dispatch.
162   void ReadAllAvailableMessages();
163 
164   // If |force_pipe_reset| is true, this method replaces the existing
165   // |message_pipe_| with a dummy message pipe handle (whose peer is closed).
166   // If |force_async_handler| is true, |connection_error_handler_| is called
167   // asynchronously.
168   void HandleError(bool force_pipe_reset, bool force_async_handler);
169 
170   // Cancels any calls made to |waiter_|.
171   void CancelWait();
172 
173   void EnsureSyncWatcherExists();
174 
175   base::Closure connection_error_handler_;
176 
177   ScopedMessagePipeHandle message_pipe_;
178   MessageReceiver* incoming_receiver_;
179 
180   scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
181   Watcher handle_watcher_;
182 
183   bool error_;
184   bool drop_writes_;
185   bool enforce_errors_from_incoming_receiver_;
186 
187   bool paused_;
188 
189   // If sending messages is allowed from multiple threads, |lock_| is used to
190   // protect modifications to |message_pipe_| and |drop_writes_|.
191   std::unique_ptr<base::Lock> lock_;
192 
193   std::unique_ptr<SyncHandleWatcher> sync_watcher_;
194   bool allow_woken_up_by_others_;
195   // If non-zero, currently the control flow is inside the sync handle watcher
196   // callback.
197   size_t sync_handle_watcher_callback_count_;
198 
199   base::ThreadChecker thread_checker_;
200 
201   // Create a single weak ptr and use it everywhere, to avoid the malloc/free
202   // cost of creating a new weak ptr whenever it is needed.
203   base::WeakPtr<Connector> weak_self_;
204   base::WeakPtrFactory<Connector> weak_factory_;
205 
206   DISALLOW_COPY_AND_ASSIGN(Connector);
207 };
208 
209 }  // namespace mojo
210 
211 #endif  // MOJO_PUBLIC_CPP_BINDINGS_CONNECTOR_H_
212