Home | History | Annotate | Download | only in system
      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_RAW_CHANNEL_H_
      6 #define MOJO_SYSTEM_RAW_CHANNEL_H_
      7 
      8 #include <deque>
      9 #include <vector>
     10 
     11 #include "base/macros.h"
     12 #include "base/memory/scoped_ptr.h"
     13 #include "base/memory/weak_ptr.h"
     14 #include "base/synchronization/lock.h"
     15 #include "mojo/embedder/platform_handle_vector.h"
     16 #include "mojo/embedder/scoped_platform_handle.h"
     17 #include "mojo/system/constants.h"
     18 #include "mojo/system/message_in_transit.h"
     19 #include "mojo/system/system_impl_export.h"
     20 
     21 namespace base {
     22 class MessageLoopForIO;
     23 }
     24 
     25 namespace mojo {
     26 namespace system {
     27 
     28 // |RawChannel| is an interface and base class for objects that wrap an OS
     29 // "pipe". It presents the following interface to users:
     30 //  - Receives and dispatches messages on an I/O thread (running a
     31 //    |MessageLoopForIO|.
     32 //  - Provides a thread-safe way of writing messages (|WriteMessage()|);
     33 //    writing/queueing messages will not block and is atomic from the point of
     34 //    view of the caller. If necessary, messages are queued (to be written on
     35 //    the aforementioned thread).
     36 //
     37 // OS-specific implementation subclasses are to be instantiated using the
     38 // |Create()| static factory method.
     39 //
     40 // With the exception of |WriteMessage()|, this class is thread-unsafe (and in
     41 // general its methods should only be used on the I/O thread, i.e., the thread
     42 // on which |Init()| is called).
     43 class MOJO_SYSTEM_IMPL_EXPORT RawChannel {
     44  public:
     45   virtual ~RawChannel();
     46 
     47   // The |Delegate| is only accessed on the same thread as the message loop
     48   // (passed in on creation).
     49   class MOJO_SYSTEM_IMPL_EXPORT Delegate {
     50    public:
     51     enum Error {
     52       // Failed read due to raw channel shutdown (e.g., on the other side).
     53       ERROR_READ_SHUTDOWN,
     54       // Failed read due to raw channel being broken (e.g., if the other side
     55       // died without shutting down).
     56       ERROR_READ_BROKEN,
     57       // Received a bad message.
     58       ERROR_READ_BAD_MESSAGE,
     59       // Unknown read error.
     60       ERROR_READ_UNKNOWN,
     61       // Generic write error.
     62       ERROR_WRITE
     63     };
     64 
     65     // Called when a message is read. This may call |Shutdown()| (on the
     66     // |RawChannel|), but must not destroy it.
     67     virtual void OnReadMessage(
     68         const MessageInTransit::View& message_view,
     69         embedder::ScopedPlatformHandleVectorPtr platform_handles) = 0;
     70 
     71     // Called when there's a (fatal) error. This may call the raw channel's
     72     // |Shutdown()|, but must not destroy it.
     73     //
     74     // For each raw channel, there'll be at most one |ERROR_READ_...| and at
     75     // most one |ERROR_WRITE| notification. After |OnError(ERROR_READ_...)|,
     76     // |OnReadMessage()| won't be called again.
     77     virtual void OnError(Error error) = 0;
     78 
     79    protected:
     80     virtual ~Delegate() {}
     81   };
     82 
     83   // Static factory method. |handle| should be a handle to a
     84   // (platform-appropriate) bidirectional communication channel (e.g., a socket
     85   // on POSIX, a named pipe on Windows).
     86   static scoped_ptr<RawChannel> Create(embedder::ScopedPlatformHandle handle);
     87 
     88   // This must be called (on an I/O thread) before this object is used. Does
     89   // *not* take ownership of |delegate|. Both the I/O thread and |delegate| must
     90   // remain alive until |Shutdown()| is called (unless this fails); |delegate|
     91   // will no longer be used after |Shutdown()|. Returns true on success. On
     92   // failure, |Shutdown()| should *not* be called.
     93   bool Init(Delegate* delegate);
     94 
     95   // This must be called (on the I/O thread) before this object is destroyed.
     96   void Shutdown();
     97 
     98   // Writes the given message (or schedules it to be written). |message| must
     99   // have no |Dispatcher|s still attached (i.e.,
    100   // |SerializeAndCloseDispatchers()| should have been called). This method is
    101   // thread-safe and may be called from any thread. Returns true on success.
    102   bool WriteMessage(scoped_ptr<MessageInTransit> message);
    103 
    104   // Returns true if the write buffer is empty (i.e., all messages written using
    105   // |WriteMessage()| have actually been sent.
    106   // TODO(vtl): We should really also notify our delegate when the write buffer
    107   // becomes empty (or something like that).
    108   bool IsWriteBufferEmpty();
    109 
    110   // Returns the amount of space needed in the |MessageInTransit|'s
    111   // |TransportData|'s "platform handle table" per platform handle (to be
    112   // attached to a message). (This amount may be zero.)
    113   virtual size_t GetSerializedPlatformHandleSize() const = 0;
    114 
    115  protected:
    116   // Result of I/O operations.
    117   enum IOResult {
    118     IO_SUCCEEDED,
    119     // Failed due to a (probably) clean shutdown (e.g., of the other end).
    120     IO_FAILED_SHUTDOWN,
    121     // Failed due to the connection being broken (e.g., the other end dying).
    122     IO_FAILED_BROKEN,
    123     // Failed due to some other (unexpected) reason.
    124     IO_FAILED_UNKNOWN,
    125     IO_PENDING
    126   };
    127 
    128   class MOJO_SYSTEM_IMPL_EXPORT ReadBuffer {
    129    public:
    130     ReadBuffer();
    131     ~ReadBuffer();
    132 
    133     void GetBuffer(char** addr, size_t* size);
    134 
    135    private:
    136     friend class RawChannel;
    137 
    138     // We store data from |[Schedule]Read()|s in |buffer_|. The start of
    139     // |buffer_| is always aligned with a message boundary (we will copy memory
    140     // to ensure this), but |buffer_| may be larger than the actual number of
    141     // bytes we have.
    142     std::vector<char> buffer_;
    143     size_t num_valid_bytes_;
    144 
    145     DISALLOW_COPY_AND_ASSIGN(ReadBuffer);
    146   };
    147 
    148   class MOJO_SYSTEM_IMPL_EXPORT WriteBuffer {
    149    public:
    150     struct Buffer {
    151       const char* addr;
    152       size_t size;
    153     };
    154 
    155     explicit WriteBuffer(size_t serialized_platform_handle_size);
    156     ~WriteBuffer();
    157 
    158     // Returns true if there are (more) platform handles to be sent (from the
    159     // front of |message_queue_|).
    160     bool HavePlatformHandlesToSend() const;
    161     // Gets platform handles to be sent (from the front of |message_queue_|).
    162     // This should only be called if |HavePlatformHandlesToSend()| returned
    163     // true. There are two components to this: the actual |PlatformHandle|s
    164     // (which should be closed once sent) and any additional serialization
    165     // information (which will be embedded in the message's data; there are
    166     // |GetSerializedPlatformHandleSize()| bytes per handle). Once all platform
    167     // handles have been sent, the message data should be written next (see
    168     // |GetBuffers()|).
    169     void GetPlatformHandlesToSend(size_t* num_platform_handles,
    170                                   embedder::PlatformHandle** platform_handles,
    171                                   void** serialization_data);
    172 
    173     // Gets buffers to be written. These buffers will always come from the front
    174     // of |message_queue_|. Once they are completely written, the front
    175     // |MessageInTransit| should be popped (and destroyed); this is done in
    176     // |OnWriteCompletedNoLock()|.
    177     void GetBuffers(std::vector<Buffer>* buffers) const;
    178 
    179    private:
    180     friend class RawChannel;
    181 
    182     const size_t serialized_platform_handle_size_;
    183 
    184     // TODO(vtl): When C++11 is available, switch this to a deque of
    185     // |scoped_ptr|/|unique_ptr|s.
    186     std::deque<MessageInTransit*> message_queue_;
    187     // Platform handles are sent before the message data, but doing so may
    188     // require several passes. |platform_handles_offset_| indicates the position
    189     // in the first message's vector of platform handles to send next.
    190     size_t platform_handles_offset_;
    191     // The first message's data may have been partially sent. |data_offset_|
    192     // indicates the position in the first message's data to start the next
    193     // write.
    194     size_t data_offset_;
    195 
    196     DISALLOW_COPY_AND_ASSIGN(WriteBuffer);
    197   };
    198 
    199   RawChannel();
    200 
    201   // |result| must not be |IO_PENDING|. Must be called on the I/O thread WITHOUT
    202   // |write_lock_| held.
    203   void OnReadCompleted(IOResult io_result, size_t bytes_read);
    204   // |result| must not be |IO_PENDING|. Must be called on the I/O thread WITHOUT
    205   // |write_lock_| held.
    206   void OnWriteCompleted(IOResult io_result,
    207                         size_t platform_handles_written,
    208                         size_t bytes_written);
    209 
    210   base::MessageLoopForIO* message_loop_for_io() { return message_loop_for_io_; }
    211   base::Lock& write_lock() { return write_lock_; }
    212 
    213   // Should only be called on the I/O thread.
    214   ReadBuffer* read_buffer() { return read_buffer_.get(); }
    215 
    216   // Only called under |write_lock_|.
    217   WriteBuffer* write_buffer_no_lock() {
    218     write_lock_.AssertAcquired();
    219     return write_buffer_.get();
    220   }
    221 
    222   // Adds |message| to the write message queue. Implementation subclasses may
    223   // override this to add any additional "control" messages needed. This is
    224   // called (on any thread) with |write_lock_| held.
    225   virtual void EnqueueMessageNoLock(scoped_ptr<MessageInTransit> message);
    226 
    227   // Handles any control messages targeted to the |RawChannel| (or
    228   // implementation subclass). Implementation subclasses may override this to
    229   // handle any implementation-specific control messages, but should call
    230   // |RawChannel::OnReadMessageForRawChannel()| for any remaining messages.
    231   // Returns true on success and false on error (e.g., invalid control message).
    232   // This is only called on the I/O thread.
    233   virtual bool OnReadMessageForRawChannel(
    234       const MessageInTransit::View& message_view);
    235 
    236   // Reads into |read_buffer()|.
    237   // This class guarantees that:
    238   // - the area indicated by |GetBuffer()| will stay valid until read completion
    239   //   (but please also see the comments for |OnShutdownNoLock()|);
    240   // - a second read is not started if there is a pending read;
    241   // - the method is called on the I/O thread WITHOUT |write_lock_| held.
    242   //
    243   // The implementing subclass must guarantee that:
    244   // - |bytes_read| is untouched unless |Read()| returns |IO_SUCCEEDED|;
    245   // - if the method returns |IO_PENDING|, |OnReadCompleted()| will be called on
    246   //   the I/O thread to report the result, unless |Shutdown()| is called.
    247   virtual IOResult Read(size_t* bytes_read) = 0;
    248   // Similar to |Read()|, except that the implementing subclass must also
    249   // guarantee that the method doesn't succeed synchronously, i.e., it only
    250   // returns |IO_FAILED_...| or |IO_PENDING|.
    251   virtual IOResult ScheduleRead() = 0;
    252 
    253   // Called by |OnReadCompleted()| to get the platform handles associated with
    254   // the given platform handle table (from a message). This should only be
    255   // called when |num_platform_handles| is nonzero. Returns null if the
    256   // |num_platform_handles| handles are not available. Only called on the I/O
    257   // thread (without |write_lock_| held).
    258   virtual embedder::ScopedPlatformHandleVectorPtr GetReadPlatformHandles(
    259       size_t num_platform_handles,
    260       const void* platform_handle_table) = 0;
    261 
    262   // Writes contents in |write_buffer_no_lock()|.
    263   // This class guarantees that:
    264   // - the |PlatformHandle|s given by |GetPlatformHandlesToSend()| and the
    265   //   buffer(s) given by |GetBuffers()| will remain valid until write
    266   //   completion (see also the comments for |OnShutdownNoLock()|);
    267   // - a second write is not started if there is a pending write;
    268   // - the method is called under |write_lock_|.
    269   //
    270   // The implementing subclass must guarantee that:
    271   // - |platform_handles_written| and |bytes_written| are untouched unless
    272   //   |WriteNoLock()| returns |IO_SUCCEEDED|;
    273   // - if the method returns |IO_PENDING|, |OnWriteCompleted()| will be called
    274   //   on the I/O thread to report the result, unless |Shutdown()| is called.
    275   virtual IOResult WriteNoLock(size_t* platform_handles_written,
    276                                size_t* bytes_written) = 0;
    277   // Similar to |WriteNoLock()|, except that the implementing subclass must also
    278   // guarantee that the method doesn't succeed synchronously, i.e., it only
    279   // returns |IO_FAILED_...| or |IO_PENDING|.
    280   virtual IOResult ScheduleWriteNoLock() = 0;
    281 
    282   // Must be called on the I/O thread WITHOUT |write_lock_| held.
    283   virtual bool OnInit() = 0;
    284   // On shutdown, passes the ownership of the buffers to subclasses, which may
    285   // want to preserve them if there are pending read/write. Must be called on
    286   // the I/O thread under |write_lock_|.
    287   virtual void OnShutdownNoLock(scoped_ptr<ReadBuffer> read_buffer,
    288                                 scoped_ptr<WriteBuffer> write_buffer) = 0;
    289 
    290  private:
    291   // Converts an |IO_FAILED_...| for a read to a |Delegate::Error|.
    292   static Delegate::Error ReadIOResultToError(IOResult io_result);
    293 
    294   // Calls |delegate_->OnError(error)|. Must be called on the I/O thread WITHOUT
    295   // |write_lock_| held.
    296   void CallOnError(Delegate::Error error);
    297 
    298   // If |io_result| is |IO_SUCCESS|, updates the write buffer and schedules a
    299   // write operation to run later if there is more to write. If |io_result| is
    300   // failure or any other error occurs, cancels pending writes and returns
    301   // false. Must be called under |write_lock_| and only if |write_stopped_| is
    302   // false.
    303   bool OnWriteCompletedNoLock(IOResult io_result,
    304                               size_t platform_handles_written,
    305                               size_t bytes_written);
    306 
    307   // Set in |Init()| and never changed (hence usable on any thread without
    308   // locking):
    309   base::MessageLoopForIO* message_loop_for_io_;
    310 
    311   // Only used on the I/O thread:
    312   Delegate* delegate_;
    313   bool read_stopped_;
    314   scoped_ptr<ReadBuffer> read_buffer_;
    315 
    316   base::Lock write_lock_;  // Protects the following members.
    317   bool write_stopped_;
    318   scoped_ptr<WriteBuffer> write_buffer_;
    319 
    320   // This is used for posting tasks from write threads to the I/O thread. It
    321   // must only be accessed under |write_lock_|. The weak pointers it produces
    322   // are only used/invalidated on the I/O thread.
    323   base::WeakPtrFactory<RawChannel> weak_ptr_factory_;
    324 
    325   DISALLOW_COPY_AND_ASSIGN(RawChannel);
    326 };
    327 
    328 }  // namespace system
    329 }  // namespace mojo
    330 
    331 #endif  // MOJO_SYSTEM_RAW_CHANNEL_H_
    332