message.c++ 10.4 KB
Newer Older
1
// Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
Kenton Varda's avatar
Kenton Varda committed
2
// 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 36 37 38
namespace {

class DummyCapTableReader: public _::CapTableReader {
public:
39
#if !CAPNP_LITE
40 41 42
  kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override {
    return nullptr;
  }
43
#endif
44 45 46 47 48
};
static constexpr DummyCapTableReader dummyCapTableReader = DummyCapTableReader();

}  // namespace

49
MessageReader::MessageReader(ReaderOptions options): options(options), allocatedArena(false) {}
50
MessageReader::~MessageReader() noexcept(false) {
51
  if (allocatedArena) {
52
    arena()->~ReaderArena();
53 54 55
  }
}

Matthew Maurer's avatar
Matthew Maurer committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
bool MessageReader::isCanonical() {
  if (!allocatedArena) {
    static_assert(sizeof(_::ReaderArena) <= sizeof(arenaSpace),
        "arenaSpace is too small to hold a ReaderArena.  Please increase it.  This will break "
        "ABI compatibility.");
    new(arena()) _::ReaderArena(this);
    allocatedArena = true;
  }

  _::SegmentReader *segment = arena()->tryGetSegment(_::SegmentId(0));

  if (segment == NULL) {
    // The message has no segments
    return false;
  }

  if (arena()->tryGetSegment(_::SegmentId(1))) {
    // The message has more than one segment
    return false;
  }

  const word* readHead = segment->getStartPtr() + 1;
78 79 80 81 82 83
  bool rootIsCanonical = _::PointerReader::getRoot(segment, nullptr,
                                                   segment->getStartPtr(),
                                                   this->getOptions().nestingLimit)
                                                  .isCanonical(&readHead);
  bool allWordsConsumed = segment->getOffsetTo(readHead) == segment->getSize();
  return rootIsCanonical && allWordsConsumed;
Matthew Maurer's avatar
Matthew Maurer committed
84 85 86
}


87
AnyPointer::Reader MessageReader::getRootInternal() {
88
  if (!allocatedArena) {
89 90
    static_assert(sizeof(_::ReaderArena) <= sizeof(arenaSpace),
        "arenaSpace is too small to hold a ReaderArena.  Please increase it.  This will break "
91
        "ABI compatibility.");
92
    new(arena()) _::ReaderArena(this);
93 94 95
    allocatedArena = true;
  }

96
  _::SegmentReader* segment = arena()->tryGetSegment(_::SegmentId(0));
97 98 99
  KJ_REQUIRE(segment != nullptr &&
             segment->containsInterval(segment->getStartPtr(), segment->getStartPtr() + 1),
             "Message did not contain a root pointer.") {
100
    return AnyPointer::Reader();
101
  }
102

103
  // const_cast here is safe because dummyCapTableReader has no state.
104
  return AnyPointer::Reader(_::PointerReader::getRoot(
105 106
      segment, const_cast<DummyCapTableReader*>(&dummyCapTableReader),
      segment->getStartPtr(), options.nestingLimit));
107 108 109 110 111
}

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

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

113
MessageBuilder::~MessageBuilder() noexcept(false) {
114
  if (allocatedArena) {
115
    kj::dtor(*arena());
116 117 118
  }
}

119 120 121 122 123 124
MessageBuilder::MessageBuilder(kj::ArrayPtr<SegmentInit> segments)
    : allocatedArena(false) {
  kj::ctor(*arena(), this, segments);
  allocatedArena = true;
}

125
_::SegmentBuilder* MessageBuilder::getRootSegment() {
126
  if (allocatedArena) {
127
    return arena()->getSegment(_::SegmentId(0));
128
  } else {
129
    static_assert(sizeof(_::BuilderArena) <= sizeof(arenaSpace),
130 131
        "arenaSpace is too small to hold a BuilderArena.  Please increase it.");
    kj::ctor(*arena(), this);
132
    allocatedArena = true;
133

134 135 136
    auto allocation = arena()->allocate(POINTER_SIZE_IN_WORDS);

    KJ_ASSERT(allocation.segment->getSegmentId() == _::SegmentId(0),
137
        "First allocated word of new arena was not in segment ID 0.");
138
    KJ_ASSERT(allocation.words == allocation.segment->getPtrUnchecked(ZERO * WORDS),
139
        "First allocated word of new arena was not the first word in its segment.");
140
    return allocation.segment;
141
  }
142 143
}

144
AnyPointer::Builder MessageBuilder::getRootInternal() {
145
  _::SegmentBuilder* rootSegment = getRootSegment();
146
  return AnyPointer::Builder(_::PointerBuilder::getRoot(
147
      rootSegment, arena()->getLocalCapTable(), rootSegment->getPtrUnchecked(ZERO * WORDS)));
148 149
}

150
kj::ArrayPtr<const kj::ArrayPtr<const word>> MessageBuilder::getSegmentsForOutput() {
151 152 153 154 155 156 157
  if (allocatedArena) {
    return arena()->getSegmentsForOutput();
  } else {
    return nullptr;
  }
}

158 159 160 161 162
Orphanage MessageBuilder::getOrphanage() {
  // We must ensure that the arena and root pointer have been allocated before the Orphanage
  // can be used.
  if (!allocatedArena) getRootSegment();

163
  return Orphanage(arena(), arena()->getLocalCapTable());
164 165
}

Matthew Maurer's avatar
Matthew Maurer committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179
bool MessageBuilder::isCanonical() {
  _::SegmentReader *segment = getRootSegment();

  if (segment == NULL) {
    // The message has no segments
    return false;
  }

  if (arena()->tryGetSegment(_::SegmentId(1))) {
    // The message has more than one segment
    return false;
  }

  const word* readHead = segment->getStartPtr() + 1;
Matthew Maurer's avatar
Matthew Maurer committed
180
  return _::PointerReader::getRoot(segment, nullptr, segment->getStartPtr(), kj::maxValue)
Matthew Maurer's avatar
Matthew Maurer committed
181 182 183
                                  .isCanonical(&readHead);
}

184 185 186
// =======================================================================================

SegmentArrayMessageReader::SegmentArrayMessageReader(
187
    kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
188
    : MessageReader(options), segments(segments) {}
189

190
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
191

192
kj::ArrayPtr<const word> SegmentArrayMessageReader::getSegment(uint id) {
193 194
  if (id < segments.size()) {
    return segments[id];
Kenton Varda's avatar
Kenton Varda committed
195
  } else {
196
    return nullptr;
Kenton Varda's avatar
Kenton Varda committed
197 198 199
  }
}

200
// -------------------------------------------------------------------
201

202 203 204
struct MallocMessageBuilder::MoreSegments {
  std::vector<void*> segments;
};
205

206 207 208
MallocMessageBuilder::MallocMessageBuilder(
    uint firstSegmentWords, AllocationStrategy allocationStrategy)
    : nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
209
      ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
210 211

MallocMessageBuilder::MallocMessageBuilder(
212
    kj::ArrayPtr<word> firstSegment, AllocationStrategy allocationStrategy)
213
    : nextSize(firstSegment.size()), allocationStrategy(allocationStrategy),
214
      ownFirstSegment(false), returnedFirstSegment(false), firstSegment(firstSegment.begin()) {
215
  KJ_REQUIRE(firstSegment.size() > 0, "First segment size must be non-zero.");
216 217

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

222
MallocMessageBuilder::~MallocMessageBuilder() noexcept(false) {
223 224 225 226 227
  if (returnedFirstSegment) {
    if (ownFirstSegment) {
      free(firstSegment);
    } else {
      // Must zero first segment.
228
      kj::ArrayPtr<const kj::ArrayPtr<const word>> segments = getSegmentsForOutput();
229
      if (segments.size() > 0) {
230
        KJ_ASSERT(segments[0].begin() == firstSegment,
231 232 233
            "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
234
    }
235

236
    KJ_IF_MAYBE(s, moreSegments) {
237
      for (void* ptr: s->get()->segments) {
238 239
        free(ptr);
      }
240 241
    }
  }
242
}
Kenton Varda's avatar
Kenton Varda committed
243

244
kj::ArrayPtr<word> MallocMessageBuilder::allocateSegment(uint minimumSize) {
245 246
  KJ_REQUIRE(minimumSize <= MAX_SEGMENT_WORDS, "MallocMessageBuilder asked to allocate segment above maximum serializable size.");

247
  if (!returnedFirstSegment && !ownFirstSegment) {
248
    kj::ArrayPtr<word> result = kj::arrayPtr(reinterpret_cast<word*>(firstSegment), nextSize);
249
    if (result.size() >= minimumSize) {
250
      returnedFirstSegment = true;
251 252 253 254 255
      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.
256
    ownFirstSegment = true;
257 258
  }

259
  uint size = kj::max(minimumSize, kj::min(MAX_SEGMENT_WORDS, nextSize));
Kenton Varda's avatar
Kenton Varda committed
260

261 262
  void* result = calloc(size, sizeof(word));
  if (result == nullptr) {
263
    KJ_FAIL_SYSCALL("calloc(size, sizeof(word))", ENOMEM, size);
264
  }
Kenton Varda's avatar
Kenton Varda committed
265

266
  if (!returnedFirstSegment) {
267
    firstSegment = result;
268 269 270
    returnedFirstSegment = true;

    // After the first segment, we want nextSize to equal the total size allocated so far.
271 272
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize = size;
  } else {
273 274
    MoreSegments* segments;
    KJ_IF_MAYBE(s, moreSegments) {
275
      segments = *s;
276 277 278 279
    } else {
      auto newSegments = kj::heap<MoreSegments>();
      segments = newSegments;
      moreSegments = mv(newSegments);
280
    }
281
    segments->segments.push_back(result);
282 283
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize += size;
  }
Kenton Varda's avatar
Kenton Varda committed
284

285
  return kj::arrayPtr(reinterpret_cast<word*>(result), size);
Kenton Varda's avatar
Kenton Varda committed
286 287
}

288 289
// -------------------------------------------------------------------

290
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
291
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
292 293

void FlatMessageBuilder::requireFilled() {
294
  KJ_REQUIRE(getSegmentsForOutput()[0].end() == array.end(),
295 296 297
          "FlatMessageBuilder's buffer was too large.");
}

298
kj::ArrayPtr<word> FlatMessageBuilder::allocateSegment(uint minimumSize) {
299
  KJ_REQUIRE(!allocated, "FlatMessageBuilder's buffer was not large enough.");
300 301 302 303
  allocated = true;
  return array;
}

304
}  // namespace capnp