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