message.c++ 8.44 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

Kenton Varda's avatar
Kenton Varda committed
22
#define CAPNP_PRIVATE
Kenton Varda's avatar
Kenton Varda committed
23
#include "message.h"
Kenton Varda's avatar
Kenton Varda committed
24
#include <kj/debug.h>
25
#include "arena.h"
Kenton Varda's avatar
Kenton Varda committed
26
#include "orphan.h"
27
#include <stdlib.h>
28 29
#include <exception>
#include <string>
30
#include <vector>
31
#include <errno.h>
32

33
namespace capnp {
34

35
MessageReader::MessageReader(ReaderOptions options): options(options), allocatedArena(false) {}
36
MessageReader::~MessageReader() noexcept(false) {
37
  if (allocatedArena) {
38
    arena()->~ReaderArena();
39 40 41
  }
}

42
AnyPointer::Reader MessageReader::getRootInternal() {
43
  if (!allocatedArena) {
44 45
    static_assert(sizeof(_::ReaderArena) <= sizeof(arenaSpace),
        "arenaSpace is too small to hold a ReaderArena.  Please increase it.  This will break "
46
        "ABI compatibility.");
47
    new(arena()) _::ReaderArena(this);
48 49 50
    allocatedArena = true;
  }

51
  _::SegmentReader* segment = arena()->tryGetSegment(_::SegmentId(0));
52 53 54
  KJ_REQUIRE(segment != nullptr &&
             segment->containsInterval(segment->getStartPtr(), segment->getStartPtr() + 1),
             "Message did not contain a root pointer.") {
55
    return AnyPointer::Reader();
56
  }
57

58
  return AnyPointer::Reader(_::PointerReader::getRoot(
Kenton Varda's avatar
Kenton Varda committed
59
      segment, segment->getStartPtr(), options.nestingLimit));
60 61 62 63 64
}

// -------------------------------------------------------------------

MessageBuilder::MessageBuilder(): allocatedArena(false) {}
65

66
MessageBuilder::~MessageBuilder() noexcept(false) {
67
  if (allocatedArena) {
68
    kj::dtor(*arena());
69 70 71
  }
}

72 73 74 75 76 77
MessageBuilder::MessageBuilder(kj::ArrayPtr<SegmentInit> segments)
    : allocatedArena(false) {
  kj::ctor(*arena(), this, segments);
  allocatedArena = true;
}

78
_::SegmentBuilder* MessageBuilder::getRootSegment() {
79
  if (allocatedArena) {
80
    return arena()->getSegment(_::SegmentId(0));
81
  } else {
82
    static_assert(sizeof(_::BuilderArena) <= sizeof(arenaSpace),
83 84
        "arenaSpace is too small to hold a BuilderArena.  Please increase it.");
    kj::ctor(*arena(), this);
85
    allocatedArena = true;
86

87 88 89
    auto allocation = arena()->allocate(POINTER_SIZE_IN_WORDS);

    KJ_ASSERT(allocation.segment->getSegmentId() == _::SegmentId(0),
90
        "First allocated word of new arena was not in segment ID 0.");
91
    KJ_ASSERT(allocation.words == allocation.segment->getPtrUnchecked(0 * WORDS),
92
        "First allocated word of new arena was not the first word in its segment.");
93
    return allocation.segment;
94
  }
95 96
}

97
AnyPointer::Builder MessageBuilder::getRootInternal() {
98
  _::SegmentBuilder* rootSegment = getRootSegment();
99
  return AnyPointer::Builder(_::PointerBuilder::getRoot(
Kenton Varda's avatar
Kenton Varda committed
100
      rootSegment, rootSegment->getPtrUnchecked(0 * WORDS)));
101 102
}

103
kj::ArrayPtr<const kj::ArrayPtr<const word>> MessageBuilder::getSegmentsForOutput() {
104 105 106 107 108 109 110
  if (allocatedArena) {
    return arena()->getSegmentsForOutput();
  } else {
    return nullptr;
  }
}

111
#if !CAPNP_LITE
112 113 114 115 116 117 118
kj::ArrayPtr<kj::Maybe<kj::Own<ClientHook>>> MessageBuilder::getCapTable() {
  if (allocatedArena) {
    return arena()->getCapTable();
  } else {
    return nullptr;
  }
}
119
#endif  // !CAPNP_LITE
120

121 122 123 124 125 126 127 128
Orphanage MessageBuilder::getOrphanage() {
  // We must ensure that the arena and root pointer have been allocated before the Orphanage
  // can be used.
  if (!allocatedArena) getRootSegment();

  return Orphanage(arena());
}

129 130 131
// =======================================================================================

SegmentArrayMessageReader::SegmentArrayMessageReader(
132
    kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
133
    : MessageReader(options), segments(segments) {}
134

135
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
136

137
kj::ArrayPtr<const word> SegmentArrayMessageReader::getSegment(uint id) {
138 139
  if (id < segments.size()) {
    return segments[id];
Kenton Varda's avatar
Kenton Varda committed
140
  } else {
141
    return nullptr;
Kenton Varda's avatar
Kenton Varda committed
142 143 144
  }
}

145
// -------------------------------------------------------------------
146

147 148 149
struct MallocMessageBuilder::MoreSegments {
  std::vector<void*> segments;
};
150

151 152 153
MallocMessageBuilder::MallocMessageBuilder(
    uint firstSegmentWords, AllocationStrategy allocationStrategy)
    : nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
154
      ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
155 156

MallocMessageBuilder::MallocMessageBuilder(
157
    kj::ArrayPtr<word> firstSegment, AllocationStrategy allocationStrategy)
158
    : nextSize(firstSegment.size()), allocationStrategy(allocationStrategy),
159
      ownFirstSegment(false), returnedFirstSegment(false), firstSegment(firstSegment.begin()) {
160
  KJ_REQUIRE(firstSegment.size() > 0, "First segment size must be non-zero.");
161 162

  // Checking just the first word should catch most cases of failing to zero the segment.
163
  KJ_REQUIRE(*reinterpret_cast<uint64_t*>(firstSegment.begin()) == 0,
164
          "First segment must be zeroed.");
165
}
166

167
MallocMessageBuilder::~MallocMessageBuilder() noexcept(false) {
168 169 170 171 172
  if (returnedFirstSegment) {
    if (ownFirstSegment) {
      free(firstSegment);
    } else {
      // Must zero first segment.
173
      kj::ArrayPtr<const kj::ArrayPtr<const word>> segments = getSegmentsForOutput();
174
      if (segments.size() > 0) {
175
        KJ_ASSERT(segments[0].begin() == firstSegment,
176 177 178
            "First segment in getSegmentsForOutput() is not the first segment allocated?");
        memset(firstSegment, 0, segments[0].size() * sizeof(word));
      }
Kenton Varda's avatar
Kenton Varda committed
179
    }
180

181
    KJ_IF_MAYBE(s, moreSegments) {
182
      for (void* ptr: s->get()->segments) {
183 184
        free(ptr);
      }
185 186
    }
  }
187
}
Kenton Varda's avatar
Kenton Varda committed
188

189
kj::ArrayPtr<word> MallocMessageBuilder::allocateSegment(uint minimumSize) {
190
  if (!returnedFirstSegment && !ownFirstSegment) {
191
    kj::ArrayPtr<word> result = kj::arrayPtr(reinterpret_cast<word*>(firstSegment), nextSize);
192
    if (result.size() >= minimumSize) {
193
      returnedFirstSegment = true;
194 195 196 197 198
      return result;
    }
    // If the provided first segment wasn't big enough, we discard it and proceed to allocate
    // our own.  This never happens in practice since minimumSize is always 1 for the first
    // segment.
199
    ownFirstSegment = true;
200 201
  }

202
  uint size = kj::max(minimumSize, nextSize);
Kenton Varda's avatar
Kenton Varda committed
203

204 205
  void* result = calloc(size, sizeof(word));
  if (result == nullptr) {
206
    KJ_FAIL_SYSCALL("calloc(size, sizeof(word))", ENOMEM, size);
207
  }
Kenton Varda's avatar
Kenton Varda committed
208

209
  if (!returnedFirstSegment) {
210
    firstSegment = result;
211 212 213
    returnedFirstSegment = true;

    // After the first segment, we want nextSize to equal the total size allocated so far.
214 215
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize = size;
  } else {
216 217
    MoreSegments* segments;
    KJ_IF_MAYBE(s, moreSegments) {
218
      segments = *s;
219 220 221 222
    } else {
      auto newSegments = kj::heap<MoreSegments>();
      segments = newSegments;
      moreSegments = mv(newSegments);
223
    }
224
    segments->segments.push_back(result);
225 226
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize += size;
  }
Kenton Varda's avatar
Kenton Varda committed
227

228
  return kj::arrayPtr(reinterpret_cast<word*>(result), size);
Kenton Varda's avatar
Kenton Varda committed
229 230
}

231 232
// -------------------------------------------------------------------

233
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
234
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
235 236

void FlatMessageBuilder::requireFilled() {
237
  KJ_REQUIRE(getSegmentsForOutput()[0].end() == array.end(),
238 239 240
          "FlatMessageBuilder's buffer was too large.");
}

241
kj::ArrayPtr<word> FlatMessageBuilder::allocateSegment(uint minimumSize) {
242
  KJ_REQUIRE(!allocated, "FlatMessageBuilder's buffer was not large enough.");
243 244 245 246
  allocated = true;
  return array;
}

247
}  // namespace capnp