raw_channel.cc revision 5f1c94371a64b3196d4be9466099bb892df9b88e
1// Copyright 2014 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#include "mojo/system/raw_channel.h"
6
7#include <string.h>
8
9#include <algorithm>
10
11#include "base/bind.h"
12#include "base/location.h"
13#include "base/logging.h"
14#include "base/message_loop/message_loop.h"
15#include "base/stl_util.h"
16#include "mojo/system/message_in_transit.h"
17#include "mojo/system/transport_data.h"
18
19namespace mojo {
20namespace system {
21
22const size_t kReadSize = 4096;
23
24// RawChannel::ReadBuffer ------------------------------------------------------
25
26RawChannel::ReadBuffer::ReadBuffer() : buffer_(kReadSize), num_valid_bytes_(0) {
27}
28
29RawChannel::ReadBuffer::~ReadBuffer() {
30}
31
32void RawChannel::ReadBuffer::GetBuffer(char** addr, size_t* size) {
33  CHECK_GE(buffer_.size(), num_valid_bytes_ + kReadSize);
34  *addr = &buffer_[0] + num_valid_bytes_;
35  *size = kReadSize;
36}
37
38// RawChannel::WriteBuffer -----------------------------------------------------
39
40RawChannel::WriteBuffer::WriteBuffer(size_t serialized_platform_handle_size)
41    : serialized_platform_handle_size_(serialized_platform_handle_size),
42      platform_handles_offset_(0),
43      data_offset_(0) {
44}
45
46RawChannel::WriteBuffer::~WriteBuffer() {
47  STLDeleteElements(&message_queue_);
48}
49
50bool RawChannel::WriteBuffer::HavePlatformHandlesToSend() const {
51  if (message_queue_.empty())
52    return false;
53
54  const TransportData* transport_data =
55      message_queue_.front()->transport_data();
56  if (!transport_data)
57    return false;
58
59  const embedder::PlatformHandleVector* all_platform_handles =
60      transport_data->platform_handles();
61  if (!all_platform_handles) {
62    CHECK_EQ(platform_handles_offset_, 0u);
63    return false;
64  }
65  if (platform_handles_offset_ >= all_platform_handles->size()) {
66    CHECK_EQ(platform_handles_offset_, all_platform_handles->size());
67    return false;
68  }
69
70  return true;
71}
72
73void RawChannel::WriteBuffer::GetPlatformHandlesToSend(
74    size_t* num_platform_handles,
75    embedder::PlatformHandle** platform_handles,
76    void** serialization_data) {
77  CHECK(HavePlatformHandlesToSend());
78
79  TransportData* transport_data = message_queue_.front()->transport_data();
80  embedder::PlatformHandleVector* all_platform_handles =
81      transport_data->platform_handles();
82  *num_platform_handles =
83      all_platform_handles->size() - platform_handles_offset_;
84  *platform_handles = &(*all_platform_handles)[platform_handles_offset_];
85  size_t serialization_data_offset =
86      transport_data->platform_handle_table_offset();
87  CHECK_GT(serialization_data_offset, 0u);
88  serialization_data_offset +=
89      platform_handles_offset_ * serialized_platform_handle_size_;
90  *serialization_data =
91      static_cast<char*>(transport_data->buffer()) + serialization_data_offset;
92}
93
94void RawChannel::WriteBuffer::GetBuffers(std::vector<Buffer>* buffers) const {
95  buffers->clear();
96
97  if (message_queue_.empty())
98    return;
99
100  MessageInTransit* message = message_queue_.front();
101  CHECK_LT(data_offset_, message->total_size());
102  size_t bytes_to_write = message->total_size() - data_offset_;
103
104  size_t transport_data_buffer_size =
105      message->transport_data() ? message->transport_data()->buffer_size() : 0;
106
107  if (!transport_data_buffer_size) {
108    // Only write from the main buffer.
109    CHECK_LT(data_offset_, message->main_buffer_size());
110    CHECK_LE(bytes_to_write, message->main_buffer_size());
111    Buffer buffer = {
112        static_cast<const char*>(message->main_buffer()) + data_offset_,
113        bytes_to_write};
114    buffers->push_back(buffer);
115    return;
116  }
117
118  if (data_offset_ >= message->main_buffer_size()) {
119    // Only write from the transport data buffer.
120    CHECK_LT(data_offset_ - message->main_buffer_size(),
121             transport_data_buffer_size);
122    CHECK_LE(bytes_to_write, transport_data_buffer_size);
123    Buffer buffer = {
124        static_cast<const char*>(message->transport_data()->buffer()) +
125            (data_offset_ - message->main_buffer_size()),
126        bytes_to_write};
127    buffers->push_back(buffer);
128    return;
129  }
130
131  // TODO(vtl): We could actually send out buffers from multiple messages, with
132  // the "stopping" condition being reaching a message with platform handles
133  // attached.
134
135  // Write from both buffers.
136  CHECK_EQ(
137      bytes_to_write,
138      message->main_buffer_size() - data_offset_ + transport_data_buffer_size);
139  Buffer buffer1 = {
140      static_cast<const char*>(message->main_buffer()) + data_offset_,
141      message->main_buffer_size() - data_offset_};
142  buffers->push_back(buffer1);
143  Buffer buffer2 = {
144      static_cast<const char*>(message->transport_data()->buffer()),
145      transport_data_buffer_size};
146  buffers->push_back(buffer2);
147}
148
149// RawChannel ------------------------------------------------------------------
150
151RawChannel::RawChannel()
152    : message_loop_for_io_(NULL),
153      delegate_(NULL),
154      read_stopped_(false),
155      write_stopped_(false),
156      weak_ptr_factory_(this) {
157}
158
159RawChannel::~RawChannel() {
160  CHECK(!read_buffer_);
161  CHECK(!write_buffer_);
162
163  // No need to take the |write_lock_| here -- if there are still weak pointers
164  // outstanding, then we're hosed anyway (since we wouldn't be able to
165  // invalidate them cleanly, since we might not be on the I/O thread).
166  CHECK(!weak_ptr_factory_.HasWeakPtrs());
167}
168
169bool RawChannel::Init(Delegate* delegate) {
170  CHECK(delegate);
171
172  CHECK(!delegate_);
173  delegate_ = delegate;
174
175  CHECK_EQ(base::MessageLoop::current()->type(), base::MessageLoop::TYPE_IO);
176  CHECK(!message_loop_for_io_);
177  message_loop_for_io_ =
178      static_cast<base::MessageLoopForIO*>(base::MessageLoop::current());
179
180  // No need to take the lock. No one should be using us yet.
181  CHECK(!read_buffer_);
182  read_buffer_.reset(new ReadBuffer);
183  CHECK(!write_buffer_);
184  write_buffer_.reset(new WriteBuffer(GetSerializedPlatformHandleSize()));
185
186  if (!OnInit()) {
187    delegate_ = NULL;
188    message_loop_for_io_ = NULL;
189    read_buffer_.reset();
190    write_buffer_.reset();
191    return false;
192  }
193
194  if (ScheduleRead() != IO_PENDING) {
195    // This will notify the delegate about the read failure. Although we're on
196    // the I/O thread, don't call it in the nested context.
197    message_loop_for_io_->PostTask(FROM_HERE,
198                                   base::Bind(&RawChannel::OnReadCompleted,
199                                              weak_ptr_factory_.GetWeakPtr(),
200                                              false,
201                                              0));
202  }
203
204  // ScheduleRead() failure is treated as a read failure (by notifying the
205  // delegate), not as an init failure.
206  return true;
207}
208
209void RawChannel::Shutdown() {
210  CHECK_EQ(base::MessageLoop::current(), message_loop_for_io_);
211
212  base::AutoLock locker(write_lock_);
213
214  LOG_IF(WARNING, !write_buffer_->message_queue_.empty())
215      << "Shutting down RawChannel with write buffer nonempty";
216
217  // Reset the delegate so that it won't receive further calls.
218  delegate_ = NULL;
219  read_stopped_ = true;
220  write_stopped_ = true;
221  weak_ptr_factory_.InvalidateWeakPtrs();
222
223  OnShutdownNoLock(read_buffer_.Pass(), write_buffer_.Pass());
224}
225
226// Reminder: This must be thread-safe.
227bool RawChannel::WriteMessage(scoped_ptr<MessageInTransit> message) {
228  CHECK(message);
229
230  base::AutoLock locker(write_lock_);
231  if (write_stopped_)
232    return false;
233
234  if (!write_buffer_->message_queue_.empty()) {
235    EnqueueMessageNoLock(message.Pass());
236    return true;
237  }
238
239  EnqueueMessageNoLock(message.Pass());
240  CHECK_EQ(write_buffer_->data_offset_, 0u);
241
242  size_t platform_handles_written = 0;
243  size_t bytes_written = 0;
244  IOResult io_result = WriteNoLock(&platform_handles_written, &bytes_written);
245  if (io_result == IO_PENDING)
246    return true;
247
248  bool result = OnWriteCompletedNoLock(
249      io_result == IO_SUCCEEDED, platform_handles_written, bytes_written);
250  if (!result) {
251    // Even if we're on the I/O thread, don't call |OnFatalError()| in the
252    // nested context.
253    message_loop_for_io_->PostTask(FROM_HERE,
254                                   base::Bind(&RawChannel::CallOnFatalError,
255                                              weak_ptr_factory_.GetWeakPtr(),
256                                              Delegate::FATAL_ERROR_WRITE));
257  }
258
259  return result;
260}
261
262// Reminder: This must be thread-safe.
263bool RawChannel::IsWriteBufferEmpty() {
264  base::AutoLock locker(write_lock_);
265  return write_buffer_->message_queue_.empty();
266}
267
268void RawChannel::OnReadCompleted(bool result, size_t bytes_read) {
269  CHECK_EQ(base::MessageLoop::current(), message_loop_for_io_);
270
271  if (read_stopped_) {
272    NOTREACHED();
273    return;
274  }
275
276  IOResult io_result = result ? IO_SUCCEEDED : IO_FAILED;
277
278  // Keep reading data in a loop, and dispatch messages if enough data is
279  // received. Exit the loop if any of the following happens:
280  //   - one or more messages were dispatched;
281  //   - the last read failed, was a partial read or would block;
282  //   - |Shutdown()| was called.
283  do {
284    if (io_result != IO_SUCCEEDED) {
285      read_stopped_ = true;
286      CallOnFatalError(Delegate::FATAL_ERROR_READ);
287      return;
288    }
289
290    read_buffer_->num_valid_bytes_ += bytes_read;
291
292    // Dispatch all the messages that we can.
293    bool did_dispatch_message = false;
294    // Tracks the offset of the first undispatched message in |read_buffer_|.
295    // Currently, we copy data to ensure that this is zero at the beginning.
296    size_t read_buffer_start = 0;
297    size_t remaining_bytes = read_buffer_->num_valid_bytes_;
298    size_t message_size;
299    // Note that we rely on short-circuit evaluation here:
300    //   - |read_buffer_start| may be an invalid index into
301    //     |read_buffer_->buffer_| if |remaining_bytes| is zero.
302    //   - |message_size| is only valid if |GetNextMessageSize()| returns true.
303    // TODO(vtl): Use |message_size| more intelligently (e.g., to request the
304    // next read).
305    // TODO(vtl): Validate that |message_size| is sane.
306    while (remaining_bytes > 0 && MessageInTransit::GetNextMessageSize(
307                                      &read_buffer_->buffer_[read_buffer_start],
308                                      remaining_bytes,
309                                      &message_size) &&
310           remaining_bytes >= message_size) {
311      MessageInTransit::View message_view(
312          message_size, &read_buffer_->buffer_[read_buffer_start]);
313      CHECK_EQ(message_view.total_size(), message_size);
314
315      const char* error_message = NULL;
316      if (!message_view.IsValid(GetSerializedPlatformHandleSize(),
317                                &error_message)) {
318        CHECK(error_message);
319        LOG(WARNING) << "Received invalid message: " << error_message;
320        read_stopped_ = true;
321        CallOnFatalError(Delegate::FATAL_ERROR_READ);
322        return;
323      }
324
325      if (message_view.type() == MessageInTransit::kTypeRawChannel) {
326        if (!OnReadMessageForRawChannel(message_view)) {
327          read_stopped_ = true;
328          CallOnFatalError(Delegate::FATAL_ERROR_READ);
329          return;
330        }
331      } else {
332        embedder::ScopedPlatformHandleVectorPtr platform_handles;
333        if (message_view.transport_data_buffer()) {
334          size_t num_platform_handles;
335          const void* platform_handle_table;
336          TransportData::GetPlatformHandleTable(
337              message_view.transport_data_buffer(),
338              &num_platform_handles,
339              &platform_handle_table);
340
341          if (num_platform_handles > 0) {
342            platform_handles =
343                GetReadPlatformHandles(num_platform_handles,
344                                       platform_handle_table).Pass();
345            if (!platform_handles) {
346              LOG(WARNING) << "Invalid number of platform handles received";
347              read_stopped_ = true;
348              CallOnFatalError(Delegate::FATAL_ERROR_READ);
349              return;
350            }
351          }
352        }
353
354        // TODO(vtl): In the case that we aren't expecting any platform handles,
355        // for the POSIX implementation, we should confirm that none are stored.
356
357        // Dispatch the message.
358        CHECK(delegate_);
359        delegate_->OnReadMessage(message_view, platform_handles.Pass());
360        if (read_stopped_) {
361          // |Shutdown()| was called in |OnReadMessage()|.
362          // TODO(vtl): Add test for this case.
363          return;
364        }
365      }
366
367      did_dispatch_message = true;
368
369      // Update our state.
370      read_buffer_start += message_size;
371      remaining_bytes -= message_size;
372    }
373
374    if (read_buffer_start > 0) {
375      // Move data back to start.
376      read_buffer_->num_valid_bytes_ = remaining_bytes;
377      if (read_buffer_->num_valid_bytes_ > 0) {
378        memmove(&read_buffer_->buffer_[0],
379                &read_buffer_->buffer_[read_buffer_start],
380                remaining_bytes);
381      }
382      read_buffer_start = 0;
383    }
384
385    if (read_buffer_->buffer_.size() - read_buffer_->num_valid_bytes_ <
386        kReadSize) {
387      // Use power-of-2 buffer sizes.
388      // TODO(vtl): Make sure the buffer doesn't get too large (and enforce the
389      // maximum message size to whatever extent necessary).
390      // TODO(vtl): We may often be able to peek at the header and get the real
391      // required extra space (which may be much bigger than |kReadSize|).
392      size_t new_size = std::max(read_buffer_->buffer_.size(), kReadSize);
393      while (new_size < read_buffer_->num_valid_bytes_ + kReadSize)
394        new_size *= 2;
395
396      // TODO(vtl): It's suboptimal to zero out the fresh memory.
397      read_buffer_->buffer_.resize(new_size, 0);
398    }
399
400    // (1) If we dispatched any messages, stop reading for now (and let the
401    // message loop do its thing for another round).
402    // TODO(vtl): Is this the behavior we want? (Alternatives: i. Dispatch only
403    // a single message. Risks: slower, more complex if we want to avoid lots of
404    // copying. ii. Keep reading until there's no more data and dispatch all the
405    // messages we can. Risks: starvation of other users of the message loop.)
406    // (2) If we didn't max out |kReadSize|, stop reading for now.
407    bool schedule_for_later = did_dispatch_message || bytes_read < kReadSize;
408    bytes_read = 0;
409    io_result = schedule_for_later ? ScheduleRead() : Read(&bytes_read);
410  } while (io_result != IO_PENDING);
411}
412
413void RawChannel::OnWriteCompleted(bool result,
414                                  size_t platform_handles_written,
415                                  size_t bytes_written) {
416  CHECK_EQ(base::MessageLoop::current(), message_loop_for_io_);
417
418  bool did_fail = false;
419  {
420    base::AutoLock locker(write_lock_);
421    CHECK_EQ(write_stopped_, write_buffer_->message_queue_.empty());
422
423    if (write_stopped_) {
424      NOTREACHED();
425      return;
426    }
427
428    did_fail = !OnWriteCompletedNoLock(
429                   result, platform_handles_written, bytes_written);
430  }
431
432  if (did_fail)
433    CallOnFatalError(Delegate::FATAL_ERROR_WRITE);
434}
435
436void RawChannel::EnqueueMessageNoLock(scoped_ptr<MessageInTransit> message) {
437  write_lock_.AssertAcquired();
438  write_buffer_->message_queue_.push_back(message.release());
439}
440
441bool RawChannel::OnReadMessageForRawChannel(
442    const MessageInTransit::View& message_view) {
443  // No non-implementation specific |RawChannel| control messages.
444  LOG(ERROR) << "Invalid control message (subtype " << message_view.subtype()
445             << ")";
446  return false;
447}
448
449void RawChannel::CallOnFatalError(Delegate::FatalError fatal_error) {
450  CHECK_EQ(base::MessageLoop::current(), message_loop_for_io_);
451  // TODO(vtl): Add a "write_lock_.AssertNotAcquired()"?
452  if (delegate_)
453    delegate_->OnFatalError(fatal_error);
454}
455
456bool RawChannel::OnWriteCompletedNoLock(bool result,
457                                        size_t platform_handles_written,
458                                        size_t bytes_written) {
459  write_lock_.AssertAcquired();
460
461  CHECK(!write_stopped_);
462  CHECK(!write_buffer_->message_queue_.empty());
463
464  if (result) {
465    write_buffer_->platform_handles_offset_ += platform_handles_written;
466    write_buffer_->data_offset_ += bytes_written;
467
468    MessageInTransit* message = write_buffer_->message_queue_.front();
469    if (write_buffer_->data_offset_ >= message->total_size()) {
470      // Complete write.
471      CHECK_EQ(write_buffer_->data_offset_, message->total_size());
472      write_buffer_->message_queue_.pop_front();
473      delete message;
474      write_buffer_->platform_handles_offset_ = 0;
475      write_buffer_->data_offset_ = 0;
476
477      if (write_buffer_->message_queue_.empty())
478        return true;
479    }
480
481    // Schedule the next write.
482    IOResult io_result = ScheduleWriteNoLock();
483    if (io_result == IO_PENDING)
484      return true;
485    CHECK_EQ(io_result, IO_FAILED);
486  }
487
488  write_stopped_ = true;
489  STLDeleteElements(&write_buffer_->message_queue_);
490  write_buffer_->platform_handles_offset_ = 0;
491  write_buffer_->data_offset_ = 0;
492  return false;
493}
494
495}  // namespace system
496}  // namespace mojo
497