summaryrefslogtreecommitdiffstats
path: root/mojo/edk/system/channel.cc
blob: e74b9004758fd7851750ccd004314839ec9d9b3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/edk/system/channel.h"

#include <string.h>

#include <algorithm>
#include <limits>

#include "base/macros.h"
#include "base/memory/aligned_memory.h"
#include "mojo/edk/embedder/platform_handle.h"

namespace mojo {
namespace edk {

namespace {

static_assert(sizeof(Channel::Message::Header) % kChannelMessageAlignment == 0,
    "Invalid Header size.");

#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
static_assert(sizeof(Channel::Message::Header) == 8,
              "Header must be 8 bytes on ChromeOS and Android");
#endif

}  // namespace

const size_t kReadBufferSize = 4096;
const size_t kMaxUnusedReadBufferCapacity = 256 * 1024;
const size_t kMaxChannelMessageSize = 256 * 1024 * 1024;
const size_t kMaxAttachedHandles = 128;

Channel::Message::Message(size_t payload_size,
                          size_t max_handles,
                          Header::MessageType message_type)
    : max_handles_(max_handles) {
  DCHECK_LE(max_handles_, kMaxAttachedHandles);

  size_t extra_header_size = 0;
#if defined(OS_WIN)
  // On Windows we serialize platform handles into the extra header space.
  extra_header_size = max_handles_ * sizeof(PlatformHandle);
#endif
  // Pad extra header data to be aliged to |kChannelMessageAlignment| bytes.
  if (extra_header_size % kChannelMessageAlignment) {
    extra_header_size += kChannelMessageAlignment -
                         (extra_header_size % kChannelMessageAlignment);
  }
  DCHECK_EQ(0u, extra_header_size % kChannelMessageAlignment);
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
  DCHECK_EQ(0u, extra_header_size);
#endif

  size_ = sizeof(Header) + extra_header_size + payload_size;
  data_ = static_cast<char*>(base::AlignedAlloc(size_,
                                                kChannelMessageAlignment));
  // Only zero out the header and not the payload. Since the payload is going to
  // be memcpy'd, zeroing the payload is unnecessary work and a significant
  // performance issue when dealing with large messages. Any sanitizer errors
  // complaining about an uninitialized read in the payload area should be
  // treated as an error and fixed.
  memset(data_, 0, sizeof(Header) + extra_header_size);
  header_ = reinterpret_cast<Header*>(data_);

  DCHECK_LE(size_, std::numeric_limits<uint32_t>::max());
  header_->num_bytes = static_cast<uint32_t>(size_);

  DCHECK_LE(sizeof(Header) + extra_header_size,
            std::numeric_limits<uint16_t>::max());
  header_->message_type = message_type;
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
  header_->num_handles = static_cast<uint16_t>(max_handles);
#else
  header_->num_header_bytes =
      static_cast<uint16_t>(sizeof(Header) + extra_header_size);
#endif

#if defined(OS_WIN)
  if (max_handles_ > 0) {
    handles_ = reinterpret_cast<PlatformHandle*>(mutable_extra_header());
    // Initialize all handles to invalid values.
    for (size_t i = 0; i < max_handles_; ++i)
      handles()[i] = PlatformHandle();
  }
#endif
}

Channel::Message::~Message() {
#if defined(OS_WIN)
  // On POSIX the ScopedPlatformHandleVectorPtr will do this for us.
  for (size_t i = 0; i < header_->num_handles; ++i)
    handles()[i].CloseIfNecessary();
#endif
  base::AlignedFree(data_);
}

// static
Channel::MessagePtr Channel::Message::Deserialize(const void* data,
                                                  size_t data_num_bytes) {
#if !defined(OS_WIN)
  // We only serialize messages into other messages when performing message
  // relay on Windows.
  NOTREACHED();
  return nullptr;
#else
  if (data_num_bytes < sizeof(Header))
    return nullptr;

  const Header* header = reinterpret_cast<const Header*>(data);
  if (header->num_bytes != data_num_bytes) {
    DLOG(ERROR) << "Decoding invalid message: " << header->num_bytes
                << " != " << data_num_bytes;
    return nullptr;
  }

  if (header->num_bytes < header->num_header_bytes) {
    DLOG(ERROR) << "Decoding invalid message: " << header->num_bytes << " < "
                << header->num_header_bytes;
    return nullptr;
  }

  uint32_t extra_header_size = header->num_header_bytes - sizeof(Header);
  uint32_t max_handles = extra_header_size / sizeof(PlatformHandle);
  if (header->num_handles > max_handles) {
    DLOG(ERROR) << "Decoding invalid message:" << header->num_handles << " > "
                << max_handles;
    return nullptr;
  }

  MessagePtr message(
      new Message(data_num_bytes - header->num_header_bytes, max_handles));

  DCHECK_EQ(message->data_num_bytes(), data_num_bytes);
  DCHECK_EQ(message->extra_header_size(), extra_header_size);
  DCHECK_EQ(message->header_->num_header_bytes, header->num_header_bytes);

  // Copy all payload bytes.
  memcpy(message->mutable_payload(),
         static_cast<const char*>(data) + header->num_header_bytes,
         data_num_bytes - header->num_header_bytes);
  // Copy extra header bytes.
  memcpy(message->mutable_extra_header(),
         static_cast<const char*>(data) + sizeof(Header),
         message->extra_header_size());
  message->header_->num_handles = header->num_handles;

  return message;
#endif
}

size_t Channel::Message::payload_size() const {
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
  return header_->num_bytes - sizeof(Header);
#else
  return size_ - header_->num_header_bytes;
#endif
}

PlatformHandle* Channel::Message::handles() {
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
  // Old semantics for ChromeOS and Android.
  if (header_->num_handles == 0)
    return nullptr;
  CHECK(handle_vector_);
  return handle_vector_->data();
#else
  if (max_handles_ == 0)
    return nullptr;
#if defined(OS_WIN)
  return handles_;
#else
  CHECK(handle_vector_);
  return handle_vector_->data();
#endif  // defined(OS_WIN)
#endif  // defined(OS_CHROMEOS) || defined(OS_ANDROID)
}

#if defined(OS_MACOSX) && !defined(OS_IOS)
bool Channel::Message::has_mach_ports() const {
  if (!has_handles())
    return false;

  for (const auto& handle : (*handle_vector_)) {
    if (handle.type == PlatformHandle::Type::MACH)
      return true;
  }
  return false;
}
#endif

void Channel::Message::SetHandles(ScopedPlatformHandleVectorPtr new_handles) {
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
  // Old semantics for ChromeOS and Android
  if (header_->num_handles == 0) {
    CHECK(!new_handles || new_handles->size() == 0);
    return;
  }
  CHECK(new_handles && new_handles->size() == header_->num_handles);
  std::swap(handle_vector_, new_handles);

#else
  if (max_handles_ == 0) {
    CHECK(!new_handles || new_handles->size() == 0);
    return;
  }

  CHECK(new_handles && new_handles->size() <= max_handles_);
  header_->num_handles = static_cast<uint16_t>(new_handles->size());
#if defined(OS_WIN)
  memcpy(handles(), new_handles->data(),
         sizeof(PlatformHandle) * new_handles->size());
  new_handles->clear();
#else
  std::swap(handle_vector_, new_handles);
#endif  // defined(OS_WIN)
#endif  // defined(OS_CHROMEOS) || defined(OS_ANDROID)
}

ScopedPlatformHandleVectorPtr Channel::Message::TakeHandles() {
#if defined(OS_WIN)
  if (header_->num_handles == 0)
    return ScopedPlatformHandleVectorPtr();
  ScopedPlatformHandleVectorPtr moved_handles(
      new PlatformHandleVector(header_->num_handles));
  for (size_t i = 0; i < header_->num_handles; ++i)
    std::swap(moved_handles->at(i), handles()[i]);
  return moved_handles;
#else
  return std::move(handle_vector_);
#endif
}

#if defined(OS_WIN)
// static
bool Channel::Message::RewriteHandles(base::ProcessHandle from_process,
                                      base::ProcessHandle to_process,
                                      PlatformHandle* handles,
                                      size_t num_handles) {
  bool success = true;
  for (size_t i = 0; i < num_handles; ++i) {
    if (!handles[i].is_valid()) {
      DLOG(ERROR) << "Refusing to duplicate invalid handle.";
      continue;
    }
    BOOL result = DuplicateHandle(
        from_process, handles[i].handle, to_process,
        reinterpret_cast<HANDLE*>(handles + i), 0, FALSE,
        DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
    if (!result)
      success = false;
  }
  return success;
}
#endif

// Helper class for managing a Channel's read buffer allocations. This maintains
// a single contiguous buffer with the layout:
//
//   [discarded bytes][occupied bytes][unoccupied bytes]
//
// The Reserve() method ensures that a certain capacity of unoccupied bytes are
// available. It does not claim that capacity and only allocates new capacity
// when strictly necessary.
//
// Claim() marks unoccupied bytes as occupied.
//
// Discard() marks occupied bytes as discarded, signifying that their contents
// can be forgotten or overwritten.
//
// The most common Channel behavior in practice should result in very few
// allocations and copies, as memory is claimed and discarded shortly after
// being reserved, and future reservations will immediately reuse discarded
// memory.
class Channel::ReadBuffer {
 public:
  ReadBuffer() {
    size_ = kReadBufferSize;
    data_ = static_cast<char*>(base::AlignedAlloc(size_,
                                                  kChannelMessageAlignment));
  }

  ~ReadBuffer() {
    DCHECK(data_);
    base::AlignedFree(data_);
  }

  const char* occupied_bytes() const { return data_ + num_discarded_bytes_; }

  size_t num_occupied_bytes() const {
    return num_occupied_bytes_ - num_discarded_bytes_;
  }

  // Ensures the ReadBuffer has enough contiguous space allocated to hold
  // |num_bytes| more bytes; returns the address of the first available byte.
  char* Reserve(size_t num_bytes) {
    if (num_occupied_bytes_ + num_bytes > size_) {
      size_ = std::max(size_ * 2, num_occupied_bytes_ + num_bytes);
      void* new_data = base::AlignedAlloc(size_, kChannelMessageAlignment);
      memcpy(new_data, data_, num_occupied_bytes_);
      base::AlignedFree(data_);
      data_ = static_cast<char*>(new_data);
    }

    return data_ + num_occupied_bytes_;
  }

  // Marks the first |num_bytes| unoccupied bytes as occupied.
  void Claim(size_t num_bytes) {
    DCHECK_LE(num_occupied_bytes_ + num_bytes, size_);
    num_occupied_bytes_ += num_bytes;
  }

  // Marks the first |num_bytes| occupied bytes as discarded. This may result in
  // shrinkage of the internal buffer, and it is not safe to assume the result
  // of a previous Reserve() call is still valid after this.
  void Discard(size_t num_bytes) {
    DCHECK_LE(num_discarded_bytes_ + num_bytes, num_occupied_bytes_);
    num_discarded_bytes_ += num_bytes;

    if (num_discarded_bytes_ == num_occupied_bytes_) {
      // We can just reuse the buffer from the beginning in this common case.
      num_discarded_bytes_ = 0;
      num_occupied_bytes_ = 0;
    }

    if (num_discarded_bytes_ > kMaxUnusedReadBufferCapacity) {
      // In the uncommon case that we have a lot of discarded data at the
      // front of the buffer, simply move remaining data to a smaller buffer.
      size_t num_preserved_bytes = num_occupied_bytes_ - num_discarded_bytes_;
      size_ = std::max(num_preserved_bytes, kReadBufferSize);
      char* new_data = static_cast<char*>(
          base::AlignedAlloc(size_, kChannelMessageAlignment));
      memcpy(new_data, data_ + num_discarded_bytes_, num_preserved_bytes);
      base::AlignedFree(data_);
      data_ = new_data;
      num_discarded_bytes_ = 0;
      num_occupied_bytes_ = num_preserved_bytes;
    }

    // TODO: we should also adaptively shrink the buffer in case of the
    // occasional abnormally large read.
  }

 private:
  char* data_ = nullptr;

  // The total size of the allocated buffer.
  size_t size_ = 0;

  // The number of discarded bytes at the beginning of the allocated buffer.
  size_t num_discarded_bytes_ = 0;

  // The total number of occupied bytes, including discarded bytes.
  size_t num_occupied_bytes_ = 0;

  DISALLOW_COPY_AND_ASSIGN(ReadBuffer);
};

Channel::Channel(Delegate* delegate)
    : delegate_(delegate), read_buffer_(new ReadBuffer) {
}

Channel::~Channel() {
}

void Channel::ShutDown() {
  delegate_ = nullptr;
  ShutDownImpl();
}

char* Channel::GetReadBuffer(size_t *buffer_capacity) {
  DCHECK(read_buffer_);
  size_t required_capacity = *buffer_capacity;
  if (!required_capacity)
    required_capacity = kReadBufferSize;

  *buffer_capacity = required_capacity;
  return read_buffer_->Reserve(required_capacity);
}

bool Channel::OnReadComplete(size_t bytes_read, size_t *next_read_size_hint) {
  bool did_dispatch_message = false;
  read_buffer_->Claim(bytes_read);
  while (read_buffer_->num_occupied_bytes() >= sizeof(Message::Header)) {
    // We have at least enough data available for a MessageHeader.
    const Message::Header* header = reinterpret_cast<const Message::Header*>(
        read_buffer_->occupied_bytes());
    if (header->num_bytes < sizeof(Message::Header) ||
        header->num_bytes > kMaxChannelMessageSize) {
      LOG(ERROR) << "Invalid message size: " << header->num_bytes;
      return false;
    }

    if (read_buffer_->num_occupied_bytes() < header->num_bytes) {
      // Not enough data available to read the full message. Hint to the
      // implementation that it should try reading the full size of the message.
      *next_read_size_hint =
          header->num_bytes - read_buffer_->num_occupied_bytes();
      return true;
    }

#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
    size_t extra_header_size = 0;
    const void* extra_header = nullptr;
    size_t payload_size = header->num_bytes - sizeof(Message::Header);
    void* payload = payload_size ? const_cast<Message::Header*>(&header[1])
                                 : nullptr;
#else
    size_t extra_header_size =
        header->num_header_bytes - sizeof(Message::Header);
    const void* extra_header = header + 1;
    size_t payload_size = header->num_bytes - header->num_header_bytes;
    void* payload =
        payload_size ? reinterpret_cast<Message::Header*>(
                           const_cast<char*>(read_buffer_->occupied_bytes()) +
                           header->num_header_bytes)
                     : nullptr;
#endif  // defined(OS_CHROMEOS) || defined(OS_ANDROID)

    ScopedPlatformHandleVectorPtr handles;
    if (header->num_handles > 0) {
      handles = GetReadPlatformHandles(header->num_handles, extra_header,
                                       extra_header_size);
      if (!handles) {
        // Not enough handles available for this message.
        break;
      }
    }

    // We've got a complete message! Dispatch it and try another.
    if (header->message_type != Message::Header::MessageType::NORMAL) {
      OnControlMessage(header->message_type, payload, payload_size,
                       std::move(handles));
      did_dispatch_message = true;
    } else if (delegate_) {
      delegate_->OnChannelMessage(payload, payload_size, std::move(handles));
      did_dispatch_message = true;
    }

    read_buffer_->Discard(header->num_bytes);
  }

  *next_read_size_hint = did_dispatch_message ? 0 : kReadBufferSize;
  return true;
}

void Channel::OnError() {
  if (delegate_)
    delegate_->OnChannelError();
}

}  // namespace edk
}  // namespace mojo