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