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/core.h"
20 #include "mojo/public/c/system/message_pipe.h"
21 #include "mojo/public/c/system/types.h"
22 #include "mojo/system/system_impl_export.h"
30 class DispatcherTransport
;
32 class LocalMessagePipeEndpoint
;
33 class ProxyMessagePipeEndpoint
;
34 class RawSharedBufferMapping
;
38 typedef std::vector
<scoped_refptr
<Dispatcher
> > DispatcherVector
;
42 // Test helper. We need to declare it here so we can friend it.
43 MOJO_SYSTEM_IMPL_EXPORT DispatcherTransport
DispatcherTryStartTransport(
44 Dispatcher
* dispatcher
);
48 // A |Dispatcher| implements Mojo primitives that are "attached" to a particular
49 // handle. This includes most (all?) primitives except for |MojoWait...()|. This
50 // object is thread-safe, with its state being protected by a single lock
51 // |lock_|, which is also made available to implementation subclasses (via the
53 class MOJO_SYSTEM_IMPL_EXPORT Dispatcher
:
54 public base::RefCountedThreadSafe
<Dispatcher
> {
59 kTypeDataPipeProducer
,
60 kTypeDataPipeConsumer
,
63 // "Private" types (not exposed via the public interface):
64 kTypePlatformHandle
= -1
66 virtual Type
GetType() const = 0;
68 // These methods implement the various primitives named |Mojo...()|. These
69 // take |lock_| and handle races with |Close()|. Then they call out to
70 // subclasses' |...ImplNoLock()| methods (still under |lock_|), which actually
71 // implement the primitives.
72 // NOTE(vtl): This puts a big lock around each dispatcher (i.e., handle), and
73 // prevents the various |...ImplNoLock()|s from releasing the lock as soon as
74 // possible. If this becomes an issue, we can rethink this.
77 // |transports| may be non-null if and only if there are handles to be
78 // written; not that |this| must not be in |transports|. On success, all the
79 // dispatchers in |transports| must have been moved to a closed state; on
80 // failure, they should remain in their original state.
81 MojoResult
WriteMessage(const void* bytes
,
83 std::vector
<DispatcherTransport
>* transports
,
84 MojoWriteMessageFlags flags
);
85 // |dispatchers| must be non-null but empty, if |num_dispatchers| is non-null
86 // and nonzero. On success, it will be set to the dispatchers to be received
87 // (and assigned handles) as part of the message.
88 MojoResult
ReadMessage(void* bytes
,
90 DispatcherVector
* dispatchers
,
91 uint32_t* num_dispatchers
,
92 MojoReadMessageFlags flags
);
93 MojoResult
WriteData(const void* elements
,
94 uint32_t* elements_num_bytes
,
95 MojoWriteDataFlags flags
);
96 MojoResult
BeginWriteData(void** buffer
,
97 uint32_t* buffer_num_bytes
,
98 MojoWriteDataFlags flags
);
99 MojoResult
EndWriteData(uint32_t num_bytes_written
);
100 MojoResult
ReadData(void* elements
,
102 MojoReadDataFlags flags
);
103 MojoResult
BeginReadData(const void** buffer
,
104 uint32_t* buffer_num_bytes
,
105 MojoReadDataFlags flags
);
106 MojoResult
EndReadData(uint32_t num_bytes_read
);
107 // |options| may be null. |new_dispatcher| must not be null, but
108 // |*new_dispatcher| should be null (and will contain the dispatcher for the
109 // new handle on success).
110 MojoResult
DuplicateBufferHandle(
111 const MojoDuplicateBufferHandleOptions
* options
,
112 scoped_refptr
<Dispatcher
>* new_dispatcher
);
113 MojoResult
MapBuffer(uint64_t offset
,
115 MojoMapBufferFlags flags
,
116 scoped_ptr
<RawSharedBufferMapping
>* mapping
);
118 // Adds a waiter to this dispatcher. The waiter will be woken up when this
119 // object changes state to satisfy |flags| with result |wake_result| (which
120 // must be >= 0, i.e., a success status). It will also be woken up when it
121 // becomes impossible for the object to ever satisfy |flags| with a suitable
125 // - |MOJO_RESULT_OK| if the waiter was added;
126 // - |MOJO_RESULT_ALREADY_EXISTS| if |flags| 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 |flags| will ever be satisfied.
130 MojoResult
AddWaiter(Waiter
* waiter
,
132 MojoResult wake_result
);
133 void RemoveWaiter(Waiter
* waiter
);
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).
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()|
143 class HandleTableAccess
{
146 friend class HandleTable
;
147 // Tests also need this, to avoid needing |Core|.
148 friend DispatcherTransport
test::DispatcherTryStartTransport(Dispatcher
*);
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
);
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
{
168 friend class TransportData
;
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
174 static void StartSerialize(Dispatcher
* dispatcher
,
177 size_t* max_platform_handles
);
178 static bool EndSerializeAndClose(
179 Dispatcher
* dispatcher
,
183 embedder::PlatformHandleVector
* platform_handles
);
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(
193 embedder::PlatformHandleVector
* platform_handles
);
197 friend class base::RefCountedThreadSafe
<Dispatcher
>;
200 virtual ~Dispatcher();
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;
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
214 virtual MojoResult
WriteMessageImplNoLock(
217 std::vector
<DispatcherTransport
>* transports
,
218 MojoWriteMessageFlags flags
);
219 virtual MojoResult
ReadMessageImplNoLock(void* bytes
,
221 DispatcherVector
* dispatchers
,
222 uint32_t* num_dispatchers
,
223 MojoReadMessageFlags flags
);
224 virtual MojoResult
WriteDataImplNoLock(const void* elements
,
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
,
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(
244 MojoMapBufferFlags flags
,
245 scoped_ptr
<RawSharedBufferMapping
>* mapping
);
246 virtual MojoResult
AddWaiterImplNoLock(Waiter
* waiter
,
248 MojoResult wake_result
);
249 virtual void RemoveWaiterImplNoLock(Waiter
* waiter
);
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
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.
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
,
267 size_t* max_platform_handles
);
268 virtual bool EndSerializeAndCloseImplNoLock(
272 embedder::PlatformHandleVector
* platform_handles
);
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_
; }
279 friend class DispatcherTransport
;
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;
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".)
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();
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).
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
,
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
,
331 embedder::PlatformHandleVector
* platform_handles
);
333 // This protects the following members as well as any state added by
335 mutable base::Lock lock_
;
338 DISALLOW_COPY_AND_ASSIGN(Dispatcher
);
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.
345 // Note: This class is deliberately "thin" -- no more expensive than a
347 class MOJO_SYSTEM_IMPL_EXPORT DispatcherTransport
{
349 DispatcherTransport() : dispatcher_(NULL
) {}
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();
360 bool is_valid() const { return !!dispatcher_
; }
363 Dispatcher
* dispatcher() { return dispatcher_
; }
366 friend class Dispatcher::HandleTableAccess
;
368 explicit DispatcherTransport(Dispatcher
* dispatcher
)
369 : dispatcher_(dispatcher
) {}
371 Dispatcher
* dispatcher_
;
373 // Copy and assign allowed.
376 } // namespace system
379 #endif // MOJO_SYSTEM_DISPATCHER_H_