1 // Copyright 2016 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/public/cpp/bindings/lib/message_buffer.h"
6
7 #include <limits>
8
9 #include "mojo/public/cpp/bindings/lib/serialization_util.h"
10
11 namespace mojo {
12 namespace internal {
13
MessageBuffer(size_t capacity,bool zero_initialized)14 MessageBuffer::MessageBuffer(size_t capacity, bool zero_initialized) {
15 DCHECK_LE(capacity, std::numeric_limits<uint32_t>::max());
16 data_num_bytes_ = static_cast<uint32_t>(capacity);
17
18 MojoResult rv = AllocMessage(capacity, nullptr, 0,
19 MOJO_ALLOC_MESSAGE_FLAG_NONE, &message_);
20 CHECK_EQ(rv, MOJO_RESULT_OK);
21
22 if (capacity == 0) {
23 buffer_ = nullptr;
24 } else {
25 rv = GetMessageBuffer(message_.get(), &buffer_);
26 CHECK_EQ(rv, MOJO_RESULT_OK);
27
28 if (zero_initialized)
29 memset(buffer_, 0, capacity);
30 }
31 }
32
MessageBuffer(ScopedMessageHandle message,uint32_t num_bytes)33 MessageBuffer::MessageBuffer(ScopedMessageHandle message, uint32_t num_bytes) {
34 message_ = std::move(message);
35 data_num_bytes_ = num_bytes;
36
37 if (num_bytes == 0) {
38 buffer_ = nullptr;
39 } else {
40 MojoResult rv = GetMessageBuffer(message_.get(), &buffer_);
41 CHECK_EQ(rv, MOJO_RESULT_OK);
42 }
43 }
44
~MessageBuffer()45 MessageBuffer::~MessageBuffer() {}
46
Allocate(size_t delta)47 void* MessageBuffer::Allocate(size_t delta) {
48 delta = internal::Align(delta);
49
50 DCHECK_LE(delta, static_cast<size_t>(data_num_bytes_));
51 DCHECK_GT(bytes_claimed_ + static_cast<uint32_t>(delta), bytes_claimed_);
52
53 uint32_t new_bytes_claimed = bytes_claimed_ + static_cast<uint32_t>(delta);
54 if (new_bytes_claimed > data_num_bytes_) {
55 NOTREACHED();
56 return nullptr;
57 }
58
59 char* start = static_cast<char*>(buffer_) + bytes_claimed_;
60 bytes_claimed_ = new_bytes_claimed;
61 return static_cast<void*>(start);
62 }
63
NotifyBadMessage(const std::string & error)64 void MessageBuffer::NotifyBadMessage(const std::string& error) {
65 DCHECK(message_.is_valid());
66 MojoResult result = mojo::NotifyBadMessage(message_.get(), error);
67 DCHECK_EQ(result, MOJO_RESULT_OK);
68 }
69
70 } // namespace internal
71 } // namespace mojo
72