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