message.c++ 8.32 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
  if (allocatedArena) {
41
    arena()->~BasicReaderArena();
42 43 44
  }
}

Kenton Varda's avatar
Kenton Varda committed
45
ObjectPointer::Reader MessageReader::getRootInternal() {
46
  if (!allocatedArena) {
47 48
    static_assert(sizeof(_::BasicReaderArena) <= sizeof(arenaSpace),
        "arenaSpace is too small to hold a BasicReaderArena.  Please increase it.  This will break "
49
        "ABI compatibility.");
50
    new(arena()) _::BasicReaderArena(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.") {
Kenton Varda's avatar
Kenton Varda committed
58
    return ObjectPointer::Reader();
59
  }
60

Kenton Varda's avatar
Kenton Varda committed
61 62
  return ObjectPointer::Reader(_::PointerReader::getRoot(
      segment, segment->getStartPtr(), options.nestingLimit));
63 64 65 66 67
}

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

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

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

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

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

Kenton Varda's avatar
Kenton Varda committed
93
ObjectPointer::Builder MessageBuilder::getRootInternal() {
94
  _::SegmentBuilder* rootSegment = getRootSegment();
Kenton Varda's avatar
Kenton Varda committed
95 96
  return ObjectPointer::Builder(_::PointerBuilder::getRoot(
      rootSegment, rootSegment->getPtrUnchecked(0 * WORDS)));
97 98
}

99
kj::ArrayPtr<const kj::ArrayPtr<const word>> MessageBuilder::getSegmentsForOutput() {
100 101 102 103 104 105 106
  if (allocatedArena) {
    return arena()->getSegmentsForOutput();
  } else {
    return nullptr;
  }
}

107 108 109 110 111 112 113 114
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());
}

115 116 117
// =======================================================================================

SegmentArrayMessageReader::SegmentArrayMessageReader(
118
    kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
119
    : MessageReader(options), segments(segments) {}
120

121
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
122

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

131
// -------------------------------------------------------------------
132

133 134 135
struct MallocMessageBuilder::MoreSegments {
  std::vector<void*> segments;
};
136

137 138 139
MallocMessageBuilder::MallocMessageBuilder(
    uint firstSegmentWords, AllocationStrategy allocationStrategy)
    : nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
140
      ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
141 142

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

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

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

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

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

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

190 191
  void* result = calloc(size, sizeof(word));
  if (result == nullptr) {
192
    KJ_FAIL_SYSCALL("calloc(size, sizeof(word))", ENOMEM, size);
193
  }
Kenton Varda's avatar
Kenton Varda committed
194

195
  if (!returnedFirstSegment) {
196
    firstSegment = result;
197 198 199
    returnedFirstSegment = true;

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

214
  return kj::arrayPtr(reinterpret_cast<word*>(result), size);
Kenton Varda's avatar
Kenton Varda committed
215 216
}

217 218
// -------------------------------------------------------------------

219
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
220
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
221 222

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

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

233
}  // namespace capnp