cannam@149: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors cannam@149: // Licensed under the MIT License: cannam@149: // cannam@149: // Permission is hereby granted, free of charge, to any person obtaining a copy cannam@149: // of this software and associated documentation files (the "Software"), to deal cannam@149: // in the Software without restriction, including without limitation the rights cannam@149: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cannam@149: // copies of the Software, and to permit persons to whom the Software is cannam@149: // furnished to do so, subject to the following conditions: cannam@149: // cannam@149: // The above copyright notice and this permission notice shall be included in cannam@149: // all copies or substantial portions of the Software. cannam@149: // cannam@149: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR cannam@149: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, cannam@149: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE cannam@149: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER cannam@149: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, cannam@149: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN cannam@149: // THE SOFTWARE. cannam@149: cannam@149: #ifndef CAPNP_ARENA_H_ cannam@149: #define CAPNP_ARENA_H_ cannam@149: cannam@149: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) cannam@149: #pragma GCC system_header cannam@149: #endif cannam@149: cannam@149: #ifndef CAPNP_PRIVATE cannam@149: #error "This header is only meant to be included by Cap'n Proto's own source code." cannam@149: #endif cannam@149: cannam@149: #include cannam@149: #include cannam@149: #include cannam@149: #include cannam@149: #include cannam@149: #include "common.h" cannam@149: #include "message.h" cannam@149: #include "layout.h" cannam@149: #include cannam@149: cannam@149: #if !CAPNP_LITE cannam@149: #include "capability.h" cannam@149: #endif // !CAPNP_LITE cannam@149: cannam@149: namespace capnp { cannam@149: cannam@149: #if !CAPNP_LITE cannam@149: class ClientHook; cannam@149: #endif // !CAPNP_LITE cannam@149: cannam@149: namespace _ { // private cannam@149: cannam@149: class SegmentReader; cannam@149: class SegmentBuilder; cannam@149: class Arena; cannam@149: class BuilderArena; cannam@149: class ReadLimiter; cannam@149: cannam@149: class Segment; cannam@149: typedef kj::Id SegmentId; cannam@149: cannam@149: class ReadLimiter { cannam@149: // Used to keep track of how much data has been processed from a message, and cut off further cannam@149: // processing if and when a particular limit is reached. This is primarily intended to guard cannam@149: // against maliciously-crafted messages which contain cycles or overlapping structures. Cycles cannam@149: // and overlapping are not permitted by the Cap'n Proto format because in many cases they could cannam@149: // be used to craft a deceptively small message which could consume excessive server resources to cannam@149: // process, perhaps even sending it into an infinite loop. Actually detecting overlaps would be cannam@149: // time-consuming, so instead we just keep track of how many words worth of data structures the cannam@149: // receiver has actually dereferenced and error out if this gets too high. cannam@149: // cannam@149: // This counting takes place as you call getters (for non-primitive values) on the message cannam@149: // readers. If you call the same getter twice, the data it returns may be double-counted. This cannam@149: // should not be a big deal in most cases -- just set the read limit high enough that it will cannam@149: // only trigger in unreasonable cases. cannam@149: // cannam@149: // This class is "safe" to use from multiple threads for its intended use case. Threads may cannam@149: // overwrite each others' changes to the counter, but this is OK because it only means that the cannam@149: // limit is enforced a bit less strictly -- it will still kick in eventually. cannam@149: cannam@149: public: cannam@149: inline explicit ReadLimiter(); // No limit. cannam@149: inline explicit ReadLimiter(WordCount64 limit); // Limit to the given number of words. cannam@149: cannam@149: inline void reset(WordCount64 limit); cannam@149: cannam@149: KJ_ALWAYS_INLINE(bool canRead(WordCount64 amount, Arena* arena)); cannam@149: cannam@149: void unread(WordCount64 amount); cannam@149: // Adds back some words to the limit. Useful when the caller knows they are double-reading cannam@149: // some data. cannam@149: cannam@149: private: cannam@149: volatile uint64_t limit; cannam@149: // Current limit, decremented each time catRead() is called. Volatile because multiple threads cannam@149: // could be trying to modify it at once. (This is not real thread-safety, but good enough for cannam@149: // the purpose of this class. See class comment.) cannam@149: cannam@149: KJ_DISALLOW_COPY(ReadLimiter); cannam@149: }; cannam@149: cannam@149: #if !CAPNP_LITE cannam@149: class BrokenCapFactory { cannam@149: // Callback for constructing broken caps. We use this so that we can avoid arena.c++ having a cannam@149: // link-time dependency on capability code that lives in libcapnp-rpc. cannam@149: cannam@149: public: cannam@149: virtual kj::Own newBrokenCap(kj::StringPtr description) = 0; cannam@149: virtual kj::Own newNullCap() = 0; cannam@149: }; cannam@149: #endif // !CAPNP_LITE cannam@149: cannam@149: class SegmentReader { cannam@149: public: cannam@149: inline SegmentReader(Arena* arena, SegmentId id, const word* ptr, SegmentWordCount size, cannam@149: ReadLimiter* readLimiter); cannam@149: cannam@149: KJ_ALWAYS_INLINE(const word* checkOffset(const word* from, ptrdiff_t offset)); cannam@149: // Adds the given offset to the given pointer, checks that it is still within the bounds of the cannam@149: // segment, then returns it. Note that the "end" pointer of the segment (which technically points cannam@149: // to the word after the last in the segment) is considered in-bounds for this purpose, so you cannam@149: // can't necessarily dereference it. You must call checkObject() next to check that the object cannam@149: // you want to read is entirely in-bounds. cannam@149: // cannam@149: // If `from + offset` is out-of-range, this returns a pointer to the end of the segment. Thus, cannam@149: // any non-zero-sized object will fail `checkObject()`. We do this instead of throwing to save cannam@149: // some code footprint. cannam@149: cannam@149: KJ_ALWAYS_INLINE(bool checkObject(const word* start, WordCountN<31> size)); cannam@149: // Assuming that `start` is in-bounds for this segment (probably checked using `checkOffset()`), cannam@149: // check that `start + size` is also in-bounds, and hence the whole area in-between is valid. cannam@149: cannam@149: KJ_ALWAYS_INLINE(bool amplifiedRead(WordCount virtualAmount)); cannam@149: // Indicates that the reader should pretend that `virtualAmount` additional data was read even cannam@149: // though no actual pointer was traversed. This is used e.g. when reading a struct list pointer cannam@149: // where the element sizes are zero -- the sender could set the list size arbitrarily high and cannam@149: // cause the receiver to iterate over this list even though the message itself is small, so we cannam@149: // need to defend against DoS attacks based on this. cannam@149: cannam@149: inline Arena* getArena(); cannam@149: inline SegmentId getSegmentId(); cannam@149: cannam@149: inline const word* getStartPtr(); cannam@149: inline SegmentWordCount getOffsetTo(const word* ptr); cannam@149: inline SegmentWordCount getSize(); cannam@149: cannam@149: inline kj::ArrayPtr getArray(); cannam@149: cannam@149: inline void unread(WordCount64 amount); cannam@149: // Add back some words to the ReadLimiter. cannam@149: cannam@149: private: cannam@149: Arena* arena; cannam@149: SegmentId id; cannam@149: kj::ArrayPtr ptr; // size guaranteed to fit in SEGMENT_WORD_COUNT_BITS bits cannam@149: ReadLimiter* readLimiter; cannam@149: cannam@149: KJ_DISALLOW_COPY(SegmentReader); cannam@149: cannam@149: friend class SegmentBuilder; cannam@149: cannam@149: static void abortCheckObjectFault(); cannam@149: // Called in debug mode in cases that would segfault in opt mode. (Should be impossible!) cannam@149: }; cannam@149: cannam@149: class SegmentBuilder: public SegmentReader { cannam@149: public: cannam@149: inline SegmentBuilder(BuilderArena* arena, SegmentId id, word* ptr, SegmentWordCount size, cannam@149: ReadLimiter* readLimiter, SegmentWordCount wordsUsed = ZERO * WORDS); cannam@149: inline SegmentBuilder(BuilderArena* arena, SegmentId id, const word* ptr, SegmentWordCount size, cannam@149: ReadLimiter* readLimiter); cannam@149: inline SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr), cannam@149: ReadLimiter* readLimiter); cannam@149: cannam@149: KJ_ALWAYS_INLINE(word* allocate(SegmentWordCount amount)); cannam@149: cannam@149: KJ_ALWAYS_INLINE(void checkWritable()); cannam@149: // Throw an exception if the segment is read-only (meaning it is a reference to external data). cannam@149: cannam@149: KJ_ALWAYS_INLINE(word* getPtrUnchecked(SegmentWordCount offset)); cannam@149: // Get a writable pointer into the segment. Throws an exception if the segment is read-only (i.e. cannam@149: // a reference to external immutable data). cannam@149: cannam@149: inline BuilderArena* getArena(); cannam@149: cannam@149: inline kj::ArrayPtr currentlyAllocated(); cannam@149: cannam@149: inline void reset(); cannam@149: cannam@149: inline bool isWritable() { return !readOnly; } cannam@149: cannam@149: inline void tryTruncate(word* from, word* to); cannam@149: // If `from` points just past the current end of the segment, then move the end back to `to`. cannam@149: // Otherwise, do nothing. cannam@149: cannam@149: inline bool tryExtend(word* from, word* to); cannam@149: // If `from` points just past the current end of the segment, and `to` is within the segment cannam@149: // boundaries, then move the end up to `to` and return true. Otherwise, do nothing and return cannam@149: // false. cannam@149: cannam@149: private: cannam@149: word* pos; cannam@149: // Pointer to a pointer to the current end point of the segment, i.e. the location where the cannam@149: // next object should be allocated. cannam@149: cannam@149: bool readOnly; cannam@149: cannam@149: void throwNotWritable(); cannam@149: cannam@149: KJ_DISALLOW_COPY(SegmentBuilder); cannam@149: }; cannam@149: cannam@149: class Arena { cannam@149: public: cannam@149: virtual ~Arena() noexcept(false); cannam@149: cannam@149: virtual SegmentReader* tryGetSegment(SegmentId id) = 0; cannam@149: // Gets the segment with the given ID, or return nullptr if no such segment exists. cannam@149: cannam@149: virtual void reportReadLimitReached() = 0; cannam@149: // Called to report that the read limit has been reached. See ReadLimiter, below. This invokes cannam@149: // the VALIDATE_INPUT() macro which may throw an exception; if it returns normally, the caller cannam@149: // will need to continue with default values. cannam@149: }; cannam@149: cannam@149: class ReaderArena final: public Arena { cannam@149: public: cannam@149: explicit ReaderArena(MessageReader* message); cannam@149: ~ReaderArena() noexcept(false); cannam@149: KJ_DISALLOW_COPY(ReaderArena); cannam@149: cannam@149: // implements Arena ------------------------------------------------ cannam@149: SegmentReader* tryGetSegment(SegmentId id) override; cannam@149: void reportReadLimitReached() override; cannam@149: cannam@149: private: cannam@149: MessageReader* message; cannam@149: ReadLimiter readLimiter; cannam@149: cannam@149: // Optimize for single-segment messages so that small messages are handled quickly. cannam@149: SegmentReader segment0; cannam@149: cannam@149: typedef std::unordered_map> SegmentMap; cannam@149: kj::MutexGuarded>> moreSegments; cannam@149: // We need to mutex-guard the segment map because we lazily initialize segments when they are cannam@149: // first requested, but a Reader is allowed to be used concurrently in multiple threads. Luckily cannam@149: // this only applies to large messages. cannam@149: // cannam@149: // TODO(perf): Thread-local thing instead? Some kind of lockless map? Or do sharing of data cannam@149: // in a different way, where you have to construct a new MessageReader in each thread (but cannam@149: // possibly backed by the same data)? cannam@149: cannam@149: ReaderArena(MessageReader* message, kj::ArrayPtr firstSegment); cannam@149: ReaderArena(MessageReader* message, const word* firstSegment, SegmentWordCount firstSegmentSize); cannam@149: }; cannam@149: cannam@149: class BuilderArena final: public Arena { cannam@149: // A BuilderArena that does not allow the injection of capabilities. cannam@149: cannam@149: public: cannam@149: explicit BuilderArena(MessageBuilder* message); cannam@149: BuilderArena(MessageBuilder* message, kj::ArrayPtr segments); cannam@149: ~BuilderArena() noexcept(false); cannam@149: KJ_DISALLOW_COPY(BuilderArena); cannam@149: cannam@149: inline SegmentBuilder* getRootSegment() { return &segment0; } cannam@149: cannam@149: kj::ArrayPtr> getSegmentsForOutput(); cannam@149: // Get an array of all the segments, suitable for writing out. This only returns the allocated cannam@149: // portion of each segment, whereas tryGetSegment() returns something that includes cannam@149: // not-yet-allocated space. cannam@149: cannam@149: inline CapTableBuilder* getLocalCapTable() { cannam@149: // Return a CapTableBuilder that merely implements local loopback. That is, you can set cannam@149: // capabilities, then read the same capabilities back, but there is no intent ever to transmit cannam@149: // these capabilities. A MessageBuilder that isn't imbued with some other CapTable uses this cannam@149: // by default. cannam@149: // cannam@149: // TODO(cleanup): It's sort of a hack that this exists. In theory, perhaps, unimbued cannam@149: // MessageBuilders should throw exceptions on any attempt to access capability fields, like cannam@149: // unimbued MessageReaders do. However, lots of code exists which uses MallocMessageBuilder cannam@149: // as a temporary holder for data to be copied in and out (without being serialized), and it cannam@149: // is expected that such data can include capabilities, which is admittedly reasonable. cannam@149: // Therefore, all MessageBuilders must have a cap table by default. Arguably we should cannam@149: // deprecate this usage and instead define a new helper type for this exact purpose. cannam@149: cannam@149: return &localCapTable; cannam@149: } cannam@149: cannam@149: SegmentBuilder* getSegment(SegmentId id); cannam@149: // Get the segment with the given id. Crashes or throws an exception if no such segment exists. cannam@149: cannam@149: struct AllocateResult { cannam@149: SegmentBuilder* segment; cannam@149: word* words; cannam@149: }; cannam@149: cannam@149: AllocateResult allocate(SegmentWordCount amount); cannam@149: // Find a segment with at least the given amount of space available and allocate the space. cannam@149: // Note that allocating directly from a particular segment is much faster, but allocating from cannam@149: // the arena is guaranteed to succeed. Therefore callers should try to allocate from a specific cannam@149: // segment first if there is one, then fall back to the arena. cannam@149: cannam@149: SegmentBuilder* addExternalSegment(kj::ArrayPtr content); cannam@149: // Add a new segment to the arena which points to some existing memory region. The segment is cannam@149: // assumed to be completley full; the arena will never allocate from it. In fact, the segment cannam@149: // is considered read-only. Any attempt to get a Builder pointing into this segment will throw cannam@149: // an exception. Readers are allowed, however. cannam@149: // cannam@149: // This can be used to inject some external data into a message without a copy, e.g. embedding a cannam@149: // large mmap'd file into a message as `Data` without forcing that data to actually be read in cannam@149: // from disk (until the message itself is written out). `Orphanage` provides the public API for cannam@149: // this feature. cannam@149: cannam@149: // implements Arena ------------------------------------------------ cannam@149: SegmentReader* tryGetSegment(SegmentId id) override; cannam@149: void reportReadLimitReached() override; cannam@149: cannam@149: private: cannam@149: MessageBuilder* message; cannam@149: ReadLimiter dummyLimiter; cannam@149: cannam@149: class LocalCapTable: public CapTableBuilder { cannam@149: #if !CAPNP_LITE cannam@149: public: cannam@149: kj::Maybe> extractCap(uint index) override; cannam@149: uint injectCap(kj::Own&& cap) override; cannam@149: void dropCap(uint index) override; cannam@149: cannam@149: private: cannam@149: kj::Vector>> capTable; cannam@149: #endif // ! CAPNP_LITE cannam@149: }; cannam@149: cannam@149: LocalCapTable localCapTable; cannam@149: cannam@149: SegmentBuilder segment0; cannam@149: kj::ArrayPtr segment0ForOutput; cannam@149: cannam@149: struct MultiSegmentState { cannam@149: kj::Vector> builders; cannam@149: kj::Vector> forOutput; cannam@149: }; cannam@149: kj::Maybe> moreSegments; cannam@149: cannam@149: SegmentBuilder* segmentWithSpace = nullptr; cannam@149: // When allocating, look for space in this segment first before resorting to allocating a new cannam@149: // segment. This is not necessarily the last segment because addExternalSegment() may add a cannam@149: // segment that is already-full, in which case we don't update this pointer. cannam@149: cannam@149: template // Can be `word` or `const word`. cannam@149: SegmentBuilder* addSegmentInternal(kj::ArrayPtr content); cannam@149: }; cannam@149: cannam@149: // ======================================================================================= cannam@149: cannam@149: inline ReadLimiter::ReadLimiter() cannam@149: : limit(kj::maxValue) {} cannam@149: cannam@149: inline ReadLimiter::ReadLimiter(WordCount64 limit): limit(unbound(limit / WORDS)) {} cannam@149: cannam@149: inline void ReadLimiter::reset(WordCount64 limit) { this->limit = unbound(limit / WORDS); } cannam@149: cannam@149: inline bool ReadLimiter::canRead(WordCount64 amount, Arena* arena) { cannam@149: // Be careful not to store an underflowed value into `limit`, even if multiple threads are cannam@149: // decrementing it. cannam@149: uint64_t current = limit; cannam@149: if (KJ_UNLIKELY(unbound(amount / WORDS) > current)) { cannam@149: arena->reportReadLimitReached(); cannam@149: return false; cannam@149: } else { cannam@149: limit = current - unbound(amount / WORDS); cannam@149: return true; cannam@149: } cannam@149: } cannam@149: cannam@149: // ------------------------------------------------------------------- cannam@149: cannam@149: inline SegmentReader::SegmentReader(Arena* arena, SegmentId id, const word* ptr, cannam@149: SegmentWordCount size, ReadLimiter* readLimiter) cannam@149: : arena(arena), id(id), ptr(kj::arrayPtr(ptr, unbound(size / WORDS))), cannam@149: readLimiter(readLimiter) {} cannam@149: cannam@149: inline const word* SegmentReader::checkOffset(const word* from, ptrdiff_t offset) { cannam@149: ptrdiff_t min = ptr.begin() - from; cannam@149: ptrdiff_t max = ptr.end() - from; cannam@149: if (offset >= min && offset <= max) { cannam@149: return from + offset; cannam@149: } else { cannam@149: return ptr.end(); cannam@149: } cannam@149: } cannam@149: cannam@149: inline bool SegmentReader::checkObject(const word* start, WordCountN<31> size) { cannam@149: auto startOffset = intervalLength(ptr.begin(), start, MAX_SEGMENT_WORDS); cannam@149: #ifdef KJ_DEBUG cannam@149: if (startOffset > bounded(ptr.size()) * WORDS) { cannam@149: abortCheckObjectFault(); cannam@149: } cannam@149: #endif cannam@149: return startOffset + size <= bounded(ptr.size()) * WORDS && cannam@149: readLimiter->canRead(size, arena); cannam@149: } cannam@149: cannam@149: inline bool SegmentReader::amplifiedRead(WordCount virtualAmount) { cannam@149: return readLimiter->canRead(virtualAmount, arena); cannam@149: } cannam@149: cannam@149: inline Arena* SegmentReader::getArena() { return arena; } cannam@149: inline SegmentId SegmentReader::getSegmentId() { return id; } cannam@149: inline const word* SegmentReader::getStartPtr() { return ptr.begin(); } cannam@149: inline SegmentWordCount SegmentReader::getOffsetTo(const word* ptr) { cannam@149: KJ_IREQUIRE(this->ptr.begin() <= ptr && ptr <= this->ptr.end()); cannam@149: return intervalLength(this->ptr.begin(), ptr, MAX_SEGMENT_WORDS); cannam@149: } cannam@149: inline SegmentWordCount SegmentReader::getSize() { cannam@149: return assumeBits(ptr.size()) * WORDS; cannam@149: } cannam@149: inline kj::ArrayPtr SegmentReader::getArray() { return ptr; } cannam@149: inline void SegmentReader::unread(WordCount64 amount) { readLimiter->unread(amount); } cannam@149: cannam@149: // ------------------------------------------------------------------- cannam@149: cannam@149: inline SegmentBuilder::SegmentBuilder( cannam@149: BuilderArena* arena, SegmentId id, word* ptr, SegmentWordCount size, cannam@149: ReadLimiter* readLimiter, SegmentWordCount wordsUsed) cannam@149: : SegmentReader(arena, id, ptr, size, readLimiter), cannam@149: pos(ptr + wordsUsed), readOnly(false) {} cannam@149: inline SegmentBuilder::SegmentBuilder( cannam@149: BuilderArena* arena, SegmentId id, const word* ptr, SegmentWordCount size, cannam@149: ReadLimiter* readLimiter) cannam@149: : SegmentReader(arena, id, ptr, size, readLimiter), cannam@149: // const_cast is safe here because the member won't ever be dereferenced because it appears cannam@149: // to point to the end of the segment anyway. cannam@149: pos(const_cast(ptr + size)), readOnly(true) {} cannam@149: inline SegmentBuilder::SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr), cannam@149: ReadLimiter* readLimiter) cannam@149: : SegmentReader(arena, id, nullptr, ZERO * WORDS, readLimiter), cannam@149: pos(nullptr), readOnly(false) {} cannam@149: cannam@149: inline word* SegmentBuilder::allocate(SegmentWordCount amount) { cannam@149: if (intervalLength(pos, ptr.end(), MAX_SEGMENT_WORDS) < amount) { cannam@149: // Not enough space in the segment for this allocation. cannam@149: return nullptr; cannam@149: } else { cannam@149: // Success. cannam@149: word* result = pos; cannam@149: pos = pos + amount; cannam@149: return result; cannam@149: } cannam@149: } cannam@149: cannam@149: inline void SegmentBuilder::checkWritable() { cannam@149: if (KJ_UNLIKELY(readOnly)) throwNotWritable(); cannam@149: } cannam@149: cannam@149: inline word* SegmentBuilder::getPtrUnchecked(SegmentWordCount offset) { cannam@149: return const_cast(ptr.begin() + offset); cannam@149: } cannam@149: cannam@149: inline BuilderArena* SegmentBuilder::getArena() { cannam@149: // Down-cast safe because SegmentBuilder's constructor always initializes its SegmentReader base cannam@149: // class with an Arena pointer that actually points to a BuilderArena. cannam@149: return static_cast(arena); cannam@149: } cannam@149: cannam@149: inline kj::ArrayPtr SegmentBuilder::currentlyAllocated() { cannam@149: return kj::arrayPtr(ptr.begin(), pos - ptr.begin()); cannam@149: } cannam@149: cannam@149: inline void SegmentBuilder::reset() { cannam@149: word* start = getPtrUnchecked(ZERO * WORDS); cannam@149: memset(start, 0, (pos - start) * sizeof(word)); cannam@149: pos = start; cannam@149: } cannam@149: cannam@149: inline void SegmentBuilder::tryTruncate(word* from, word* to) { cannam@149: if (pos == from) pos = to; cannam@149: } cannam@149: cannam@149: inline bool SegmentBuilder::tryExtend(word* from, word* to) { cannam@149: // Careful about overflow. cannam@149: if (pos == from && to <= ptr.end() && to >= from) { cannam@149: pos = to; cannam@149: return true; cannam@149: } else { cannam@149: return false; cannam@149: } cannam@149: } cannam@149: cannam@149: } // namespace _ (private) cannam@149: } // namespace capnp cannam@149: cannam@149: #endif // CAPNP_ARENA_H_