- add sources.
[platform/framework/web/crosswalk.git] / src / mojo / system / message_in_transit.cc
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/system/message_in_transit.h"
6
7 #include <stdlib.h>
8 #include <string.h>
9
10 #include <new>
11
12 #include "base/basictypes.h"
13 #include "base/logging.h"
14 #include "build/build_config.h"
15 #include "mojo/system/limits.h"
16
17 namespace mojo {
18 namespace system {
19
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);
25
26 COMPILE_ASSERT(sizeof(MessageInTransit) %
27                    MessageInTransit::kMessageAlignment == 0,
28                sizeof_MessageInTransit_not_a_multiple_of_alignment);
29
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;
34 #endif
35
36 // static
37 MessageInTransit* MessageInTransit::Create(const void* bytes,
38                                            uint32_t num_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);
42
43   char* buffer = static_cast<char*>(malloc(size_with_header_and_padding));
44   DCHECK_EQ(reinterpret_cast<size_t>(buffer) %
45                 MessageInTransit::kMessageAlignment, 0u);
46
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);
53   return rv;
54 }
55
56 }  // namespace system
57 }  // namespace mojo