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.
5 #include "mojo/system/message_in_transit.h"
12 #include "base/basictypes.h"
13 #include "base/logging.h"
14 #include "build/build_config.h"
15 #include "mojo/system/limits.h"
20 // Avoid dangerous situations, but making sure that the size of the "header" +
21 // the size of the data fits into a 31-bit number.
22 COMPILE_ASSERT(static_cast<uint64_t>(sizeof(MessageInTransit)) +
23 kMaxMessageNumBytes <= 0x7fffffff,
24 kMaxMessageNumBytes_too_big);
26 COMPILE_ASSERT(sizeof(MessageInTransit) %
27 MessageInTransit::kMessageAlignment == 0,
28 sizeof_MessageInTransit_not_a_multiple_of_alignment);
30 // C++ requires that storage be declared (in a single compilation unit), but
31 // MSVS isn't standards-conformant and doesn't handle this correctly.
32 #if !defined(COMPILER_MSVC)
33 const size_t MessageInTransit::kMessageAlignment;
37 MessageInTransit* MessageInTransit::Create(const void* bytes,
39 const size_t size_with_header = sizeof(MessageInTransit) + num_bytes;
40 const size_t size_with_header_and_padding =
41 RoundUpMessageAlignment(size_with_header);
43 char* buffer = static_cast<char*>(malloc(size_with_header_and_padding));
44 DCHECK_EQ(reinterpret_cast<size_t>(buffer) %
45 MessageInTransit::kMessageAlignment, 0u);
47 // The buffer consists of the header (a |MessageInTransit|, constructed using
48 // a placement new), followed by the data, followed by padding (of zeros).
49 MessageInTransit* rv = new (buffer) MessageInTransit(num_bytes);
50 memcpy(buffer + sizeof(MessageInTransit), bytes, num_bytes);
51 memset(buffer + size_with_header, 0,
52 size_with_header_and_padding - size_with_header);