message.c++ 10.3 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
#include <errno.h>
29

30
namespace capnp {
31

32 33 34 35
namespace {

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

}  // namespace

46
MessageReader::MessageReader(ReaderOptions options): options(options), allocatedArena(false) {}
47
MessageReader::~MessageReader() noexcept(false) {
48
  if (allocatedArena) {
49
    arena()->~ReaderArena();
50 51 52
  }
}

Matthew Maurer's avatar
Matthew Maurer committed
53 54 55 56 57
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.");
58
    kj::ctor(*arena(), this);
Matthew Maurer's avatar
Matthew Maurer committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    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;
75 76 77 78 79 80
  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
81 82 83
}


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

93
  _::SegmentReader* segment = arena()->tryGetSegment(_::SegmentId(0));
94
  KJ_REQUIRE(segment != nullptr &&
95
             segment->checkObject(segment->getStartPtr(), ONE * WORDS),
96
             "Message did not contain a root pointer.") {
97
    return AnyPointer::Reader();
98
  }
99

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

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

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

110
MessageBuilder::~MessageBuilder() noexcept(false) {
111
  if (allocatedArena) {
112
    kj::dtor(*arena());
113 114 115
  }
}

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

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

131 132 133
    auto allocation = arena()->allocate(POINTER_SIZE_IN_WORDS);

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

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

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

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

160
  return Orphanage(arena(), arena()->getLocalCapTable());
161 162
}

Matthew Maurer's avatar
Matthew Maurer committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176
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
177
  return _::PointerReader::getRoot(segment, nullptr, segment->getStartPtr(), kj::maxValue)
Matthew Maurer's avatar
Matthew Maurer committed
178 179 180
                                  .isCanonical(&readHead);
}

181 182 183
// =======================================================================================

SegmentArrayMessageReader::SegmentArrayMessageReader(
184
    kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
185
    : MessageReader(options), segments(segments) {}
186

187
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
188

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

197
// -------------------------------------------------------------------
198

199 200 201
MallocMessageBuilder::MallocMessageBuilder(
    uint firstSegmentWords, AllocationStrategy allocationStrategy)
    : nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
202
      ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
203 204

MallocMessageBuilder::MallocMessageBuilder(
205
    kj::ArrayPtr<word> firstSegment, AllocationStrategy allocationStrategy)
206
    : nextSize(firstSegment.size()), allocationStrategy(allocationStrategy),
207
      ownFirstSegment(false), returnedFirstSegment(false), firstSegment(firstSegment.begin()) {
208
  KJ_REQUIRE(firstSegment.size() > 0, "First segment size must be non-zero.");
209 210

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

215
MallocMessageBuilder::~MallocMessageBuilder() noexcept(false) {
216 217 218 219 220
  if (returnedFirstSegment) {
    if (ownFirstSegment) {
      free(firstSegment);
    } else {
      // Must zero first segment.
221
      kj::ArrayPtr<const kj::ArrayPtr<const word>> segments = getSegmentsForOutput();
222
      if (segments.size() > 0) {
223
        KJ_ASSERT(segments[0].begin() == firstSegment,
224 225 226
            "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
227
    }
228

229 230
    for (void* ptr: moreSegments) {
      free(ptr);
231 232
    }
  }
233
}
Kenton Varda's avatar
Kenton Varda committed
234

235
kj::ArrayPtr<word> MallocMessageBuilder::allocateSegment(uint minimumSize) {
236 237 238 239
  KJ_REQUIRE(bounded(minimumSize) * WORDS <= MAX_SEGMENT_WORDS,
      "MallocMessageBuilder asked to allocate segment above maximum serializable size.");
  KJ_ASSERT(bounded(nextSize) * WORDS <= MAX_SEGMENT_WORDS,
      "MallocMessageBuilder nextSize out of bounds.");
240

241
  if (!returnedFirstSegment && !ownFirstSegment) {
242
    kj::ArrayPtr<word> result = kj::arrayPtr(reinterpret_cast<word*>(firstSegment), nextSize);
243
    if (result.size() >= minimumSize) {
244
      returnedFirstSegment = true;
245 246 247 248 249
      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.
250
    ownFirstSegment = true;
251 252
  }

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

255 256
  void* result = calloc(size, sizeof(word));
  if (result == nullptr) {
257
    KJ_FAIL_SYSCALL("calloc(size, sizeof(word))", ENOMEM, size);
258
  }
Kenton Varda's avatar
Kenton Varda committed
259

260
  if (!returnedFirstSegment) {
261
    firstSegment = result;
262 263 264
    returnedFirstSegment = true;

    // After the first segment, we want nextSize to equal the total size allocated so far.
265 266
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize = size;
  } else {
267
    moreSegments.add(result);
268 269 270
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) {
      // set nextSize = min(nextSize+size, MAX_SEGMENT_WORDS)
      // while protecting against possible overflow of (nextSize+size)
271 272
      nextSize = (size <= unbound(MAX_SEGMENT_WORDS / WORDS) - nextSize)
          ? nextSize + size : unbound(MAX_SEGMENT_WORDS / WORDS);
273
    }
274
  }
Kenton Varda's avatar
Kenton Varda committed
275

276
  return kj::arrayPtr(reinterpret_cast<word*>(result), size);
Kenton Varda's avatar
Kenton Varda committed
277 278
}

279 280
// -------------------------------------------------------------------

281
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
282
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
283 284

void FlatMessageBuilder::requireFilled() {
285
  KJ_REQUIRE(getSegmentsForOutput()[0].end() == array.end(),
286 287 288
          "FlatMessageBuilder's buffer was too large.");
}

289
kj::ArrayPtr<word> FlatMessageBuilder::allocateSegment(uint minimumSize) {
290
  KJ_REQUIRE(!allocated, "FlatMessageBuilder's buffer was not large enough.");
291 292 293 294
  allocated = true;
  return array;
}

295
}  // namespace capnp