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_SYSTEM_DISPATCHER_H_ 6 #define MOJO_SYSTEM_DISPATCHER_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <vector> 12 13 #include "base/macros.h" 14 #include "base/memory/ref_counted.h" 15 #include "base/memory/scoped_ptr.h" 16 #include "base/synchronization/lock.h" 17 #include "mojo/embedder/platform_handle.h" 18 #include "mojo/embedder/platform_handle_vector.h" 19 #include "mojo/public/c/system/buffer.h" 20 #include "mojo/public/c/system/data_pipe.h" 21 #include "mojo/public/c/system/message_pipe.h" 22 #include "mojo/public/c/system/types.h" 23 #include "mojo/system/system_impl_export.h" 24 25 namespace mojo { 26 namespace system { 27 28 class Channel; 29 class Core; 30 class Dispatcher; 31 class DispatcherTransport; 32 class HandleTable; 33 class LocalMessagePipeEndpoint; 34 class ProxyMessagePipeEndpoint; 35 class RawSharedBufferMapping; 36 class TransportData; 37 class Waiter; 38 39 typedef std::vector<scoped_refptr<Dispatcher> > DispatcherVector; 40 41 namespace test { 42 43 // Test helper. We need to declare it here so we can friend it. 44 MOJO_SYSTEM_IMPL_EXPORT DispatcherTransport DispatcherTryStartTransport( 45 Dispatcher* dispatcher); 46 47 } // namespace test 48 49 // A |Dispatcher| implements Mojo primitives that are "attached" to a particular 50 // handle. This includes most (all?) primitives except for |MojoWait...()|. This 51 // object is thread-safe, with its state being protected by a single lock 52 // |lock_|, which is also made available to implementation subclasses (via the 53 // |lock()| method). 54 class MOJO_SYSTEM_IMPL_EXPORT Dispatcher : 55 public base::RefCountedThreadSafe<Dispatcher> { 56 public: 57 enum Type { 58 kTypeUnknown = 0, 59 kTypeMessagePipe, 60 kTypeDataPipeProducer, 61 kTypeDataPipeConsumer, 62 kTypeSharedBuffer, 63 64 // "Private" types (not exposed via the public interface): 65 kTypePlatformHandle = -1 66 }; 67 virtual Type GetType() const = 0; 68 69 // These methods implement the various primitives named |Mojo...()|. These 70 // take |lock_| and handle races with |Close()|. Then they call out to 71 // subclasses' |...ImplNoLock()| methods (still under |lock_|), which actually 72 // implement the primitives. 73 // NOTE(vtl): This puts a big lock around each dispatcher (i.e., handle), and 74 // prevents the various |...ImplNoLock()|s from releasing the lock as soon as 75 // possible. If this becomes an issue, we can rethink this. 76 MojoResult Close(); 77 78 // |transports| may be non-null if and only if there are handles to be 79 // written; not that |this| must not be in |transports|. On success, all the 80 // dispatchers in |transports| must have been moved to a closed state; on 81 // failure, they should remain in their original state. 82 MojoResult WriteMessage(const void* bytes, 83 uint32_t num_bytes, 84 std::vector<DispatcherTransport>* transports, 85 MojoWriteMessageFlags flags); 86 // |dispatchers| must be non-null but empty, if |num_dispatchers| is non-null 87 // and nonzero. On success, it will be set to the dispatchers to be received 88 // (and assigned handles) as part of the message. 89 MojoResult ReadMessage(void* bytes, 90 uint32_t* num_bytes, 91 DispatcherVector* dispatchers, 92 uint32_t* num_dispatchers, 93 MojoReadMessageFlags flags); 94 MojoResult WriteData(const void* elements, 95 uint32_t* elements_num_bytes, 96 MojoWriteDataFlags flags); 97 MojoResult BeginWriteData(void** buffer, 98 uint32_t* buffer_num_bytes, 99 MojoWriteDataFlags flags); 100 MojoResult EndWriteData(uint32_t num_bytes_written); 101 MojoResult ReadData(void* elements, 102 uint32_t* num_bytes, 103 MojoReadDataFlags flags); 104 MojoResult BeginReadData(const void** buffer, 105 uint32_t* buffer_num_bytes, 106 MojoReadDataFlags flags); 107 MojoResult EndReadData(uint32_t num_bytes_read); 108 // |options| may be null. |new_dispatcher| must not be null, but 109 // |*new_dispatcher| should be null (and will contain the dispatcher for the 110 // new handle on success). 111 MojoResult DuplicateBufferHandle( 112 const MojoDuplicateBufferHandleOptions* options, 113 scoped_refptr<Dispatcher>* new_dispatcher); 114 MojoResult MapBuffer(uint64_t offset, 115 uint64_t num_bytes, 116 MojoMapBufferFlags flags, 117 scoped_ptr<RawSharedBufferMapping>* mapping); 118 119 // Adds a waiter to this dispatcher. The waiter will be woken up when this 120 // object changes state to satisfy |signals| with context |context|. It will 121 // also be woken up when it becomes impossible for the object to ever satisfy 122 // |signals| with a suitable error status. 123 // 124 // Returns: 125 // - |MOJO_RESULT_OK| if the waiter was added; 126 // - |MOJO_RESULT_ALREADY_EXISTS| if |signals| is already satisfied; 127 // - |MOJO_RESULT_INVALID_ARGUMENT| if the dispatcher has been closed; and 128 // - |MOJO_RESULT_FAILED_PRECONDITION| if it is not (or no longer) possible 129 // that |signals| will ever be satisfied. 130 MojoResult AddWaiter(Waiter* waiter, 131 MojoHandleSignals signals, 132 uint32_t context); 133 void RemoveWaiter(Waiter* waiter); 134 135 // A dispatcher must be put into a special state in order to be sent across a 136 // message pipe. Outside of tests, only |HandleTableAccess| is allowed to do 137 // this, since there are requirements on the handle table (see below). 138 // 139 // In this special state, only a restricted set of operations is allowed. 140 // These are the ones available as |DispatcherTransport| methods. Other 141 // |Dispatcher| methods must not be called until |DispatcherTransport::End()| 142 // has been called. 143 class HandleTableAccess { 144 private: 145 friend class Core; 146 friend class HandleTable; 147 // Tests also need this, to avoid needing |Core|. 148 friend DispatcherTransport test::DispatcherTryStartTransport(Dispatcher*); 149 150 // This must be called under the handle table lock and only if the handle 151 // table entry is not marked busy. The caller must maintain a reference to 152 // |dispatcher| until |DispatcherTransport::End()| is called. 153 static DispatcherTransport TryStartTransport(Dispatcher* dispatcher); 154 }; 155 156 // A |TransportData| may serialize dispatchers that are given to it (and which 157 // were previously attached to the |MessageInTransit| that is creating it) to 158 // a given |Channel| and then (probably in a different process) deserialize. 159 // Note that the |MessageInTransit| "owns" (i.e., has the only ref to) these 160 // dispatchers, so there are no locking issues. (There's no lock ordering 161 // issue, and in fact no need to take dispatcher locks at all.) 162 // TODO(vtl): Consider making another wrapper similar to |DispatcherTransport| 163 // (but with an owning, unique reference), and having 164 // |CreateEquivalentDispatcherAndCloseImplNoLock()| return that wrapper (and 165 // |MessageInTransit|, etc. only holding on to such wrappers). 166 class TransportDataAccess { 167 private: 168 friend class TransportData; 169 170 // Serialization API. These functions may only be called on such 171 // dispatchers. (|channel| is the |Channel| to which the dispatcher is to be 172 // serialized.) See the |Dispatcher| methods of the same names for more 173 // details. 174 static void StartSerialize(Dispatcher* dispatcher, 175 Channel* channel, 176 size_t* max_size, 177 size_t* max_platform_handles); 178 static bool EndSerializeAndClose( 179 Dispatcher* dispatcher, 180 Channel* channel, 181 void* destination, 182 size_t* actual_size, 183 embedder::PlatformHandleVector* platform_handles); 184 185 // Deserialization API. 186 // Note: This "clears" (i.e., reset to the invalid handle) any platform 187 // handles that it takes ownership of. 188 static scoped_refptr<Dispatcher> Deserialize( 189 Channel* channel, 190 int32_t type, 191 const void* source, 192 size_t size, 193 embedder::PlatformHandleVector* platform_handles); 194 }; 195 196 protected: 197 friend class base::RefCountedThreadSafe<Dispatcher>; 198 199 Dispatcher(); 200 virtual ~Dispatcher(); 201 202 // These are to be overridden by subclasses (if necessary). They are called 203 // exactly once -- first |CancelAllWaitersNoLock()|, then |CloseImplNoLock()|, 204 // when the dispatcher is being closed. They are called under |lock_|. 205 virtual void CancelAllWaitersNoLock(); 206 virtual void CloseImplNoLock(); 207 virtual scoped_refptr<Dispatcher> 208 CreateEquivalentDispatcherAndCloseImplNoLock() = 0; 209 210 // These are to be overridden by subclasses (if necessary). They are never 211 // called after the dispatcher has been closed. They are called under |lock_|. 212 // See the descriptions of the methods without the "ImplNoLock" for more 213 // information. 214 virtual MojoResult WriteMessageImplNoLock( 215 const void* bytes, 216 uint32_t num_bytes, 217 std::vector<DispatcherTransport>* transports, 218 MojoWriteMessageFlags flags); 219 virtual MojoResult ReadMessageImplNoLock(void* bytes, 220 uint32_t* num_bytes, 221 DispatcherVector* dispatchers, 222 uint32_t* num_dispatchers, 223 MojoReadMessageFlags flags); 224 virtual MojoResult WriteDataImplNoLock(const void* elements, 225 uint32_t* num_bytes, 226 MojoWriteDataFlags flags); 227 virtual MojoResult BeginWriteDataImplNoLock(void** buffer, 228 uint32_t* buffer_num_bytes, 229 MojoWriteDataFlags flags); 230 virtual MojoResult EndWriteDataImplNoLock(uint32_t num_bytes_written); 231 virtual MojoResult ReadDataImplNoLock(void* elements, 232 uint32_t* num_bytes, 233 MojoReadDataFlags flags); 234 virtual MojoResult BeginReadDataImplNoLock(const void** buffer, 235 uint32_t* buffer_num_bytes, 236 MojoReadDataFlags flags); 237 virtual MojoResult EndReadDataImplNoLock(uint32_t num_bytes_read); 238 virtual MojoResult DuplicateBufferHandleImplNoLock( 239 const MojoDuplicateBufferHandleOptions* options, 240 scoped_refptr<Dispatcher>* new_dispatcher); 241 virtual MojoResult MapBufferImplNoLock( 242 uint64_t offset, 243 uint64_t num_bytes, 244 MojoMapBufferFlags flags, 245 scoped_ptr<RawSharedBufferMapping>* mapping); 246 virtual MojoResult AddWaiterImplNoLock(Waiter* waiter, 247 MojoHandleSignals signals, 248 uint32_t context); 249 virtual void RemoveWaiterImplNoLock(Waiter* waiter); 250 251 // These implement the API used to serialize dispatchers to a |Channel| 252 // (described below). They will only be called on a dispatcher that's attached 253 // to and "owned" by a |MessageInTransit|. See the non-"impl" versions for 254 // more information. 255 // 256 // Note: |StartSerializeImplNoLock()| is actually called with |lock_| NOT 257 // held, since the dispatcher should only be accessible to the calling thread. 258 // On Debug builds, |EndSerializeAndCloseImplNoLock()| is called with |lock_| 259 // held, to satisfy any |lock_.AssertAcquired()| (e.g., in |CloseImplNoLock()| 260 // -- and anything it calls); disentangling those assertions is 261 // difficult/fragile, and would weaken our general checking of invariants. 262 // 263 // TODO(vtl): Consider making these pure virtual once most things support 264 // being passed over a message pipe. 265 virtual void StartSerializeImplNoLock(Channel* channel, 266 size_t* max_size, 267 size_t* max_platform_handles); 268 virtual bool EndSerializeAndCloseImplNoLock( 269 Channel* channel, 270 void* destination, 271 size_t* actual_size, 272 embedder::PlatformHandleVector* platform_handles); 273 274 // Available to subclasses. (Note: Returns a non-const reference, just like 275 // |base::AutoLock|'s constructor takes a non-const reference.) 276 base::Lock& lock() const { return lock_; } 277 278 private: 279 friend class DispatcherTransport; 280 281 // This should be overridden to return true if/when there's an ongoing 282 // operation (e.g., two-phase read/writes on data pipes) that should prevent a 283 // handle from being sent over a message pipe (with status "busy"). 284 virtual bool IsBusyNoLock() const; 285 286 // Closes the dispatcher. This must be done under lock, and unlike |Close()|, 287 // the dispatcher must not be closed already. (This is the "equivalent" of 288 // |CreateEquivalentDispatcherAndCloseNoLock()|, for situations where the 289 // dispatcher must be disposed of instead of "transferred".) 290 void CloseNoLock(); 291 292 // Creates an equivalent dispatcher -- representing the same resource as this 293 // dispatcher -- and close (i.e., disable) this dispatcher. I.e., this 294 // dispatcher will look as though it was closed, but the resource it 295 // represents will be assigned to the new dispatcher. This must be called 296 // under the dispatcher's lock. 297 scoped_refptr<Dispatcher> CreateEquivalentDispatcherAndCloseNoLock(); 298 299 // API to serialize dispatchers to a |Channel|, exposed to only 300 // |TransportData| (via |TransportData|). They may only be called on a 301 // dispatcher attached to a |MessageInTransit| (and in particular not in 302 // |CoreImpl|'s handle table). 303 // 304 // Starts the serialization. Returns (via the two "out" parameters) the 305 // maximum amount of space that may be needed to serialize this dispatcher to 306 // the given |Channel| (no more than 307 // |TransportData::kMaxSerializedDispatcherSize|) and the maximum number of 308 // |PlatformHandle|s that may need to be attached (no more than 309 // |TransportData::kMaxSerializedDispatcherPlatformHandles|). If this 310 // dispatcher cannot be serialized to the given |Channel|, |*max_size| and 311 // |*max_platform_handles| should be set to zero. A call to this method will 312 // ALWAYS be followed by a call to |EndSerializeAndClose()| (even if this 313 // dispatcher cannot be serialized to the given |Channel|). 314 void StartSerialize(Channel* channel, 315 size_t* max_size, 316 size_t* max_platform_handles); 317 // Completes the serialization of this dispatcher to the given |Channel| and 318 // closes it. (This call will always follow an earlier call to 319 // |StartSerialize()|, with the same |Channel|.) This does so by writing to 320 // |destination| and appending any |PlatformHandle|s needed to 321 // |platform_handles| (which may be null if no platform handles were indicated 322 // to be required to |StartSerialize()|). This may write no more than the 323 // amount indicated by |StartSerialize()|. (WARNING: Beware of races, e.g., if 324 // something can be mutated between the two calls!) Returns true on success, 325 // in which case |*actual_size| is set to the amount it actually wrote to 326 // |destination|. On failure, |*actual_size| should not be modified; however, 327 // the dispatcher will still be closed. 328 bool EndSerializeAndClose(Channel* channel, 329 void* destination, 330 size_t* actual_size, 331 embedder::PlatformHandleVector* platform_handles); 332 333 // This protects the following members as well as any state added by 334 // subclasses. 335 mutable base::Lock lock_; 336 bool is_closed_; 337 338 DISALLOW_COPY_AND_ASSIGN(Dispatcher); 339 }; 340 341 // Wrapper around a |Dispatcher| pointer, while it's being processed to be 342 // passed in a message pipe. See the comment about 343 // |Dispatcher::HandleTableAccess| for more details. 344 // 345 // Note: This class is deliberately "thin" -- no more expensive than a 346 // |Dispatcher*|. 347 class MOJO_SYSTEM_IMPL_EXPORT DispatcherTransport { 348 public: 349 DispatcherTransport() : dispatcher_(NULL) {} 350 351 void End(); 352 353 Dispatcher::Type GetType() const { return dispatcher_->GetType(); } 354 bool IsBusy() const { return dispatcher_->IsBusyNoLock(); } 355 void Close() { dispatcher_->CloseNoLock(); } 356 scoped_refptr<Dispatcher> CreateEquivalentDispatcherAndClose() { 357 return dispatcher_->CreateEquivalentDispatcherAndCloseNoLock(); 358 } 359 360 bool is_valid() const { return !!dispatcher_; } 361 362 protected: 363 Dispatcher* dispatcher() { return dispatcher_; } 364 365 private: 366 friend class Dispatcher::HandleTableAccess; 367 368 explicit DispatcherTransport(Dispatcher* dispatcher) 369 : dispatcher_(dispatcher) {} 370 371 Dispatcher* dispatcher_; 372 373 // Copy and assign allowed. 374 }; 375 376 } // namespace system 377 } // namespace mojo 378 379 #endif // MOJO_SYSTEM_DISPATCHER_H_ 380