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 <stddef.h> | |
9 | |
10 #include <vector> | |
11 | |
12 #include "base/memory/scoped_ptr.h" | |
13 #include "base/memory/weak_ptr.h" | |
14 #include "base/message_loop/message_loop.h" | |
15 #include "base/synchronization/lock.h" | |
16 #include "mojo/edk/embedder/platform_handle_vector.h" | |
17 #include "mojo/edk/embedder/scoped_platform_handle.h" | |
18 #include "mojo/edk/system/message_in_transit.h" | |
19 #include "mojo/edk/system/message_in_transit_queue.h" | |
20 #include "mojo/edk/system/system_impl_export.h" | |
21 #include "mojo/public/cpp/system/macros.h" | |
22 | |
23 namespace mojo { | |
24 namespace edk { | |
25 | |
26 // |RawChannel| is an interface and base class for objects that wrap an OS | |
27 // "pipe". It presents the following interface to users: | |
28 // - Receives and dispatches messages on an I/O thread (running a | |
29 // |MessageLoopForIO|. | |
30 // - Provides a thread-safe way of writing messages (|WriteMessage()|); | |
31 // writing/queueing messages will not block and is atomic from the point of | |
32 // view of the caller. If necessary, messages are queued (to be written on | |
33 // the aforementioned thread). | |
34 // | |
35 // OS-specific implementation subclasses are to be instantiated using the | |
36 // |Create()| static factory method. | |
37 // | |
38 // With the exception of |WriteMessage()|, this class is thread-unsafe (and in | |
39 // general its methods should only be used on the I/O thread, i.e., the thread | |
40 // on which |Init()| is called). | |
41 class MOJO_SYSTEM_IMPL_EXPORT RawChannel : | |
42 public base::MessageLoop::DestructionObserver { | |
43 public: | |
44 | |
45 // The |Delegate| is only accessed on the same thread as the message loop | |
46 // (passed in on creation). | |
47 class MOJO_SYSTEM_IMPL_EXPORT Delegate { | |
48 public: | |
49 enum Error { | |
50 // Failed read due to raw channel shutdown (e.g., on the other side). | |
51 ERROR_READ_SHUTDOWN, | |
52 // Failed read due to raw channel being broken (e.g., if the other side | |
53 // died without shutting down). | |
54 ERROR_READ_BROKEN, | |
55 // Received a bad message. | |
56 ERROR_READ_BAD_MESSAGE, | |
57 // Unknown read error. | |
58 ERROR_READ_UNKNOWN, | |
59 // Generic write error. | |
60 ERROR_WRITE | |
61 }; | |
62 | |
63 // Called when a message is read. The delegate may not call back into this | |
64 // object synchronously. | |
65 virtual void OnReadMessage( | |
66 const MessageInTransit::View& message_view, | |
67 ScopedPlatformHandleVectorPtr platform_handles) = 0; | |
68 | |
69 // Called when there's a (fatal) error. The delegate may not call back into | |
70 // this object synchronously. | |
71 // | |
72 // For each raw channel, there'll be at most one |ERROR_READ_...| and at | |
73 // most one |ERROR_WRITE| notification. After |OnError(ERROR_READ_...)|, | |
74 // |OnReadMessage()| won't be called again. | |
75 virtual void OnError(Error error) = 0; | |
76 | |
77 protected: | |
78 virtual ~Delegate() {} | |
79 }; | |
80 | |
81 // Static factory method. |handle| should be a handle to a | |
82 // (platform-appropriate) bidirectional communication channel (e.g., a socket | |
83 // on POSIX, a named pipe on Windows). The returned object must be destructed | |
84 // by calling Shutdown on the IO thread. | |
85 static RawChannel* Create(ScopedPlatformHandle handle); | |
86 | |
87 // Returns the amount of space needed in the |MessageInTransit|'s | |
88 // |TransportData|'s "platform handle table" per platform handle (to be | |
89 // attached to a message). (This amount may be zero.) | |
90 static size_t GetSerializedPlatformHandleSize(); | |
91 | |
92 // This must be called (on an I/O thread) before this object is used. Does | |
93 // *not* take ownership of |delegate|. Both the I/O thread and |delegate| must | |
94 // remain alive until |Shutdown()| is called (unless this fails); |delegate| | |
95 // will no longer be used after |Shutdown()|. | |
96 // NOTE: for performance reasons, this doesn't connect to the raw pipe until | |
97 // either WriteMessage or EnsureLazyInitialized are called. If the delegate | |
98 // cares about reading data from the pipe or getting OnError notifications, | |
99 // they must call EnsureLazyInitialized at such point. | |
100 void Init(Delegate* delegate); | |
101 | |
102 // This can be called on any thread. It's safe to call multiple times. | |
103 void EnsureLazyInitialized(); | |
104 | |
105 // This must be called (on the I/O thread) to destroy the object. After | |
106 // calling this method, no more methods on the class can be called and it will | |
107 // start self destruction. | |
108 // It's safe to call this method from delegate callbacks. | |
109 void Shutdown(); | |
110 | |
111 // Returns the platform handle for the pipe synchronously. | |
112 // |serialized_read_buffer| contains partially read data, if any. | |
113 // |serialized_write_buffer| contains a serialized representation of messages | |
114 // that haven't been written yet. | |
115 // |serialized_read_fds| is only used on POSIX, and it returns FDs associated | |
116 // with partially read data. | |
117 // |serialized_write_fds| is only used on POSIX, and it returns FDs associated | |
118 // with messages that haven't been written yet. | |
119 // All these arrays need to be passed to SetSerializedData below when | |
120 // recreating the channel. | |
121 // If there was a read or write in progress, they will be completed. If the | |
122 // in-progress read results in an error, an invalid handle is returned. If the | |
123 // in-progress write results in an error, |write_error| is true. | |
124 // NOTE: After calling this, consider the channel shutdown and don't call into | |
125 // it anymore. | |
126 ScopedPlatformHandle ReleaseHandle( | |
127 std::vector<char>* serialized_read_buffer, | |
128 std::vector<char>* serialized_write_buffer, | |
129 std::vector<int>* serialized_read_fds, | |
130 std::vector<int>* serialized_write_fds, | |
131 bool* write_error); | |
132 | |
133 // Writes the given message (or schedules it to be written). |message| must | |
134 // have no |Dispatcher|s still attached (i.e., | |
135 // |SerializeAndCloseDispatchers()| should have been called). This method is | |
136 // thread-safe and may be called from any thread. Returns true on success. | |
137 bool WriteMessage(scoped_ptr<MessageInTransit> message); | |
138 | |
139 // When a RawChannel is serialized (i.e. through ReleaseHandle), the delegate | |
140 // saves the data that is returned and passes it here. | |
141 // TODO(jam): perhaps this should be encapsulated inside RawChannel, and | |
142 // ReleaseHandle returns another handle that is shared memory? | |
143 void SetSerializedData( | |
144 char* serialized_read_buffer, size_t serialized_read_buffer_size, | |
145 char* serialized_write_buffer, size_t serialized_write_buffer_size, | |
146 std::vector<int>* serialized_read_fds, | |
147 std::vector<int>* serialized_write_fds); | |
148 | |
149 // Checks if this RawChannel is the other endpoint to |other|. | |
150 bool IsOtherEndOf(RawChannel* other); | |
151 | |
152 protected: | |
153 // Result of I/O operations. | |
154 enum IOResult { | |
155 IO_SUCCEEDED, | |
156 // Failed due to a (probably) clean shutdown (e.g., of the other end). | |
157 IO_FAILED_SHUTDOWN, | |
158 // Failed due to the connection being broken (e.g., the other end dying). | |
159 IO_FAILED_BROKEN, | |
160 // Failed due to some other (unexpected) reason. | |
161 IO_FAILED_UNKNOWN, | |
162 IO_PENDING | |
163 }; | |
164 | |
165 class MOJO_SYSTEM_IMPL_EXPORT ReadBuffer { | |
166 public: | |
167 ReadBuffer(); | |
168 ~ReadBuffer(); | |
169 | |
170 void GetBuffer(char** addr, size_t* size); | |
171 | |
172 bool IsEmpty() const { return num_valid_bytes_ == 0; } | |
173 | |
174 private: | |
175 friend class RawChannel; | |
176 | |
177 // We store data from |[Schedule]Read()|s in |buffer_|. The start of | |
178 // |buffer_| is always aligned with a message boundary (we will copy memory | |
179 // to ensure this), but |buffer_| may be larger than the actual number of | |
180 // bytes we have. | |
181 std::vector<char> buffer_; | |
182 size_t num_valid_bytes_; | |
183 | |
184 MOJO_DISALLOW_COPY_AND_ASSIGN(ReadBuffer); | |
185 }; | |
186 | |
187 class MOJO_SYSTEM_IMPL_EXPORT WriteBuffer { | |
188 public: | |
189 struct Buffer { | |
190 const char* addr; | |
191 size_t size; | |
192 }; | |
193 | |
194 WriteBuffer(); | |
195 ~WriteBuffer(); | |
196 | |
197 // Returns true if there are (more) platform handles to be sent (from the | |
198 // front of |message_queue_|). | |
199 bool HavePlatformHandlesToSend() const; | |
200 // Gets platform handles to be sent (from the front of |message_queue_|). | |
201 // This should only be called if |HavePlatformHandlesToSend()| returned | |
202 // true. There are two components to this: the actual |PlatformHandle|s | |
203 // (which should be closed once sent) and any additional serialization | |
204 // information (which will be embedded in the message's data; there are | |
205 // |GetSerializedPlatformHandleSize()| bytes per handle). Once all platform | |
206 // handles have been sent, the message data should be written next (see | |
207 // |GetBuffers()|). | |
208 // TODO(vtl): Maybe this method should be const, but | |
209 // |PlatformHandle::CloseIfNecessary()| isn't const (and actually modifies | |
210 // state). | |
211 void GetPlatformHandlesToSend(size_t* num_platform_handles, | |
212 PlatformHandle** platform_handles, | |
213 void** serialization_data); | |
214 | |
215 // Gets buffers to be written. These buffers will always come from the front | |
216 // of |message_queue_|. Once they are completely written, the front | |
217 // |MessageInTransit| should be popped (and destroyed); this is done in | |
218 // |OnWriteCompletedInternalNoLock()|. | |
219 void GetBuffers(std::vector<Buffer>* buffers); | |
220 | |
221 bool IsEmpty() const { return message_queue_.IsEmpty(); } | |
222 | |
223 private: | |
224 friend class RawChannel; | |
225 | |
226 size_t serialized_platform_handle_size_; | |
227 | |
228 MessageInTransitQueue message_queue_; | |
229 // Platform handles are sent before the message data, but doing so may | |
230 // require several passes. |platform_handles_offset_| indicates the position | |
231 // in the first message's vector of platform handles to send next. | |
232 size_t platform_handles_offset_; | |
233 // The first message's data may have been partially sent. |data_offset_| | |
234 // indicates the position in the first message's data to start the next | |
235 // write. | |
236 size_t data_offset_; | |
237 | |
238 MOJO_DISALLOW_COPY_AND_ASSIGN(WriteBuffer); | |
239 }; | |
240 | |
241 RawChannel(); | |
242 | |
243 // Shutdown must be called on the IO thread. This object deletes itself once | |
244 // it's flushed all pending writes and insured that the other side of the pipe | |
245 // read them. | |
246 ~RawChannel() override; | |
247 | |
248 // |result| must not be |IO_PENDING|. Must be called on the I/O thread WITHOUT | |
249 // |write_lock_| held. This object may be destroyed by this call. This | |
250 // acquires |write_lock_| inside of it. The caller needs to acquire read_lock_ | |
251 // first. | |
252 void OnReadCompletedNoLock(IOResult io_result, size_t bytes_read); | |
253 // |result| must not be |IO_PENDING|. Must be called on the I/O thread WITHOUT | |
254 // |write_lock_| held. This object may be destroyed by this call. The caller | |
255 // needs to acquire write_lock_ first. | |
256 void OnWriteCompletedNoLock(IOResult io_result, | |
257 size_t platform_handles_written, | |
258 size_t bytes_written); | |
259 | |
260 // Serialize the read buffer into the given array so that it can be sent to | |
261 // another process. Increments |num_valid_bytes_| by |additional_bytes_read| | |
262 // before serialization.. | |
263 void SerializeReadBuffer(size_t additional_bytes_read, | |
264 std::vector<char>* buffer); | |
265 | |
266 // Serialize the pending messages to be written to the OS pipe to the given | |
267 // buffer so that it can be sent to another process. | |
268 void SerializeWriteBuffer(size_t additional_bytes_written, | |
269 size_t additional_platform_handles_written, | |
270 std::vector<char>* buffer, | |
271 std::vector<int>* fds); | |
272 | |
273 base::Lock& write_lock() { return write_lock_; } | |
274 base::Lock& read_lock() { return read_lock_; } | |
275 | |
276 // Should only be called on the I/O thread. | |
277 ReadBuffer* read_buffer() { return read_buffer_.get(); } | |
278 | |
279 // Only called under |write_lock_|. | |
280 WriteBuffer* write_buffer_no_lock() { | |
281 write_lock_.AssertAcquired(); | |
282 return write_buffer_.get(); | |
283 } | |
284 | |
285 bool pending_write_error() { return pending_write_error_; } | |
286 | |
287 // Adds |message| to the write message queue. Implementation subclasses may | |
288 // override this to add any additional "control" messages needed. This is | |
289 // called (on any thread) with |write_lock_| held. | |
290 virtual void EnqueueMessageNoLock(scoped_ptr<MessageInTransit> message); | |
291 | |
292 // Handles any control messages targeted to the |RawChannel| (or | |
293 // implementation subclass). Implementation subclasses may override this to | |
294 // handle any implementation-specific control messages, but should call | |
295 // |RawChannel::OnReadMessageForRawChannel()| for any remaining messages. | |
296 // Returns true on success and false on error (e.g., invalid control message). | |
297 // This is only called on the I/O thread. | |
298 virtual bool OnReadMessageForRawChannel( | |
299 const MessageInTransit::View& message_view); | |
300 | |
301 #if defined(OS_POSIX) | |
302 // This is used to give the POSIX implementation FDs that belong to ReadBuffer | |
303 // and WriteBuffer after the channel is deserialized. | |
304 virtual void SetSerializedFDs(std::vector<int>* serialized_read_fds, | |
305 std::vector<int>* serialized_write_fds) = 0; | |
306 #endif | |
307 | |
308 // Returns true iff the pipe handle is valid. | |
309 virtual bool IsHandleValid() = 0; | |
310 | |
311 // Implementation must write any pending messages synchronously. | |
312 virtual ScopedPlatformHandle ReleaseHandleNoLock( | |
313 std::vector<char>* serialized_read_buffer, | |
314 std::vector<char>* serialized_write_buffer, | |
315 std::vector<int>* serialized_read_fds, | |
316 std::vector<int>* serialized_write_fds, | |
317 bool* write_error) = 0; | |
318 | |
319 // Reads into |read_buffer()|. | |
320 // This class guarantees that: | |
321 // - the area indicated by |GetBuffer()| will stay valid until read completion | |
322 // (but please also see the comments for |OnShutdownNoLock()|); | |
323 // - a second read is not started if there is a pending read; | |
324 // - the method is called on the I/O thread WITHOUT |write_lock_| held. | |
325 // | |
326 // The implementing subclass must guarantee that: | |
327 // - |bytes_read| is untouched unless |Read()| returns |IO_SUCCEEDED|; | |
328 // - if the method returns |IO_PENDING|, |OnReadCompleted()| will be called on | |
329 // the I/O thread to report the result, unless |Shutdown()| is called. | |
330 virtual IOResult Read(size_t* bytes_read) = 0; | |
331 // Similar to |Read()|, except that the implementing subclass must also | |
332 // guarantee that the method doesn't succeed synchronously, i.e., it only | |
333 // returns |IO_FAILED_...| or |IO_PENDING|. | |
334 virtual IOResult ScheduleRead() = 0; | |
335 | |
336 // Called by |OnReadCompleted()| to get the platform handles associated with | |
337 // the given platform handle table (from a message). This should only be | |
338 // called when |num_platform_handles| is nonzero. Returns null if the | |
339 // |num_platform_handles| handles are not available. Only called on the I/O | |
340 // thread (without |write_lock_| held). | |
341 virtual ScopedPlatformHandleVectorPtr GetReadPlatformHandles( | |
342 size_t num_platform_handles, | |
343 const void* platform_handle_table) = 0; | |
344 | |
345 // Serialize all platform handles for the front message in the queue from the | |
346 // transport data to the transport buffer. Returns how many handles were | |
347 // serialized. | |
348 // On POSIX, |fds| contains FDs from the front messages, if any. | |
349 virtual size_t SerializePlatformHandles(std::vector<int>* fds) = 0; | |
350 | |
351 // Writes contents in |write_buffer_no_lock()|. | |
352 // This class guarantees that: | |
353 // - the |PlatformHandle|s given by |GetPlatformHandlesToSend()| and the | |
354 // buffer(s) given by |GetBuffers()| will remain valid until write | |
355 // completion (see also the comments for |OnShutdownNoLock()|); | |
356 // - a second write is not started if there is a pending write; | |
357 // - the method is called under |write_lock_|. | |
358 // | |
359 // The implementing subclass must guarantee that: | |
360 // - |platform_handles_written| and |bytes_written| are untouched unless | |
361 // |WriteNoLock()| returns |IO_SUCCEEDED|; | |
362 // - if the method returns |IO_PENDING|, |OnWriteCompleted()| will be called | |
363 // on the I/O thread to report the result, unless |Shutdown()| is called. | |
364 virtual IOResult WriteNoLock(size_t* platform_handles_written, | |
365 size_t* bytes_written) = 0; | |
366 // Similar to |WriteNoLock()|, except that the implementing subclass must also | |
367 // guarantee that the method doesn't succeed synchronously, i.e., it only | |
368 // returns |IO_FAILED_...| or |IO_PENDING|. | |
369 virtual IOResult ScheduleWriteNoLock() = 0; | |
370 | |
371 // Must be called on the I/O thread WITHOUT |write_lock_| held. | |
372 virtual void OnInit() = 0; | |
373 // On shutdown, passes the ownership of the buffers to subclasses, which may | |
374 // want to preserve them if there are pending read/writes. After this is | |
375 // called, |OnReadCompleted()| must no longer be called. Must be called on the | |
376 // I/O thread under |write_lock_|. | |
377 virtual void OnShutdownNoLock(scoped_ptr<ReadBuffer> read_buffer, | |
378 scoped_ptr<WriteBuffer> write_buffer) = 0; | |
379 | |
380 bool SendQueuedMessagesNoLock(); | |
381 | |
382 private: | |
383 friend class base::DeleteHelper<RawChannel>; | |
384 | |
385 // Converts an |IO_FAILED_...| for a read to a |Delegate::Error|. | |
386 static Delegate::Error ReadIOResultToError(IOResult io_result); | |
387 | |
388 // Calls |delegate_->OnError(error)|. Must be called on the I/O thread WITHOUT | |
389 // |write_lock_| held. This object may be destroyed by this call. | |
390 void CallOnError(Delegate::Error error); | |
391 | |
392 void LockAndCallOnError(Delegate::Error error); | |
393 | |
394 // If |io_result| is |IO_SUCCESS|, updates the write buffer and schedules a | |
395 // write operation to run later if there is more to write. If |io_result| is | |
396 // failure or any other error occurs, cancels pending writes and returns | |
397 // false. Must be called under |write_lock_| and only if |write_stopped_| is | |
398 // false. | |
399 bool OnWriteCompletedInternalNoLock(IOResult io_result, | |
400 size_t platform_handles_written, | |
401 size_t bytes_written); | |
402 | |
403 // Helper method to dispatch messages from the read buffer. | |
404 // |did_dispatch_message| is true iff it dispatched any messages. | |
405 // |stop_dispatching| is set to true if the code calling this should stop | |
406 // dispatching, either because we hit an erorr or the delegate shutdown the | |
407 // channel. | |
408 void DispatchMessages(bool* did_dispatch_message, bool* stop_dispatching); | |
409 | |
410 void UpdateWriteBuffer(size_t platform_handles_written, size_t bytes_written); | |
411 | |
412 // Acquires read_lock_ and calls OnReadCompletedNoLock. | |
413 void CallOnReadCompleted(IOResult io_result, size_t bytes_read); | |
414 | |
415 // Used with PostTask to acquire both locks and call LazyInitialize. | |
416 void LockAndCallLazyInitialize(); | |
417 | |
418 // Connects to the OS pipe. | |
419 void LazyInitialize(); | |
420 | |
421 // base::MessageLoop::DestructionObserver: | |
422 void WillDestroyCurrentMessageLoop() override; | |
423 | |
424 | |
425 | |
426 | |
427 | |
428 // TODO(jam): one lock only... but profile first to ensure it doesn't slow | |
429 // things down compared to fine grained locks. | |
430 | |
431 | |
432 | |
433 | |
434 // Only used on the I/O thread (with exception noted below). | |
435 base::Lock read_lock_; // Protects read_buffer_. | |
436 // This is usually only accessed on IO thread, except when ReleaseHandle is | |
437 // called. | |
438 scoped_ptr<ReadBuffer> read_buffer_; | |
439 // ditto: usually used on io thread except ReleaseHandle | |
440 Delegate* delegate_; | |
441 // This is only used on the IO thread, so we don't bother with locking. | |
442 bool error_occurred_; | |
443 bool calling_delegate_; | |
444 | |
445 // If grabbing both locks, grab read first. | |
446 | |
447 base::Lock write_lock_; // Protects the following members. | |
448 bool write_ready_; | |
449 bool write_stopped_; | |
450 scoped_ptr<WriteBuffer> write_buffer_; | |
451 // True iff a PostTask has been called for a write error. Can be written under | |
452 // either read or write lock. It's read with both acquired. | |
453 bool pending_write_error_; | |
454 | |
455 // True iff we connected to the underying pipe. | |
456 bool initialized_; | |
457 | |
458 // This is used for posting tasks from write threads to the I/O thread. It | |
459 // must only be accessed under |write_lock_|. The weak pointers it produces | |
460 // are only used/invalidated on the I/O thread. | |
461 base::WeakPtrFactory<RawChannel> weak_ptr_factory_; | |
462 | |
463 MOJO_DISALLOW_COPY_AND_ASSIGN(RawChannel); | |
464 }; | |
465 | |
466 } // namespace edk | |
467 } // namespace mojo | |
468 | |
469 #endif // MOJO_EDK_SYSTEM_RAW_CHANNEL_H_ | |
OLD | NEW |