message.c++ 8.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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

36
namespace capnp {
37

38
MessageReader::MessageReader(ReaderOptions options): options(options), allocatedArena(false) {}
39
MessageReader::~MessageReader() noexcept(false) {
40 41 42 43 44
  if (allocatedArena) {
    arena()->~ReaderArena();
  }
}

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

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

61
  return _::StructReader::readRoot(segment->getStartPtr(), segment, options.nestingLimit);
62 63 64 65 66
}

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

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

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

82 83 84
    auto allocation = arena()->allocate(POINTER_SIZE_IN_WORDS);

    KJ_ASSERT(allocation.segment->getSegmentId() == _::SegmentId(0),
85
        "First allocated word of new arena was not in segment ID 0.");
86
    KJ_ASSERT(allocation.words == allocation.segment->getPtrUnchecked(0 * WORDS),
87
        "First allocated word of new arena was not the first word in its segment.");
88
    return allocation.segment;
89
  }
90 91
}

92 93 94
_::StructBuilder MessageBuilder::initRoot(_::StructSize size) {
  _::SegmentBuilder* rootSegment = getRootSegment();
  return _::StructBuilder::initRoot(
95
      rootSegment, rootSegment->getPtrUnchecked(0 * WORDS), size);
96 97
}

98 99 100
void MessageBuilder::setRootInternal(_::StructReader reader) {
  _::SegmentBuilder* rootSegment = getRootSegment();
  _::StructBuilder::setRoot(
101 102 103
      rootSegment, rootSegment->getPtrUnchecked(0 * WORDS), reader);
}

104 105 106
_::StructBuilder MessageBuilder::getRoot(_::StructSize size) {
  _::SegmentBuilder* rootSegment = getRootSegment();
  return _::StructBuilder::getRoot(
107
      rootSegment, rootSegment->getPtrUnchecked(0 * WORDS), size);
108 109
}

110
kj::ArrayPtr<const kj::ArrayPtr<const word>> MessageBuilder::getSegmentsForOutput() {
111 112 113 114 115 116 117
  if (allocatedArena) {
    return arena()->getSegmentsForOutput();
  } else {
    return nullptr;
  }
}

118 119 120 121 122 123 124 125
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());
}

126 127 128
// =======================================================================================

SegmentArrayMessageReader::SegmentArrayMessageReader(
129
    kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
130
    : MessageReader(options), segments(segments) {}
131

132
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
133

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

142
// -------------------------------------------------------------------
143

144 145 146
struct MallocMessageBuilder::MoreSegments {
  std::vector<void*> segments;
};
147

148 149 150
MallocMessageBuilder::MallocMessageBuilder(
    uint firstSegmentWords, AllocationStrategy allocationStrategy)
    : nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
151
      ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
152 153

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

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

164
MallocMessageBuilder::~MallocMessageBuilder() noexcept(false) {
165 166 167 168 169
  if (returnedFirstSegment) {
    if (ownFirstSegment) {
      free(firstSegment);
    } else {
      // Must zero first segment.
170
      kj::ArrayPtr<const kj::ArrayPtr<const word>> segments = getSegmentsForOutput();
171
      if (segments.size() > 0) {
172
        KJ_ASSERT(segments[0].begin() == firstSegment,
173 174 175
            "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
176
    }
177

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

186
kj::ArrayPtr<word> MallocMessageBuilder::allocateSegment(uint minimumSize) {
187
  if (!returnedFirstSegment && !ownFirstSegment) {
188
    kj::ArrayPtr<word> result = kj::arrayPtr(reinterpret_cast<word*>(firstSegment), nextSize);
189
    if (result.size() >= minimumSize) {
190
      returnedFirstSegment = true;
191 192 193 194 195
      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.
196
    ownFirstSegment = true;
197 198
  }

199
  uint size = std::max(minimumSize, nextSize);
Kenton Varda's avatar
Kenton Varda committed
200

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

206
  if (!returnedFirstSegment) {
207
    firstSegment = result;
208 209 210
    returnedFirstSegment = true;

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

225
  return kj::arrayPtr(reinterpret_cast<word*>(result), size);
Kenton Varda's avatar
Kenton Varda committed
226 227
}

228 229
// -------------------------------------------------------------------

230
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
231
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
232 233

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

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

244
}  // namespace capnp