message.c++ 8.54 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"
28
#include <stdlib.h>
29 30
#include <exception>
#include <string>
31
#include <vector>
32
#include <unistd.h>
33

34
namespace capnp {
35

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

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

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

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

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

MessageBuilder::MessageBuilder(): allocatedArena(false) {}
65
MessageBuilder::~MessageBuilder() noexcept(false) {
66 67 68 69 70
  if (allocatedArena) {
    arena()->~BuilderArena();
  }
}

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

81
    WordCount ptrSize = 1 * POINTERS * WORDS_PER_POINTER;
82 83
    _::SegmentBuilder* segment = arena()->getSegmentWithAvailable(ptrSize);
    KJ_ASSERT(segment->getSegmentId() == _::SegmentId(0),
84
        "First allocated word of new arena was not in segment ID 0.");
85
    word* location = segment->allocate(ptrSize);
86
    KJ_ASSERT(location == segment->getPtrUnchecked(0 * WORDS),
87 88 89
        "First allocated word of new arena was not the first word in its segment.");
    return segment;
  }
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 118 119 120
  if (allocatedArena) {
    return arena()->getSegmentsForOutput();
  } else {
    return nullptr;
  }
}

// =======================================================================================

SegmentArrayMessageReader::SegmentArrayMessageReader(
121
    kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
122
    : MessageReader(options), segments(segments) {}
123

124
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
125

126
kj::ArrayPtr<const word> SegmentArrayMessageReader::getSegment(uint id) {
127 128
  if (id < segments.size()) {
    return segments[id];
Kenton Varda's avatar
Kenton Varda committed
129
  } else {
130
    return nullptr;
Kenton Varda's avatar
Kenton Varda committed
131 132 133
  }
}

134
// -------------------------------------------------------------------
135

136 137 138
struct MallocMessageBuilder::MoreSegments {
  std::vector<void*> segments;
};
139

140 141 142
MallocMessageBuilder::MallocMessageBuilder(
    uint firstSegmentWords, AllocationStrategy allocationStrategy)
    : nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
143
      ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
144 145

MallocMessageBuilder::MallocMessageBuilder(
146
    kj::ArrayPtr<word> firstSegment, AllocationStrategy allocationStrategy)
147
    : nextSize(firstSegment.size()), allocationStrategy(allocationStrategy),
148
      ownFirstSegment(false), returnedFirstSegment(false), firstSegment(firstSegment.begin()) {
149
  KJ_REQUIRE(firstSegment.size() > 0, "First segment size must be non-zero.");
150 151

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

156
MallocMessageBuilder::~MallocMessageBuilder() noexcept(false) {
157 158 159 160 161
  if (returnedFirstSegment) {
    if (ownFirstSegment) {
      free(firstSegment);
    } else {
      // Must zero first segment.
162
      kj::ArrayPtr<const kj::ArrayPtr<const word>> segments = getSegmentsForOutput();
163
      if (segments.size() > 0) {
164
        KJ_ASSERT(segments[0].begin() == firstSegment,
165 166 167
            "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
168
    }
169

170 171
    KJ_IF_MAYBE(s, moreSegments) {
      for (void* ptr: s->segments) {
172 173
        free(ptr);
      }
174 175
    }
  }
176
}
Kenton Varda's avatar
Kenton Varda committed
177

178
kj::ArrayPtr<word> MallocMessageBuilder::allocateSegment(uint minimumSize) {
179
  if (!returnedFirstSegment && !ownFirstSegment) {
180
    kj::ArrayPtr<word> result = kj::arrayPtr(reinterpret_cast<word*>(firstSegment), nextSize);
181
    if (result.size() >= minimumSize) {
182
      returnedFirstSegment = true;
183 184 185 186 187
      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.
188
    ownFirstSegment = true;
189 190
  }

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

193 194
  void* result = calloc(size, sizeof(word));
  if (result == nullptr) {
195
    FAIL_SYSCALL("calloc(size, sizeof(word))", ENOMEM, size);
196
  }
Kenton Varda's avatar
Kenton Varda committed
197

198
  if (!returnedFirstSegment) {
199
    firstSegment = result;
200 201 202
    returnedFirstSegment = true;

    // After the first segment, we want nextSize to equal the total size allocated so far.
203 204
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize = size;
  } else {
205 206 207 208 209 210 211
    MoreSegments* segments;
    KJ_IF_MAYBE(s, moreSegments) {
      segments = s;
    } else {
      auto newSegments = kj::heap<MoreSegments>();
      segments = newSegments;
      moreSegments = mv(newSegments);
212
    }
213
    segments->segments.push_back(result);
214 215
    if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize += size;
  }
Kenton Varda's avatar
Kenton Varda committed
216

217
  return kj::arrayPtr(reinterpret_cast<word*>(result), size);
Kenton Varda's avatar
Kenton Varda committed
218 219
}

220 221
// -------------------------------------------------------------------

222
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
223
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
224 225

void FlatMessageBuilder::requireFilled() {
226
  KJ_REQUIRE(getSegmentsForOutput()[0].end() == array.end(),
227 228 229
          "FlatMessageBuilder's buffer was too large.");
}

230
kj::ArrayPtr<word> FlatMessageBuilder::allocateSegment(uint minimumSize) {
231
  KJ_REQUIRE(!allocated, "FlatMessageBuilder's buffer was not large enough.");
232 233 234 235
  allocated = true;
  return array;
}

236
}  // namespace capnp