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 #include "mojo/public/cpp/bindings/message.h"
6
7 #include <assert.h>
8 #include <stdlib.h>
9
10 #include <algorithm>
11
12 namespace mojo {
13
Message()14 Message::Message()
15 : data_num_bytes_(0),
16 data_(NULL) {
17 }
18
~Message()19 Message::~Message() {
20 free(data_);
21
22 for (std::vector<Handle>::iterator it = handles_.begin();
23 it != handles_.end(); ++it) {
24 if (it->is_valid())
25 CloseRaw(*it);
26 }
27 }
28
AllocUninitializedData(uint32_t num_bytes)29 void Message::AllocUninitializedData(uint32_t num_bytes) {
30 assert(!data_);
31 data_num_bytes_ = num_bytes;
32 data_ = static_cast<internal::MessageData*>(malloc(num_bytes));
33 }
34
AdoptData(uint32_t num_bytes,internal::MessageData * data)35 void Message::AdoptData(uint32_t num_bytes, internal::MessageData* data) {
36 assert(!data_);
37 data_num_bytes_ = num_bytes;
38 data_ = data;
39 }
40
Swap(Message * other)41 void Message::Swap(Message* other) {
42 std::swap(data_num_bytes_, other->data_num_bytes_);
43 std::swap(data_, other->data_);
44 std::swap(handles_, other->handles_);
45 }
46
ReadAndDispatchMessage(MessagePipeHandle handle,MessageReceiver * receiver,bool * receiver_result)47 MojoResult ReadAndDispatchMessage(MessagePipeHandle handle,
48 MessageReceiver* receiver,
49 bool* receiver_result) {
50 MojoResult rv;
51
52 uint32_t num_bytes = 0, num_handles = 0;
53 rv = ReadMessageRaw(handle,
54 NULL,
55 &num_bytes,
56 NULL,
57 &num_handles,
58 MOJO_READ_MESSAGE_FLAG_NONE);
59 if (rv != MOJO_RESULT_RESOURCE_EXHAUSTED)
60 return rv;
61
62 Message message;
63 message.AllocUninitializedData(num_bytes);
64 message.mutable_handles()->resize(num_handles);
65
66 rv = ReadMessageRaw(handle,
67 message.mutable_data(),
68 &num_bytes,
69 message.mutable_handles()->empty()
70 ? NULL
71 : reinterpret_cast<MojoHandle*>(
72 &message.mutable_handles()->front()),
73 &num_handles,
74 MOJO_READ_MESSAGE_FLAG_NONE);
75 if (receiver && rv == MOJO_RESULT_OK)
76 *receiver_result = receiver->Accept(&message);
77
78 return rv;
79 }
80
81 } // namespace mojo
82