arena.h 17.4 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// 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 23
#ifndef CAPNP_ARENA_H_
#define CAPNP_ARENA_H_
24

25
#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
26 27 28
#pragma GCC system_header
#endif

Kenton Varda's avatar
Kenton Varda committed
29
#ifndef CAPNP_PRIVATE
30 31
#error "This header is only meant to be included by Cap'n Proto's own source code."
#endif
32

Kenton Varda's avatar
Kenton Varda committed
33
#include <kj/common.h>
34
#include <kj/mutex.h>
35
#include <kj/exception.h>
36
#include <kj/vector.h>
37
#include "common.h"
38
#include "message.h"
39
#include "layout.h"
40
#include <unordered_map>
41 42

#if !CAPNP_LITE
43
#include "capability.h"
44
#endif  // !CAPNP_LITE
45

46
namespace capnp {
47

48
#if !CAPNP_LITE
49
class ClientHook;
50
#endif  // !CAPNP_LITE
51

52
namespace _ {  // private
53 54 55 56 57 58 59

class SegmentReader;
class SegmentBuilder;
class Arena;
class BuilderArena;
class ReadLimiter;

Kenton Varda's avatar
Kenton Varda committed
60
class Segment;
61
typedef kj::Id<uint32_t, Segment> SegmentId;
Kenton Varda's avatar
Kenton Varda committed
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76
class ReadLimiter {
  // Used to keep track of how much data has been processed from a message, and cut off further
  // processing if and when a particular limit is reached.  This is primarily intended to guard
  // against maliciously-crafted messages which contain cycles or overlapping structures.  Cycles
  // and overlapping are not permitted by the Cap'n Proto format because in many cases they could
  // be used to craft a deceptively small message which could consume excessive server resources to
  // process, perhaps even sending it into an infinite loop.  Actually detecting overlaps would be
  // time-consuming, so instead we just keep track of how many words worth of data structures the
  // receiver has actually dereferenced and error out if this gets too high.
  //
  // This counting takes place as you call getters (for non-primitive values) on the message
  // readers.  If you call the same getter twice, the data it returns may be double-counted.  This
  // should not be a big deal in most cases -- just set the read limit high enough that it will
  // only trigger in unreasonable cases.
77 78 79 80
  //
  // This class is "safe" to use from multiple threads for its intended use case.  Threads may
  // overwrite each others' changes to the counter, but this is OK because it only means that the
  // limit is enforced a bit less strictly -- it will still kick in eventually.
81 82 83 84 85

public:
  inline explicit ReadLimiter();                     // No limit.
  inline explicit ReadLimiter(WordCount64 limit);    // Limit to the given number of words.

86 87
  inline void reset(WordCount64 limit);

88
  KJ_ALWAYS_INLINE(bool canRead(WordCount amount, Arena* arena));
89

90 91 92 93
  void unread(WordCount64 amount);
  // Adds back some words to the limit.  Useful when the caller knows they are double-reading
  // some data.

94
private:
95 96 97 98
  volatile uint64_t limit;
  // Current limit, decremented each time catRead() is called.  Volatile because multiple threads
  // could be trying to modify it at once.  (This is not real thread-safety, but good enough for
  // the purpose of this class.  See class comment.)
99

100
  KJ_DISALLOW_COPY(ReadLimiter);
101 102
};

103
#if !CAPNP_LITE
104 105 106 107 108 109
class BrokenCapFactory {
  // Callback for constructing broken caps.  We use this so that we can avoid arena.c++ having a
  // link-time dependency on capability code that lives in libcapnp-rpc.

public:
  virtual kj::Own<ClientHook> newBrokenCap(kj::StringPtr description) = 0;
110
  virtual kj::Own<ClientHook> newNullCap() = 0;
111
};
112
#endif  // !CAPNP_LITE
113

114 115
class SegmentReader {
public:
116
  inline SegmentReader(Arena* arena, SegmentId id, kj::ArrayPtr<const word> ptr,
117 118
                       ReadLimiter* readLimiter);

119
  KJ_ALWAYS_INLINE(bool containsInterval(const void* from, const void* to));
120

121 122 123 124 125
  KJ_ALWAYS_INLINE(bool amplifiedRead(WordCount virtualAmount));
  // Indicates that the reader should pretend that `virtualAmount` additional data was read even
  // though no actual pointer was traversed. This is used e.g. when reading a struct list pointer
  // where the element sizes are zero -- the sender could set the list size arbitrarily high and
  // cause the receiver to iterate over this list even though the message itself is small, so we
Andrew Murray's avatar
Andrew Murray committed
126
  // need to defend against DoS attacks based on this.
127

128 129 130 131 132 133 134
  inline Arena* getArena();
  inline SegmentId getSegmentId();

  inline const word* getStartPtr();
  inline WordCount getOffsetTo(const word* ptr);
  inline WordCount getSize();

135
  inline kj::ArrayPtr<const word> getArray();
136

137 138 139
  inline void unread(WordCount64 amount);
  // Add back some words to the ReadLimiter.

140 141 142
private:
  Arena* arena;
  SegmentId id;
143
  kj::ArrayPtr<const word> ptr;
144 145
  ReadLimiter* readLimiter;

146
  KJ_DISALLOW_COPY(SegmentReader);
147 148 149 150 151 152

  friend class SegmentBuilder;
};

class SegmentBuilder: public SegmentReader {
public:
153
  inline SegmentBuilder(BuilderArena* arena, SegmentId id, kj::ArrayPtr<word> ptr,
154
                        ReadLimiter* readLimiter, size_t wordsUsed = 0);
155 156 157 158
  inline SegmentBuilder(BuilderArena* arena, SegmentId id, kj::ArrayPtr<const word> ptr,
                        ReadLimiter* readLimiter);
  inline SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr),
                        ReadLimiter* readLimiter);
159

160
  KJ_ALWAYS_INLINE(word* allocate(WordCount amount));
161 162 163 164 165 166 167

  KJ_ALWAYS_INLINE(void checkWritable());
  // Throw an exception if the segment is read-only (meaning it is a reference to external data).

  KJ_ALWAYS_INLINE(word* getPtrUnchecked(WordCount offset));
  // Get a writable pointer into the segment.  Throws an exception if the segment is read-only (i.e.
  // a reference to external immutable data).
168 169 170

  inline BuilderArena* getArena();

171
  inline kj::ArrayPtr<const word> currentlyAllocated();
172

173 174
  inline void reset();

175 176
  inline bool isWritable() { return !readOnly; }

177 178 179 180
  inline void tryTruncate(word* from, word* to);
  // If `from` points just past the current end of the segment, then move the end back to `to`.
  // Otherwise, do nothing.

181 182 183 184 185
  inline bool tryExtend(word* from, word* to);
  // If `from` points just past the current end of the segment, and `to` is within the segment
  // boundaries, then move the end up to `to` and return true. Otherwise, do nothing and return
  // false.

186
private:
187
  word* pos;
188
  // Pointer to a pointer to the current end point of the segment, i.e. the location where the
189
  // next object should be allocated.
190

191 192 193 194
  bool readOnly;

  void throwNotWritable();

195
  KJ_DISALLOW_COPY(SegmentBuilder);
196 197
};

198 199
class Arena {
public:
200
  virtual ~Arena() noexcept(false);
201 202 203 204 205

  virtual SegmentReader* tryGetSegment(SegmentId id) = 0;
  // Gets the segment with the given ID, or return nullptr if no such segment exists.

  virtual void reportReadLimitReached() = 0;
206
  // Called to report that the read limit has been reached.  See ReadLimiter, below.  This invokes
207
  // the VALIDATE_INPUT() macro which may throw an exception; if it returns normally, the caller
208
  // will need to continue with default values.
209 210
};

211
class ReaderArena final: public Arena {
212
public:
213 214 215 216
  ReaderArena(MessageReader* message);
  ~ReaderArena() noexcept(false);
  KJ_DISALLOW_COPY(ReaderArena);

217 218 219 220 221
  // implements Arena ------------------------------------------------
  SegmentReader* tryGetSegment(SegmentId id) override;
  void reportReadLimitReached() override;

private:
222
  MessageReader* message;
223
  ReadLimiter readLimiter;
224 225 226 227

  // Optimize for single-segment messages so that small messages are handled quickly.
  SegmentReader segment0;

228
  typedef std::unordered_map<uint, kj::Own<SegmentReader>> SegmentMap;
229
  kj::MutexGuarded<kj::Maybe<kj::Own<SegmentMap>>> moreSegments;
230 231 232 233 234 235 236
  // We need to mutex-guard the segment map because we lazily initialize segments when they are
  // first requested, but a Reader is allowed to be used concurrently in multiple threads.  Luckily
  // this only applies to large messages.
  //
  // TODO(perf):  Thread-local thing instead?  Some kind of lockless map?  Or do sharing of data
  //   in a different way, where you have to construct a new MessageReader in each thread (but
  //   possibly backed by the same data)?
237 238
};

239 240
class BuilderArena final: public Arena {
  // A BuilderArena that does not allow the injection of capabilities.
241

242
public:
243 244
  explicit BuilderArena(MessageBuilder* message);
  BuilderArena(MessageBuilder* message, kj::ArrayPtr<MessageBuilder::SegmentInit> segments);
245 246
  ~BuilderArena() noexcept(false);
  KJ_DISALLOW_COPY(BuilderArena);
247

248
  inline SegmentBuilder* getRootSegment() { return &segment0; }
249

250 251 252 253
  kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
  // Get an array of all the segments, suitable for writing out.  This only returns the allocated
  // portion of each segment, whereas tryGetSegment() returns something that includes
  // not-yet-allocated space.
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
  inline CapTableBuilder* getLocalCapTable() {
    // Return a CapTableBuilder that merely implements local loopback. That is, you can set
    // capabilities, then read the same capabilities back, but there is no intent ever to transmit
    // these capabilities. A MessageBuilder that isn't imbued with some other CapTable uses this
    // by default.
    //
    // TODO(cleanup): It's sort of a hack that this exists. In theory, perhaps, unimbued
    //   MessageBuilders should throw exceptions on any attempt to access capability fields, like
    //   unimbued MessageReaders do. However, lots of code exists which uses MallocMessageBuilder
    //   as a temporary holder for data to be copied in and out (without being serialized), and it
    //   is expected that such data can include capabilities, which is admittedly reasonable.
    //   Therefore, all MessageBuilders must have a cap table by default. Arguably we should
    //   deprecate this usage and instead define a new helper type for this exact purpose.

    return &localCapTable;
  }
271

272
  SegmentBuilder* getSegment(SegmentId id);
273 274
  // Get the segment with the given id.  Crashes or throws an exception if no such segment exists.

275 276 277 278 279
  struct AllocateResult {
    SegmentBuilder* segment;
    word* words;
  };

280
  AllocateResult allocate(WordCount amount);
281 282 283 284
  // Find a segment with at least the given amount of space available and allocate the space.
  // Note that allocating directly from a particular segment is much faster, but allocating from
  // the arena is guaranteed to succeed.  Therefore callers should try to allocate from a specific
  // segment first if there is one, then fall back to the arena.
285

286 287 288 289 290 291 292 293 294 295 296
  SegmentBuilder* addExternalSegment(kj::ArrayPtr<const word> content);
  // Add a new segment to the arena which points to some existing memory region.  The segment is
  // assumed to be completley full; the arena will never allocate from it.  In fact, the segment
  // is considered read-only.  Any attempt to get a Builder pointing into this segment will throw
  // an exception.  Readers are allowed, however.
  //
  // This can be used to inject some external data into a message without a copy, e.g. embedding a
  // large mmap'd file into a message as `Data` without forcing that data to actually be read in
  // from disk (until the message itself is written out).  `Orphanage` provides the public API for
  // this feature.

297 298 299 300 301
  // implements Arena ------------------------------------------------
  SegmentReader* tryGetSegment(SegmentId id) override;
  void reportReadLimitReached() override;

private:
302
  MessageBuilder* message;
303
  ReadLimiter dummyLimiter;
304 305

  class LocalCapTable: public CapTableBuilder {
306
#if !CAPNP_LITE
307 308 309 310 311 312 313
  public:
    kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override;
    uint injectCap(kj::Own<ClientHook>&& cap) override;
    void dropCap(uint index) override;

  private:
    kj::Vector<kj::Maybe<kj::Own<ClientHook>>> capTable;
314
#endif // ! CAPNP_LITE
315 316 317
  };

  LocalCapTable localCapTable;
318

319
  SegmentBuilder segment0;
320
  kj::ArrayPtr<const word> segment0ForOutput;
321

322
  struct MultiSegmentState {
323
    kj::Vector<kj::Own<SegmentBuilder>> builders;
324
    kj::Vector<kj::ArrayPtr<const word>> forOutput;
325
  };
326
  kj::Maybe<kj::Own<MultiSegmentState>> moreSegments;
327 328 329 330 331 332 333 334

  SegmentBuilder* segmentWithSpace = nullptr;
  // When allocating, look for space in this segment first before resorting to allocating a new
  // segment.  This is not necessarily the last segment because addExternalSegment() may add a
  // segment that is already-full, in which case we don't update this pointer.

  template <typename T>  // Can be `word` or `const word`.
  SegmentBuilder* addSegmentInternal(kj::ArrayPtr<T> content);
335 336 337 338 339
};

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

inline ReadLimiter::ReadLimiter()
340
    : limit(kj::maxValue) {}
341

342
inline ReadLimiter::ReadLimiter(WordCount64 limit): limit(limit / WORDS) {}
343

344
inline void ReadLimiter::reset(WordCount64 limit) { this->limit = limit / WORDS; }
345

346
inline bool ReadLimiter::canRead(WordCount amount, Arena* arena) {
347 348 349 350
  // Be careful not to store an underflowed value into `limit`, even if multiple threads are
  // decrementing it.
  uint64_t current = limit;
  if (KJ_UNLIKELY(amount / WORDS > current)) {
351 352 353
    arena->reportReadLimitReached();
    return false;
  } else {
354
    limit = current - amount / WORDS;
355 356 357 358 359 360
    return true;
  }
}

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

361
inline SegmentReader::SegmentReader(Arena* arena, SegmentId id, kj::ArrayPtr<const word> ptr,
362 363 364
                                    ReadLimiter* readLimiter)
    : arena(arena), id(id), ptr(ptr), readLimiter(readLimiter) {}

365
inline bool SegmentReader::containsInterval(const void* from, const void* to) {
366
  return from >= this->ptr.begin() && to <= this->ptr.end() && from <= to &&
367 368 369 370
      readLimiter->canRead(
          intervalLength(reinterpret_cast<const byte*>(from),
                         reinterpret_cast<const byte*>(to)) / BYTES_PER_WORD,
          arena);
371 372
}

373 374 375 376
inline bool SegmentReader::amplifiedRead(WordCount virtualAmount) {
  return readLimiter->canRead(virtualAmount, arena);
}

377 378 379 380 381 382 383
inline Arena* SegmentReader::getArena() { return arena; }
inline SegmentId SegmentReader::getSegmentId() { return id; }
inline const word* SegmentReader::getStartPtr() { return ptr.begin(); }
inline WordCount SegmentReader::getOffsetTo(const word* ptr) {
  return intervalLength(this->ptr.begin(), ptr);
}
inline WordCount SegmentReader::getSize() { return ptr.size() * WORDS; }
384
inline kj::ArrayPtr<const word> SegmentReader::getArray() { return ptr; }
385
inline void SegmentReader::unread(WordCount64 amount) { readLimiter->unread(amount); }
386 387 388 389

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

inline SegmentBuilder::SegmentBuilder(
390 391 392
    BuilderArena* arena, SegmentId id, kj::ArrayPtr<word> ptr, ReadLimiter* readLimiter,
    size_t wordsUsed)
    : SegmentReader(arena, id, ptr, readLimiter), pos(ptr.begin() + wordsUsed), readOnly(false) {}
393 394 395 396 397 398 399 400 401 402
inline SegmentBuilder::SegmentBuilder(
    BuilderArena* arena, SegmentId id, kj::ArrayPtr<const word> ptr, ReadLimiter* readLimiter)
    : SegmentReader(arena, id, ptr, readLimiter),
      // const_cast is safe here because the member won't ever be dereferenced because it appears
      // to point to the end of the segment anyway.
      pos(const_cast<word*>(ptr.end())),
      readOnly(true) {}
inline SegmentBuilder::SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr),
                                      ReadLimiter* readLimiter)
    : SegmentReader(arena, id, nullptr, readLimiter), pos(nullptr), readOnly(false) {}
403 404

inline word* SegmentBuilder::allocate(WordCount amount) {
405
  if (intervalLength(pos, ptr.end()) < amount) {
406
    // Not enough space in the segment for this allocation.
407 408
    return nullptr;
  } else {
409
    // Success.
410 411
    word* result = pos;
    pos = pos + amount;
412 413 414 415
    return result;
  }
}

416 417 418 419
inline void SegmentBuilder::checkWritable() {
  if (KJ_UNLIKELY(readOnly)) throwNotWritable();
}

420 421 422 423 424 425 426 427 428 429
inline word* SegmentBuilder::getPtrUnchecked(WordCount offset) {
  return const_cast<word*>(ptr.begin() + offset);
}

inline BuilderArena* SegmentBuilder::getArena() {
  // Down-cast safe because SegmentBuilder's constructor always initializes its SegmentReader base
  // class with an Arena pointer that actually points to a BuilderArena.
  return static_cast<BuilderArena*>(arena);
}

430
inline kj::ArrayPtr<const word> SegmentBuilder::currentlyAllocated() {
431
  return kj::arrayPtr(ptr.begin(), pos - ptr.begin());
432 433
}

434 435
inline void SegmentBuilder::reset() {
  word* start = getPtrUnchecked(0 * WORDS);
436 437
  memset(start, 0, (pos - start) * sizeof(word));
  pos = start;
438 439
}

440 441 442 443
inline void SegmentBuilder::tryTruncate(word* from, word* to) {
  if (pos == from) pos = to;
}

444 445 446 447 448 449 450 451 452 453
inline bool SegmentBuilder::tryExtend(word* from, word* to) {
  // Careful about overflow.
  if (pos == from && to <= ptr.end() && to >= from) {
    pos = to;
    return true;
  } else {
    return false;
  }
}

454
}  // namespace _ (private)
455
}  // namespace capnp
456

Kenton Varda's avatar
Kenton Varda committed
457
#endif  // CAPNP_ARENA_H_