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.
5 #ifndef MOJO_SYSTEM_DISPATCHER_H_
6 #define MOJO_SYSTEM_DISPATCHER_H_
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"
31 class DispatcherTransport
;
33 class LocalMessagePipeEndpoint
;
34 class ProxyMessagePipeEndpoint
;
35 class RawSharedBufferMapping
;
39 typedef std::vector
<scoped_refptr
<Dispatcher
> > DispatcherVector
;
43 // Test helper. We need to declare it here so we can friend it.
44 MOJO_SYSTEM_IMPL_EXPORT DispatcherTransport
DispatcherTryStartTransport(
45 Dispatcher
* dispatcher
);
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
54 class MOJO_SYSTEM_IMPL_EXPORT Dispatcher
:
55 public base::RefCountedThreadSafe
<Dispatcher
> {
60 kTypeDataPipeProducer
,
61 kTypeDataPipeConsumer
,
64 // "Private" types (not exposed via the public interface):
65 kTypePlatformHandle
= -1
67 virtual Type
GetType() const = 0;
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.
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
,
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
,
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
,
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
,
116 MojoMapBufferFlags flags
,
117 scoped_ptr
<RawSharedBufferMapping
>* mapping
);
119 // Adds a waiter to this dispatcher. The waiter will be woken up when this
120 // object changes state to satisfy |flags| with result |wake_result| (which
121 // must be >= 0, i.e., a success status). It will also be woken up when it
122 // becomes impossible for the object to ever satisfy |flags| with a suitable
126 // - |MOJO_RESULT_OK| if the waiter was added;
127 // - |MOJO_RESULT_ALREADY_EXISTS| if |flags| is already satisfied;
128 // - |MOJO_RESULT_INVALID_ARGUMENT| if the dispatcher has been closed; and
129 // - |MOJO_RESULT_FAILED_PRECONDITION| if it is not (or no longer) possible
130 // that |flags| will ever be satisfied.
131 MojoResult
AddWaiter(Waiter
* waiter
,
133 MojoResult wake_result
);
134 void RemoveWaiter(Waiter
* waiter
);
136 // A dispatcher must be put into a special state in order to be sent across a
137 // message pipe. Outside of tests, only |HandleTableAccess| is allowed to do
138 // this, since there are requirements on the handle table (see below).
140 // In this special state, only a restricted set of operations is allowed.
141 // These are the ones available as |DispatcherTransport| methods. Other
142 // |Dispatcher| methods must not be called until |DispatcherTransport::End()|
144 class HandleTableAccess
{
147 friend class HandleTable
;
148 // Tests also need this, to avoid needing |Core|.
149 friend DispatcherTransport
test::DispatcherTryStartTransport(Dispatcher
*);
151 // This must be called under the handle table lock and only if the handle
152 // table entry is not marked busy. The caller must maintain a reference to
153 // |dispatcher| until |DispatcherTransport::End()| is called.
154 static DispatcherTransport
TryStartTransport(Dispatcher
* dispatcher
);
157 // A |TransportData| may serialize dispatchers that are given to it (and which
158 // were previously attached to the |MessageInTransit| that is creating it) to
159 // a given |Channel| and then (probably in a different process) deserialize.
160 // Note that the |MessageInTransit| "owns" (i.e., has the only ref to) these
161 // dispatchers, so there are no locking issues. (There's no lock ordering
162 // issue, and in fact no need to take dispatcher locks at all.)
163 // TODO(vtl): Consider making another wrapper similar to |DispatcherTransport|
164 // (but with an owning, unique reference), and having
165 // |CreateEquivalentDispatcherAndCloseImplNoLock()| return that wrapper (and
166 // |MessageInTransit|, etc. only holding on to such wrappers).
167 class TransportDataAccess
{
169 friend class TransportData
;
171 // Serialization API. These functions may only be called on such
172 // dispatchers. (|channel| is the |Channel| to which the dispatcher is to be
173 // serialized.) See the |Dispatcher| methods of the same names for more
175 static void StartSerialize(Dispatcher
* dispatcher
,
178 size_t* max_platform_handles
);
179 static bool EndSerializeAndClose(
180 Dispatcher
* dispatcher
,
184 embedder::PlatformHandleVector
* platform_handles
);
186 // Deserialization API.
187 // Note: This "clears" (i.e., reset to the invalid handle) any platform
188 // handles that it takes ownership of.
189 static scoped_refptr
<Dispatcher
> Deserialize(
194 embedder::PlatformHandleVector
* platform_handles
);
198 friend class base::RefCountedThreadSafe
<Dispatcher
>;
201 virtual ~Dispatcher();
203 // These are to be overridden by subclasses (if necessary). They are called
204 // exactly once -- first |CancelAllWaitersNoLock()|, then |CloseImplNoLock()|,
205 // when the dispatcher is being closed. They are called under |lock_|.
206 virtual void CancelAllWaitersNoLock();
207 virtual void CloseImplNoLock();
208 virtual scoped_refptr
<Dispatcher
>
209 CreateEquivalentDispatcherAndCloseImplNoLock() = 0;
211 // These are to be overridden by subclasses (if necessary). They are never
212 // called after the dispatcher has been closed. They are called under |lock_|.
213 // See the descriptions of the methods without the "ImplNoLock" for more
215 virtual MojoResult
WriteMessageImplNoLock(
218 std::vector
<DispatcherTransport
>* transports
,
219 MojoWriteMessageFlags flags
);
220 virtual MojoResult
ReadMessageImplNoLock(void* bytes
,
222 DispatcherVector
* dispatchers
,
223 uint32_t* num_dispatchers
,
224 MojoReadMessageFlags flags
);
225 virtual MojoResult
WriteDataImplNoLock(const void* elements
,
227 MojoWriteDataFlags flags
);
228 virtual MojoResult
BeginWriteDataImplNoLock(void** buffer
,
229 uint32_t* buffer_num_bytes
,
230 MojoWriteDataFlags flags
);
231 virtual MojoResult
EndWriteDataImplNoLock(uint32_t num_bytes_written
);
232 virtual MojoResult
ReadDataImplNoLock(void* elements
,
234 MojoReadDataFlags flags
);
235 virtual MojoResult
BeginReadDataImplNoLock(const void** buffer
,
236 uint32_t* buffer_num_bytes
,
237 MojoReadDataFlags flags
);
238 virtual MojoResult
EndReadDataImplNoLock(uint32_t num_bytes_read
);
239 virtual MojoResult
DuplicateBufferHandleImplNoLock(
240 const MojoDuplicateBufferHandleOptions
* options
,
241 scoped_refptr
<Dispatcher
>* new_dispatcher
);
242 virtual MojoResult
MapBufferImplNoLock(
245 MojoMapBufferFlags flags
,
246 scoped_ptr
<RawSharedBufferMapping
>* mapping
);
247 virtual MojoResult
AddWaiterImplNoLock(Waiter
* waiter
,
249 MojoResult wake_result
);
250 virtual void RemoveWaiterImplNoLock(Waiter
* waiter
);
252 // These implement the API used to serialize dispatchers to a |Channel|
253 // (described below). They will only be called on a dispatcher that's attached
254 // to and "owned" by a |MessageInTransit|. See the non-"impl" versions for
257 // Note: |StartSerializeImplNoLock()| is actually called with |lock_| NOT
258 // held, since the dispatcher should only be accessible to the calling thread.
259 // On Debug builds, |EndSerializeAndCloseImplNoLock()| is called with |lock_|
260 // held, to satisfy any |lock_.AssertAcquired()| (e.g., in |CloseImplNoLock()|
261 // -- and anything it calls); disentangling those assertions is
262 // difficult/fragile, and would weaken our general checking of invariants.
264 // TODO(vtl): Consider making these pure virtual once most things support
265 // being passed over a message pipe.
266 virtual void StartSerializeImplNoLock(Channel
* channel
,
268 size_t* max_platform_handles
);
269 virtual bool EndSerializeAndCloseImplNoLock(
273 embedder::PlatformHandleVector
* platform_handles
);
275 // Available to subclasses. (Note: Returns a non-const reference, just like
276 // |base::AutoLock|'s constructor takes a non-const reference.)
277 base::Lock
& lock() const { return lock_
; }
280 friend class DispatcherTransport
;
282 // This should be overridden to return true if/when there's an ongoing
283 // operation (e.g., two-phase read/writes on data pipes) that should prevent a
284 // handle from being sent over a message pipe (with status "busy").
285 virtual bool IsBusyNoLock() const;
287 // Closes the dispatcher. This must be done under lock, and unlike |Close()|,
288 // the dispatcher must not be closed already. (This is the "equivalent" of
289 // |CreateEquivalentDispatcherAndCloseNoLock()|, for situations where the
290 // dispatcher must be disposed of instead of "transferred".)
293 // Creates an equivalent dispatcher -- representing the same resource as this
294 // dispatcher -- and close (i.e., disable) this dispatcher. I.e., this
295 // dispatcher will look as though it was closed, but the resource it
296 // represents will be assigned to the new dispatcher. This must be called
297 // under the dispatcher's lock.
298 scoped_refptr
<Dispatcher
> CreateEquivalentDispatcherAndCloseNoLock();
300 // API to serialize dispatchers to a |Channel|, exposed to only
301 // |TransportData| (via |TransportData|). They may only be called on a
302 // dispatcher attached to a |MessageInTransit| (and in particular not in
303 // |CoreImpl|'s handle table).
305 // Starts the serialization. Returns (via the two "out" parameters) the
306 // maximum amount of space that may be needed to serialize this dispatcher to
307 // the given |Channel| (no more than
308 // |TransportData::kMaxSerializedDispatcherSize|) and the maximum number of
309 // |PlatformHandle|s that may need to be attached (no more than
310 // |TransportData::kMaxSerializedDispatcherPlatformHandles|). If this
311 // dispatcher cannot be serialized to the given |Channel|, |*max_size| and
312 // |*max_platform_handles| should be set to zero. A call to this method will
313 // ALWAYS be followed by a call to |EndSerializeAndClose()| (even if this
314 // dispatcher cannot be serialized to the given |Channel|).
315 void StartSerialize(Channel
* channel
,
317 size_t* max_platform_handles
);
318 // Completes the serialization of this dispatcher to the given |Channel| and
319 // closes it. (This call will always follow an earlier call to
320 // |StartSerialize()|, with the same |Channel|.) This does so by writing to
321 // |destination| and appending any |PlatformHandle|s needed to
322 // |platform_handles| (which may be null if no platform handles were indicated
323 // to be required to |StartSerialize()|). This may write no more than the
324 // amount indicated by |StartSerialize()|. (WARNING: Beware of races, e.g., if
325 // something can be mutated between the two calls!) Returns true on success,
326 // in which case |*actual_size| is set to the amount it actually wrote to
327 // |destination|. On failure, |*actual_size| should not be modified; however,
328 // the dispatcher will still be closed.
329 bool EndSerializeAndClose(Channel
* channel
,
332 embedder::PlatformHandleVector
* platform_handles
);
334 // This protects the following members as well as any state added by
336 mutable base::Lock lock_
;
339 DISALLOW_COPY_AND_ASSIGN(Dispatcher
);
342 // Wrapper around a |Dispatcher| pointer, while it's being processed to be
343 // passed in a message pipe. See the comment about
344 // |Dispatcher::HandleTableAccess| for more details.
346 // Note: This class is deliberately "thin" -- no more expensive than a
348 class MOJO_SYSTEM_IMPL_EXPORT DispatcherTransport
{
350 DispatcherTransport() : dispatcher_(NULL
) {}
354 Dispatcher::Type
GetType() const { return dispatcher_
->GetType(); }
355 bool IsBusy() const { return dispatcher_
->IsBusyNoLock(); }
356 void Close() { dispatcher_
->CloseNoLock(); }
357 scoped_refptr
<Dispatcher
> CreateEquivalentDispatcherAndClose() {
358 return dispatcher_
->CreateEquivalentDispatcherAndCloseNoLock();
361 bool is_valid() const { return !!dispatcher_
; }
364 Dispatcher
* dispatcher() { return dispatcher_
; }
367 friend class Dispatcher::HandleTableAccess
;
369 explicit DispatcherTransport(Dispatcher
* dispatcher
)
370 : dispatcher_(dispatcher
) {}
372 Dispatcher
* dispatcher_
;
374 // Copy and assign allowed.
377 } // namespace system
380 #endif // MOJO_SYSTEM_DISPATCHER_H_