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

35
namespace capnp {
36

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

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

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

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

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

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

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

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

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

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

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

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

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

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

125 126 127
// =======================================================================================

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

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

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

141
// -------------------------------------------------------------------
142

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

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

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

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

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

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

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

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

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

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

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

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

227 228
// -------------------------------------------------------------------

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

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

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

243
}  // namespace capnp