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