cannam@62: // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors cannam@62: // Licensed under the MIT License: cannam@62: // cannam@62: // Permission is hereby granted, free of charge, to any person obtaining a copy cannam@62: // of this software and associated documentation files (the "Software"), to deal cannam@62: // in the Software without restriction, including without limitation the rights cannam@62: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cannam@62: // copies of the Software, and to permit persons to whom the Software is cannam@62: // furnished to do so, subject to the following conditions: cannam@62: // cannam@62: // The above copyright notice and this permission notice shall be included in cannam@62: // all copies or substantial portions of the Software. cannam@62: // cannam@62: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR cannam@62: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, cannam@62: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE cannam@62: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER cannam@62: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, cannam@62: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN cannam@62: // THE SOFTWARE. cannam@62: cannam@62: // This file is NOT intended for use by clients, except in generated code. cannam@62: // cannam@62: // This file defines low-level, non-type-safe classes for traversing the Cap'n Proto memory layout cannam@62: // (which is also its wire format). Code generated by the Cap'n Proto compiler uses these classes, cannam@62: // as does other parts of the Cap'n proto library which provide a higher-level interface for cannam@62: // dynamic introspection. cannam@62: cannam@62: #ifndef CAPNP_LAYOUT_H_ cannam@62: #define CAPNP_LAYOUT_H_ cannam@62: cannam@62: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) cannam@62: #pragma GCC system_header cannam@62: #endif cannam@62: cannam@62: #include cannam@62: #include cannam@62: #include "common.h" cannam@62: #include "blob.h" cannam@62: #include "endian.h" cannam@62: cannam@62: #if (defined(__mips__) || defined(__hppa__)) && !defined(CAPNP_CANONICALIZE_NAN) cannam@62: #define CAPNP_CANONICALIZE_NAN 1 cannam@62: // Explicitly detect NaNs and canonicalize them to the quiet NaN value as would be returned by cannam@62: // __builtin_nan("") on systems implementing the IEEE-754 recommended (but not required) NaN cannam@62: // signalling/quiet differentiation (such as x86). Unfortunately, some architectures -- in cannam@62: // particular, MIPS -- represent quiet vs. signalling nans differently than the rest of the world. cannam@62: // Canonicalizing them makes output consistent (which is important!), but hurts performance cannam@62: // slightly. cannam@62: // cannam@62: // Note that trying to convert MIPS NaNs to standard NaNs without losing data doesn't work. cannam@62: // Signaling vs. quiet is indicated by a bit, with the meaning being the opposite on MIPS vs. cannam@62: // everyone else. It would be great if we could just flip that bit, but we can't, because if the cannam@62: // significand is all-zero, then the value is infinity rather than NaN. This means that on most cannam@62: // machines, where the bit indicates quietness, there is one more quiet NaN value than signalling cannam@62: // NaN value, whereas on MIPS there is one more sNaN than qNaN, and thus there is no isomorphic cannam@62: // mapping that properly preserves quietness. Instead of doing something hacky, we just give up cannam@62: // and blow away NaN payloads, because no one uses them anyway. cannam@62: #endif cannam@62: cannam@62: namespace capnp { cannam@62: cannam@62: #if !CAPNP_LITE cannam@62: class ClientHook; cannam@62: #endif // !CAPNP_LITE cannam@62: cannam@62: namespace _ { // private cannam@62: cannam@62: class PointerBuilder; cannam@62: class PointerReader; cannam@62: class StructBuilder; cannam@62: class StructReader; cannam@62: class ListBuilder; cannam@62: class ListReader; cannam@62: class OrphanBuilder; cannam@62: struct WirePointer; cannam@62: struct WireHelpers; cannam@62: class SegmentReader; cannam@62: class SegmentBuilder; cannam@62: class Arena; cannam@62: class BuilderArena; cannam@62: cannam@62: // ============================================================================= cannam@62: cannam@62: #if CAPNP_DEBUG_TYPES cannam@62: typedef kj::UnitRatio, BitLabel, ElementLabel> BitsPerElementTableType; cannam@62: #else cannam@62: typedef uint BitsPerElementTableType; cannam@62: #endif cannam@62: cannam@62: static constexpr BitsPerElementTableType BITS_PER_ELEMENT_TABLE[8] = { cannam@62: bounded< 0>() * BITS / ELEMENTS, cannam@62: bounded< 1>() * BITS / ELEMENTS, cannam@62: bounded< 8>() * BITS / ELEMENTS, cannam@62: bounded<16>() * BITS / ELEMENTS, cannam@62: bounded<32>() * BITS / ELEMENTS, cannam@62: bounded<64>() * BITS / ELEMENTS, cannam@62: bounded< 0>() * BITS / ELEMENTS, cannam@62: bounded< 0>() * BITS / ELEMENTS cannam@62: }; cannam@62: cannam@62: inline KJ_CONSTEXPR() BitsPerElementTableType dataBitsPerElement(ElementSize size) { cannam@62: return _::BITS_PER_ELEMENT_TABLE[static_cast(size)]; cannam@62: } cannam@62: cannam@62: inline constexpr PointersPerElementN<1> pointersPerElement(ElementSize size) { cannam@62: return size == ElementSize::POINTER cannam@62: ? PointersPerElementN<1>(ONE * POINTERS / ELEMENTS) cannam@62: : PointersPerElementN<1>(ZERO * POINTERS / ELEMENTS); cannam@62: } cannam@62: cannam@62: static constexpr BitsPerElementTableType BITS_PER_ELEMENT_INCLUDING_PONITERS_TABLE[8] = { cannam@62: bounded< 0>() * BITS / ELEMENTS, cannam@62: bounded< 1>() * BITS / ELEMENTS, cannam@62: bounded< 8>() * BITS / ELEMENTS, cannam@62: bounded<16>() * BITS / ELEMENTS, cannam@62: bounded<32>() * BITS / ELEMENTS, cannam@62: bounded<64>() * BITS / ELEMENTS, cannam@62: bounded<64>() * BITS / ELEMENTS, cannam@62: bounded< 0>() * BITS / ELEMENTS cannam@62: }; cannam@62: cannam@62: inline KJ_CONSTEXPR() BitsPerElementTableType bitsPerElementIncludingPointers(ElementSize size) { cannam@62: return _::BITS_PER_ELEMENT_INCLUDING_PONITERS_TABLE[static_cast(size)]; cannam@62: } cannam@62: cannam@62: template struct ElementSizeForByteSize; cannam@62: template <> struct ElementSizeForByteSize<1> { static constexpr ElementSize value = ElementSize::BYTE; }; cannam@62: template <> struct ElementSizeForByteSize<2> { static constexpr ElementSize value = ElementSize::TWO_BYTES; }; cannam@62: template <> struct ElementSizeForByteSize<4> { static constexpr ElementSize value = ElementSize::FOUR_BYTES; }; cannam@62: template <> struct ElementSizeForByteSize<8> { static constexpr ElementSize value = ElementSize::EIGHT_BYTES; }; cannam@62: cannam@62: template struct ElementSizeForType { cannam@62: static constexpr ElementSize value = cannam@62: // Primitive types that aren't special-cased below can be determined from sizeof(). cannam@62: CAPNP_KIND(T) == Kind::PRIMITIVE ? ElementSizeForByteSize::value : cannam@62: CAPNP_KIND(T) == Kind::ENUM ? ElementSize::TWO_BYTES : cannam@62: CAPNP_KIND(T) == Kind::STRUCT ? ElementSize::INLINE_COMPOSITE : cannam@62: cannam@62: // Everything else is a pointer. cannam@62: ElementSize::POINTER; cannam@62: }; cannam@62: cannam@62: // Void and bool are special. cannam@62: template <> struct ElementSizeForType { static constexpr ElementSize value = ElementSize::VOID; }; cannam@62: template <> struct ElementSizeForType { static constexpr ElementSize value = ElementSize::BIT; }; cannam@62: cannam@62: // Lists and blobs are pointers, not structs. cannam@62: template struct ElementSizeForType> { cannam@62: static constexpr ElementSize value = ElementSize::POINTER; cannam@62: }; cannam@62: template <> struct ElementSizeForType { cannam@62: static constexpr ElementSize value = ElementSize::POINTER; cannam@62: }; cannam@62: template <> struct ElementSizeForType { cannam@62: static constexpr ElementSize value = ElementSize::POINTER; cannam@62: }; cannam@62: cannam@62: template cannam@62: inline constexpr ElementSize elementSizeForType() { cannam@62: return ElementSizeForType::value; cannam@62: } cannam@62: cannam@62: struct MessageSizeCounts { cannam@62: WordCountN<61, uint64_t> wordCount; // 2^64 bytes cannam@62: uint capCount; cannam@62: cannam@62: MessageSizeCounts& operator+=(const MessageSizeCounts& other) { cannam@62: // OK to truncate unchecked because this class is used to count actual stuff in memory, and cannam@62: // we couldn't possibly have anywhere near 2^61 words. cannam@62: wordCount = assumeBits<61>(wordCount + other.wordCount); cannam@62: capCount += other.capCount; cannam@62: return *this; cannam@62: } cannam@62: cannam@62: void addWords(WordCountN<61, uint64_t> other) { cannam@62: wordCount = assumeBits<61>(wordCount + other); cannam@62: } cannam@62: cannam@62: MessageSize asPublic() { cannam@62: return MessageSize { unbound(wordCount / WORDS), capCount }; cannam@62: } cannam@62: }; cannam@62: cannam@62: // ============================================================================= cannam@62: cannam@62: template cannam@62: union AlignedData { cannam@62: // Useful for declaring static constant data blobs as an array of bytes, but forcing those cannam@62: // bytes to be word-aligned. cannam@62: cannam@62: uint8_t bytes[wordCount * sizeof(word)]; cannam@62: word words[wordCount]; cannam@62: }; cannam@62: cannam@62: struct StructSize { cannam@62: StructDataWordCount data; cannam@62: StructPointerCount pointers; cannam@62: cannam@62: inline constexpr WordCountN<17> total() const { return data + pointers * WORDS_PER_POINTER; } cannam@62: cannam@62: StructSize() = default; cannam@62: inline constexpr StructSize(StructDataWordCount data, StructPointerCount pointers) cannam@62: : data(data), pointers(pointers) {} cannam@62: }; cannam@62: cannam@62: template cannam@62: inline constexpr StructSize structSize() { cannam@62: return StructSize(bounded(CapnpPrivate::dataWordSize) * WORDS, cannam@62: bounded(CapnpPrivate::pointerCount) * POINTERS); cannam@62: } cannam@62: cannam@62: template > cannam@62: inline constexpr StructSize minStructSizeForElement() { cannam@62: // If T is a struct, return its struct size. Otherwise return the minimum struct size big enough cannam@62: // to hold a T. cannam@62: cannam@62: return StructSize(bounded(CapnpPrivate::dataWordSize) * WORDS, cannam@62: bounded(CapnpPrivate::pointerCount) * POINTERS); cannam@62: } cannam@62: cannam@62: template > cannam@62: inline constexpr StructSize minStructSizeForElement() { cannam@62: // If T is a struct, return its struct size. Otherwise return the minimum struct size big enough cannam@62: // to hold a T. cannam@62: cannam@62: return StructSize( cannam@62: dataBitsPerElement(elementSizeForType()) * ELEMENTS > ZERO * BITS cannam@62: ? StructDataWordCount(ONE * WORDS) : StructDataWordCount(ZERO * WORDS), cannam@62: pointersPerElement(elementSizeForType()) * ELEMENTS); cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: // Masking of default values cannam@62: cannam@62: template struct Mask_; cannam@62: template struct Mask_ { typedef T Type; }; cannam@62: template struct Mask_ { typedef uint16_t Type; }; cannam@62: template <> struct Mask_ { typedef uint32_t Type; }; cannam@62: template <> struct Mask_ { typedef uint64_t Type; }; cannam@62: cannam@62: template struct Mask_ { cannam@62: // Union discriminants end up here. cannam@62: static_assert(sizeof(T) == 2, "Don't know how to mask this type."); cannam@62: typedef uint16_t Type; cannam@62: }; cannam@62: cannam@62: template cannam@62: using Mask = typename Mask_::Type; cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(Mask mask(T value, Mask mask)); cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T unmask(Mask value, Mask mask)); cannam@62: cannam@62: template cannam@62: inline Mask mask(T value, Mask mask) { cannam@62: return static_cast >(value) ^ mask; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline uint32_t mask(float value, uint32_t mask) { cannam@62: #if CAPNP_CANONICALIZE_NAN cannam@62: if (value != value) { cannam@62: return 0x7fc00000u ^ mask; cannam@62: } cannam@62: #endif cannam@62: cannam@62: uint32_t i; cannam@62: static_assert(sizeof(i) == sizeof(value), "float is not 32 bits?"); cannam@62: memcpy(&i, &value, sizeof(value)); cannam@62: return i ^ mask; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline uint64_t mask(double value, uint64_t mask) { cannam@62: #if CAPNP_CANONICALIZE_NAN cannam@62: if (value != value) { cannam@62: return 0x7ff8000000000000ull ^ mask; cannam@62: } cannam@62: #endif cannam@62: cannam@62: uint64_t i; cannam@62: static_assert(sizeof(i) == sizeof(value), "double is not 64 bits?"); cannam@62: memcpy(&i, &value, sizeof(value)); cannam@62: return i ^ mask; cannam@62: } cannam@62: cannam@62: template cannam@62: inline T unmask(Mask value, Mask mask) { cannam@62: return static_cast(value ^ mask); cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline float unmask(uint32_t value, uint32_t mask) { cannam@62: value ^= mask; cannam@62: float result; cannam@62: static_assert(sizeof(result) == sizeof(value), "float is not 32 bits?"); cannam@62: memcpy(&result, &value, sizeof(value)); cannam@62: return result; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline double unmask(uint64_t value, uint64_t mask) { cannam@62: value ^= mask; cannam@62: double result; cannam@62: static_assert(sizeof(result) == sizeof(value), "double is not 64 bits?"); cannam@62: memcpy(&result, &value, sizeof(value)); cannam@62: return result; cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: class CapTableReader { cannam@62: public: cannam@62: #if !CAPNP_LITE cannam@62: virtual kj::Maybe> extractCap(uint index) = 0; cannam@62: // Extract the capability at the given index. If the index is invalid, returns null. cannam@62: #endif // !CAPNP_LITE cannam@62: }; cannam@62: cannam@62: class CapTableBuilder: public CapTableReader { cannam@62: public: cannam@62: #if !CAPNP_LITE cannam@62: virtual uint injectCap(kj::Own&& cap) = 0; cannam@62: // Add the capability to the message and return its index. If the same ClientHook is injected cannam@62: // twice, this may return the same index both times, but in this case dropCap() needs to be cannam@62: // called an equal number of times to actually remove the cap. cannam@62: cannam@62: virtual void dropCap(uint index) = 0; cannam@62: // Remove a capability injected earlier. Called when the pointer is overwritten or zero'd out. cannam@62: #endif // !CAPNP_LITE cannam@62: }; cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: class PointerBuilder: public kj::DisallowConstCopy { cannam@62: // Represents a single pointer, usually embedded in a struct or a list. cannam@62: cannam@62: public: cannam@62: inline PointerBuilder(): segment(nullptr), capTable(nullptr), pointer(nullptr) {} cannam@62: cannam@62: static inline PointerBuilder getRoot( cannam@62: SegmentBuilder* segment, CapTableBuilder* capTable, word* location); cannam@62: // Get a PointerBuilder representing a message root located in the given segment at the given cannam@62: // location. cannam@62: cannam@62: inline bool isNull() { return getPointerType() == PointerType::NULL_; } cannam@62: PointerType getPointerType() const; cannam@62: cannam@62: StructBuilder getStruct(StructSize size, const word* defaultValue); cannam@62: ListBuilder getList(ElementSize elementSize, const word* defaultValue); cannam@62: ListBuilder getStructList(StructSize elementSize, const word* defaultValue); cannam@62: ListBuilder getListAnySize(const word* defaultValue); cannam@62: template typename T::Builder getBlob( cannam@62: const void* defaultValue, ByteCount defaultSize); cannam@62: #if !CAPNP_LITE cannam@62: kj::Own getCapability(); cannam@62: #endif // !CAPNP_LITE cannam@62: // Get methods: Get the value. If it is null, initialize it to a copy of the default value. cannam@62: // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a cannam@62: // simple byte array for blobs. cannam@62: cannam@62: StructBuilder initStruct(StructSize size); cannam@62: ListBuilder initList(ElementSize elementSize, ElementCount elementCount); cannam@62: ListBuilder initStructList(ElementCount elementCount, StructSize size); cannam@62: template typename T::Builder initBlob(ByteCount size); cannam@62: // Init methods: Initialize the pointer to a newly-allocated object, discarding the existing cannam@62: // object. cannam@62: cannam@62: void setStruct(const StructReader& value, bool canonical = false); cannam@62: void setList(const ListReader& value, bool canonical = false); cannam@62: template void setBlob(typename T::Reader value); cannam@62: #if !CAPNP_LITE cannam@62: void setCapability(kj::Own&& cap); cannam@62: #endif // !CAPNP_LITE cannam@62: // Set methods: Initialize the pointer to a newly-allocated copy of the given value, discarding cannam@62: // the existing object. cannam@62: cannam@62: void adopt(OrphanBuilder&& orphan); cannam@62: // Set the pointer to point at the given orphaned value. cannam@62: cannam@62: OrphanBuilder disown(); cannam@62: // Set the pointer to null and return its previous value as an orphan. cannam@62: cannam@62: void clear(); cannam@62: // Clear the pointer to null, discarding its previous value. cannam@62: cannam@62: void transferFrom(PointerBuilder other); cannam@62: // Equivalent to `adopt(other.disown())`. cannam@62: cannam@62: void copyFrom(PointerReader other, bool canonical = false); cannam@62: // Equivalent to `set(other.get())`. cannam@62: // If you set the canonical flag, it will attempt to lay the target out cannam@62: // canonically, provided enough space is available. cannam@62: cannam@62: PointerReader asReader() const; cannam@62: cannam@62: BuilderArena* getArena() const; cannam@62: // Get the arena containing this pointer. cannam@62: cannam@62: CapTableBuilder* getCapTable(); cannam@62: // Gets the capability context in which this object is operating. cannam@62: cannam@62: PointerBuilder imbue(CapTableBuilder* capTable); cannam@62: // Return a copy of this builder except using the given capability context. cannam@62: cannam@62: private: cannam@62: SegmentBuilder* segment; // Memory segment in which the pointer resides. cannam@62: CapTableBuilder* capTable; // Table of capability indexes. cannam@62: WirePointer* pointer; // Pointer to the pointer. cannam@62: cannam@62: inline PointerBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, WirePointer* pointer) cannam@62: : segment(segment), capTable(capTable), pointer(pointer) {} cannam@62: cannam@62: friend class StructBuilder; cannam@62: friend class ListBuilder; cannam@62: friend class OrphanBuilder; cannam@62: }; cannam@62: cannam@62: class PointerReader { cannam@62: public: cannam@62: inline PointerReader() cannam@62: : segment(nullptr), capTable(nullptr), pointer(nullptr), nestingLimit(0x7fffffff) {} cannam@62: cannam@62: static PointerReader getRoot(SegmentReader* segment, CapTableReader* capTable, cannam@62: const word* location, int nestingLimit); cannam@62: // Get a PointerReader representing a message root located in the given segment at the given cannam@62: // location. cannam@62: cannam@62: static inline PointerReader getRootUnchecked(const word* location); cannam@62: // Get a PointerReader for an unchecked message. cannam@62: cannam@62: MessageSizeCounts targetSize() const; cannam@62: // Return the total size of the target object and everything to which it points. Does not count cannam@62: // far pointer overhead. This is useful for deciding how much space is needed to copy the object cannam@62: // into a flat array. However, the caller is advised NOT to treat this value as secure. Instead, cannam@62: // use the result as a hint for allocating the first segment, do the copy, and then throw an cannam@62: // exception if it overruns. cannam@62: cannam@62: inline bool isNull() const { return getPointerType() == PointerType::NULL_; } cannam@62: PointerType getPointerType() const; cannam@62: cannam@62: StructReader getStruct(const word* defaultValue) const; cannam@62: ListReader getList(ElementSize expectedElementSize, const word* defaultValue) const; cannam@62: ListReader getListAnySize(const word* defaultValue) const; cannam@62: template cannam@62: typename T::Reader getBlob(const void* defaultValue, ByteCount defaultSize) const; cannam@62: #if !CAPNP_LITE cannam@62: kj::Own getCapability() const; cannam@62: #endif // !CAPNP_LITE cannam@62: // Get methods: Get the value. If it is null, return the default value instead. cannam@62: // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a cannam@62: // simple byte array for blobs. cannam@62: cannam@62: const word* getUnchecked() const; cannam@62: // If this is an unchecked message, get a word* pointing at the location of the pointer. This cannam@62: // word* can actually be passed to readUnchecked() to read the designated sub-object later. If cannam@62: // this isn't an unchecked message, throws an exception. cannam@62: cannam@62: kj::Maybe getArena() const; cannam@62: // Get the arena containing this pointer. cannam@62: cannam@62: CapTableReader* getCapTable(); cannam@62: // Gets the capability context in which this object is operating. cannam@62: cannam@62: PointerReader imbue(CapTableReader* capTable) const; cannam@62: // Return a copy of this reader except using the given capability context. cannam@62: cannam@62: bool isCanonical(const word **readHead); cannam@62: // Validate this pointer's canonicity, subject to the conditions: cannam@62: // * All data to the left of readHead has been read thus far (for pointer cannam@62: // ordering) cannam@62: // * All pointers in preorder have already been checked cannam@62: // * This pointer is in the first and only segment of the message cannam@62: cannam@62: private: cannam@62: SegmentReader* segment; // Memory segment in which the pointer resides. cannam@62: CapTableReader* capTable; // Table of capability indexes. cannam@62: const WirePointer* pointer; // Pointer to the pointer. null = treat as null pointer. cannam@62: cannam@62: int nestingLimit; cannam@62: // Limits the depth of message structures to guard against stack-overflow-based DoS attacks. cannam@62: // Once this reaches zero, further pointers will be pruned. cannam@62: cannam@62: inline PointerReader(SegmentReader* segment, CapTableReader* capTable, cannam@62: const WirePointer* pointer, int nestingLimit) cannam@62: : segment(segment), capTable(capTable), pointer(pointer), nestingLimit(nestingLimit) {} cannam@62: cannam@62: friend class StructReader; cannam@62: friend class ListReader; cannam@62: friend class PointerBuilder; cannam@62: friend class OrphanBuilder; cannam@62: }; cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: class StructBuilder: public kj::DisallowConstCopy { cannam@62: public: cannam@62: inline StructBuilder(): segment(nullptr), capTable(nullptr), data(nullptr), pointers(nullptr) {} cannam@62: cannam@62: inline word* getLocation() { return reinterpret_cast(data); } cannam@62: // Get the object's location. Only valid for independently-allocated objects (i.e. not list cannam@62: // elements). cannam@62: cannam@62: inline StructDataBitCount getDataSectionSize() const { return dataSize; } cannam@62: inline StructPointerCount getPointerSectionSize() const { return pointerCount; } cannam@62: inline kj::ArrayPtr getDataSectionAsBlob(); cannam@62: inline _::ListBuilder getPointerSectionAsList(); cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(bool hasDataField(StructDataOffset offset)); cannam@62: // Return true if the field is set to something other than its default value. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset)); cannam@62: // Gets the data field value of the given type at the given offset. The offset is measured in cannam@62: // multiples of the field size, determined by the type. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset, Mask mask)); cannam@62: // Like getDataField() but applies the given XOR mask to the data on load. Used for reading cannam@62: // fields with non-zero default values. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(void setDataField(StructDataOffset offset, kj::NoInfer value)); cannam@62: // Sets the data field value at the given offset. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(void setDataField(StructDataOffset offset, cannam@62: kj::NoInfer value, Mask mask)); cannam@62: // Like setDataField() but applies the given XOR mask before storing. Used for writing fields cannam@62: // with non-zero default values. cannam@62: cannam@62: KJ_ALWAYS_INLINE(PointerBuilder getPointerField(StructPointerOffset ptrIndex)); cannam@62: // Get a builder for a pointer field given the index within the pointer section. cannam@62: cannam@62: void clearAll(); cannam@62: // Clear all pointers and data. cannam@62: cannam@62: void transferContentFrom(StructBuilder other); cannam@62: // Adopt all pointers from `other`, and also copy all data. If `other`'s sections are larger cannam@62: // than this, the extra data is not transferred, meaning there is a risk of data loss when cannam@62: // transferring from messages built with future versions of the protocol. cannam@62: cannam@62: void copyContentFrom(StructReader other); cannam@62: // Copy content from `other`. If `other`'s sections are larger than this, the extra data is not cannam@62: // copied, meaning there is a risk of data loss when copying from messages built with future cannam@62: // versions of the protocol. cannam@62: cannam@62: StructReader asReader() const; cannam@62: // Gets a StructReader pointing at the same memory. cannam@62: cannam@62: BuilderArena* getArena(); cannam@62: // Gets the arena in which this object is allocated. cannam@62: cannam@62: CapTableBuilder* getCapTable(); cannam@62: // Gets the capability context in which this object is operating. cannam@62: cannam@62: StructBuilder imbue(CapTableBuilder* capTable); cannam@62: // Return a copy of this builder except using the given capability context. cannam@62: cannam@62: private: cannam@62: SegmentBuilder* segment; // Memory segment in which the struct resides. cannam@62: CapTableBuilder* capTable; // Table of capability indexes. cannam@62: void* data; // Pointer to the encoded data. cannam@62: WirePointer* pointers; // Pointer to the encoded pointers. cannam@62: cannam@62: StructDataBitCount dataSize; cannam@62: // Size of data section. We use a bit count rather than a word count to more easily handle the cannam@62: // case of struct lists encoded with less than a word per element. cannam@62: cannam@62: StructPointerCount pointerCount; // Size of the pointer section. cannam@62: cannam@62: inline StructBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, cannam@62: void* data, WirePointer* pointers, cannam@62: StructDataBitCount dataSize, StructPointerCount pointerCount) cannam@62: : segment(segment), capTable(capTable), data(data), pointers(pointers), cannam@62: dataSize(dataSize), pointerCount(pointerCount) {} cannam@62: cannam@62: friend class ListBuilder; cannam@62: friend struct WireHelpers; cannam@62: friend class OrphanBuilder; cannam@62: }; cannam@62: cannam@62: class StructReader { cannam@62: public: cannam@62: inline StructReader() cannam@62: : segment(nullptr), capTable(nullptr), data(nullptr), pointers(nullptr), cannam@62: dataSize(ZERO * BITS), pointerCount(ZERO * POINTERS), nestingLimit(0x7fffffff) {} cannam@62: inline StructReader(kj::ArrayPtr data) cannam@62: : segment(nullptr), capTable(nullptr), data(data.begin()), pointers(nullptr), cannam@62: dataSize(assumeBits(data.size()) * WORDS * BITS_PER_WORD), cannam@62: pointerCount(ZERO * POINTERS), nestingLimit(0x7fffffff) {} cannam@62: cannam@62: const void* getLocation() const { return data; } cannam@62: cannam@62: inline StructDataBitCount getDataSectionSize() const { return dataSize; } cannam@62: inline StructPointerCount getPointerSectionSize() const { return pointerCount; } cannam@62: inline kj::ArrayPtr getDataSectionAsBlob(); cannam@62: inline _::ListReader getPointerSectionAsList(); cannam@62: cannam@62: kj::Array canonicalize(); cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(bool hasDataField(StructDataOffset offset) const); cannam@62: // Return true if the field is set to something other than its default value. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset) const); cannam@62: // Get the data field value of the given type at the given offset. The offset is measured in cannam@62: // multiples of the field size, determined by the type. Returns zero if the offset is past the cannam@62: // end of the struct's data section. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset, Mask mask) const); cannam@62: // Like getDataField(offset), but applies the given XOR mask to the result. Used for reading cannam@62: // fields with non-zero default values. cannam@62: cannam@62: KJ_ALWAYS_INLINE(PointerReader getPointerField(StructPointerOffset ptrIndex) const); cannam@62: // Get a reader for a pointer field given the index within the pointer section. If the index cannam@62: // is out-of-bounds, returns a null pointer. cannam@62: cannam@62: MessageSizeCounts totalSize() const; cannam@62: // Return the total size of the struct and everything to which it points. Does not count far cannam@62: // pointer overhead. This is useful for deciding how much space is needed to copy the struct cannam@62: // into a flat array. However, the caller is advised NOT to treat this value as secure. Instead, cannam@62: // use the result as a hint for allocating the first segment, do the copy, and then throw an cannam@62: // exception if it overruns. cannam@62: cannam@62: CapTableReader* getCapTable(); cannam@62: // Gets the capability context in which this object is operating. cannam@62: cannam@62: StructReader imbue(CapTableReader* capTable) const; cannam@62: // Return a copy of this reader except using the given capability context. cannam@62: cannam@62: bool isCanonical(const word **readHead, const word **ptrHead, cannam@62: bool *dataTrunc, bool *ptrTrunc); cannam@62: // Validate this pointer's canonicity, subject to the conditions: cannam@62: // * All data to the left of readHead has been read thus far (for pointer cannam@62: // ordering) cannam@62: // * All pointers in preorder have already been checked cannam@62: // * This pointer is in the first and only segment of the message cannam@62: // cannam@62: // If this function returns false, the struct is non-canonical. If it cannam@62: // returns true, then: cannam@62: // * If it is a composite in a list, it is canonical if at least one struct cannam@62: // in the list outputs dataTrunc = 1, and at least one outputs ptrTrunc = 1 cannam@62: // * If it is derived from a struct pointer, it is canonical if cannam@62: // dataTrunc = 1 AND ptrTrunc = 1 cannam@62: cannam@62: private: cannam@62: SegmentReader* segment; // Memory segment in which the struct resides. cannam@62: CapTableReader* capTable; // Table of capability indexes. cannam@62: cannam@62: const void* data; cannam@62: const WirePointer* pointers; cannam@62: cannam@62: StructDataBitCount dataSize; cannam@62: // Size of data section. We use a bit count rather than a word count to more easily handle the cannam@62: // case of struct lists encoded with less than a word per element. cannam@62: cannam@62: StructPointerCount pointerCount; // Size of the pointer section. cannam@62: cannam@62: int nestingLimit; cannam@62: // Limits the depth of message structures to guard against stack-overflow-based DoS attacks. cannam@62: // Once this reaches zero, further pointers will be pruned. cannam@62: // TODO(perf): Limit to 16 bits for better packing? cannam@62: cannam@62: inline StructReader(SegmentReader* segment, CapTableReader* capTable, cannam@62: const void* data, const WirePointer* pointers, cannam@62: StructDataBitCount dataSize, StructPointerCount pointerCount, cannam@62: int nestingLimit) cannam@62: : segment(segment), capTable(capTable), data(data), pointers(pointers), cannam@62: dataSize(dataSize), pointerCount(pointerCount), cannam@62: nestingLimit(nestingLimit) {} cannam@62: cannam@62: friend class ListReader; cannam@62: friend class StructBuilder; cannam@62: friend struct WireHelpers; cannam@62: }; cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: class ListBuilder: public kj::DisallowConstCopy { cannam@62: public: cannam@62: inline explicit ListBuilder(ElementSize elementSize) cannam@62: : segment(nullptr), capTable(nullptr), ptr(nullptr), elementCount(ZERO * ELEMENTS), cannam@62: step(ZERO * BITS / ELEMENTS), structDataSize(ZERO * BITS), cannam@62: structPointerCount(ZERO * POINTERS), elementSize(elementSize) {} cannam@62: cannam@62: inline word* getLocation() { cannam@62: // Get the object's location. cannam@62: cannam@62: if (elementSize == ElementSize::INLINE_COMPOSITE && ptr != nullptr) { cannam@62: return reinterpret_cast(ptr) - POINTER_SIZE_IN_WORDS; cannam@62: } else { cannam@62: return reinterpret_cast(ptr); cannam@62: } cannam@62: } cannam@62: cannam@62: inline ElementSize getElementSize() const { return elementSize; } cannam@62: cannam@62: inline ListElementCount size() const; cannam@62: // The number of elements in the list. cannam@62: cannam@62: Text::Builder asText(); cannam@62: Data::Builder asData(); cannam@62: // Reinterpret the list as a blob. Throws an exception if the elements are not byte-sized. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T getDataElement(ElementCount index)); cannam@62: // Get the element of the given type at the given index. cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(void setDataElement(ElementCount index, kj::NoInfer value)); cannam@62: // Set the element at the given index. cannam@62: cannam@62: KJ_ALWAYS_INLINE(PointerBuilder getPointerElement(ElementCount index)); cannam@62: cannam@62: StructBuilder getStructElement(ElementCount index); cannam@62: cannam@62: ListReader asReader() const; cannam@62: // Get a ListReader pointing at the same memory. cannam@62: cannam@62: BuilderArena* getArena(); cannam@62: // Gets the arena in which this object is allocated. cannam@62: cannam@62: CapTableBuilder* getCapTable(); cannam@62: // Gets the capability context in which this object is operating. cannam@62: cannam@62: ListBuilder imbue(CapTableBuilder* capTable); cannam@62: // Return a copy of this builder except using the given capability context. cannam@62: cannam@62: private: cannam@62: SegmentBuilder* segment; // Memory segment in which the list resides. cannam@62: CapTableBuilder* capTable; // Table of capability indexes. cannam@62: cannam@62: byte* ptr; // Pointer to list content. cannam@62: cannam@62: ListElementCount elementCount; // Number of elements in the list. cannam@62: cannam@62: BitsPerElementN<23> step; cannam@62: // The distance between elements. The maximum value occurs when a struct contains 2^16-1 data cannam@62: // words and 2^16-1 pointers, i.e. 2^17 - 2 words, or 2^23 - 128 bits. cannam@62: cannam@62: StructDataBitCount structDataSize; cannam@62: StructPointerCount structPointerCount; cannam@62: // The struct properties to use when interpreting the elements as structs. All lists can be cannam@62: // interpreted as struct lists, so these are always filled in. cannam@62: cannam@62: ElementSize elementSize; cannam@62: // The element size as a ElementSize. This is only really needed to disambiguate INLINE_COMPOSITE cannam@62: // from other types when the overall size is exactly zero or one words. cannam@62: cannam@62: inline ListBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, void* ptr, cannam@62: BitsPerElementN<23> step, ListElementCount size, cannam@62: StructDataBitCount structDataSize, StructPointerCount structPointerCount, cannam@62: ElementSize elementSize) cannam@62: : segment(segment), capTable(capTable), ptr(reinterpret_cast(ptr)), cannam@62: elementCount(size), step(step), structDataSize(structDataSize), cannam@62: structPointerCount(structPointerCount), elementSize(elementSize) {} cannam@62: cannam@62: friend class StructBuilder; cannam@62: friend struct WireHelpers; cannam@62: friend class OrphanBuilder; cannam@62: }; cannam@62: cannam@62: class ListReader { cannam@62: public: cannam@62: inline explicit ListReader(ElementSize elementSize) cannam@62: : segment(nullptr), capTable(nullptr), ptr(nullptr), elementCount(ZERO * ELEMENTS), cannam@62: step(ZERO * BITS / ELEMENTS), structDataSize(ZERO * BITS), cannam@62: structPointerCount(ZERO * POINTERS), elementSize(elementSize), nestingLimit(0x7fffffff) {} cannam@62: cannam@62: inline ListElementCount size() const; cannam@62: // The number of elements in the list. cannam@62: cannam@62: inline ElementSize getElementSize() const { return elementSize; } cannam@62: cannam@62: Text::Reader asText(); cannam@62: Data::Reader asData(); cannam@62: // Reinterpret the list as a blob. Throws an exception if the elements are not byte-sized. cannam@62: cannam@62: kj::ArrayPtr asRawBytes(); cannam@62: cannam@62: template cannam@62: KJ_ALWAYS_INLINE(T getDataElement(ElementCount index) const); cannam@62: // Get the element of the given type at the given index. cannam@62: cannam@62: KJ_ALWAYS_INLINE(PointerReader getPointerElement(ElementCount index) const); cannam@62: cannam@62: StructReader getStructElement(ElementCount index) const; cannam@62: cannam@62: CapTableReader* getCapTable(); cannam@62: // Gets the capability context in which this object is operating. cannam@62: cannam@62: ListReader imbue(CapTableReader* capTable) const; cannam@62: // Return a copy of this reader except using the given capability context. cannam@62: cannam@62: bool isCanonical(const word **readHead, const WirePointer* ref); cannam@62: // Validate this pointer's canonicity, subject to the conditions: cannam@62: // * All data to the left of readHead has been read thus far (for pointer cannam@62: // ordering) cannam@62: // * All pointers in preorder have already been checked cannam@62: // * This pointer is in the first and only segment of the message cannam@62: cannam@62: private: cannam@62: SegmentReader* segment; // Memory segment in which the list resides. cannam@62: CapTableReader* capTable; // Table of capability indexes. cannam@62: cannam@62: const byte* ptr; // Pointer to list content. cannam@62: cannam@62: ListElementCount elementCount; // Number of elements in the list. cannam@62: cannam@62: BitsPerElementN<23> step; cannam@62: // The distance between elements. The maximum value occurs when a struct contains 2^16-1 data cannam@62: // words and 2^16-1 pointers, i.e. 2^17 - 2 words, or 2^23 - 2 bits. cannam@62: cannam@62: StructDataBitCount structDataSize; cannam@62: StructPointerCount structPointerCount; cannam@62: // The struct properties to use when interpreting the elements as structs. All lists can be cannam@62: // interpreted as struct lists, so these are always filled in. cannam@62: cannam@62: ElementSize elementSize; cannam@62: // The element size as a ElementSize. This is only really needed to disambiguate INLINE_COMPOSITE cannam@62: // from other types when the overall size is exactly zero or one words. cannam@62: cannam@62: int nestingLimit; cannam@62: // Limits the depth of message structures to guard against stack-overflow-based DoS attacks. cannam@62: // Once this reaches zero, further pointers will be pruned. cannam@62: cannam@62: inline ListReader(SegmentReader* segment, CapTableReader* capTable, const void* ptr, cannam@62: ListElementCount elementCount, BitsPerElementN<23> step, cannam@62: StructDataBitCount structDataSize, StructPointerCount structPointerCount, cannam@62: ElementSize elementSize, int nestingLimit) cannam@62: : segment(segment), capTable(capTable), ptr(reinterpret_cast(ptr)), cannam@62: elementCount(elementCount), step(step), structDataSize(structDataSize), cannam@62: structPointerCount(structPointerCount), elementSize(elementSize), cannam@62: nestingLimit(nestingLimit) {} cannam@62: cannam@62: friend class StructReader; cannam@62: friend class ListBuilder; cannam@62: friend struct WireHelpers; cannam@62: friend class OrphanBuilder; cannam@62: }; cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: class OrphanBuilder { cannam@62: public: cannam@62: inline OrphanBuilder(): segment(nullptr), capTable(nullptr), location(nullptr) { cannam@62: memset(&tag, 0, sizeof(tag)); cannam@62: } cannam@62: OrphanBuilder(const OrphanBuilder& other) = delete; cannam@62: inline OrphanBuilder(OrphanBuilder&& other) noexcept; cannam@62: inline ~OrphanBuilder() noexcept(false); cannam@62: cannam@62: static OrphanBuilder initStruct(BuilderArena* arena, CapTableBuilder* capTable, StructSize size); cannam@62: static OrphanBuilder initList(BuilderArena* arena, CapTableBuilder* capTable, cannam@62: ElementCount elementCount, ElementSize elementSize); cannam@62: static OrphanBuilder initStructList(BuilderArena* arena, CapTableBuilder* capTable, cannam@62: ElementCount elementCount, StructSize elementSize); cannam@62: static OrphanBuilder initText(BuilderArena* arena, CapTableBuilder* capTable, ByteCount size); cannam@62: static OrphanBuilder initData(BuilderArena* arena, CapTableBuilder* capTable, ByteCount size); cannam@62: cannam@62: static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, StructReader copyFrom); cannam@62: static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, ListReader copyFrom); cannam@62: static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, PointerReader copyFrom); cannam@62: static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, Text::Reader copyFrom); cannam@62: static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, Data::Reader copyFrom); cannam@62: #if !CAPNP_LITE cannam@62: static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, cannam@62: kj::Own copyFrom); cannam@62: #endif // !CAPNP_LITE cannam@62: cannam@62: static OrphanBuilder concat(BuilderArena* arena, CapTableBuilder* capTable, cannam@62: ElementSize expectedElementSize, StructSize expectedStructSize, cannam@62: kj::ArrayPtr lists); cannam@62: cannam@62: static OrphanBuilder referenceExternalData(BuilderArena* arena, Data::Reader data); cannam@62: cannam@62: OrphanBuilder& operator=(const OrphanBuilder& other) = delete; cannam@62: inline OrphanBuilder& operator=(OrphanBuilder&& other); cannam@62: cannam@62: inline bool operator==(decltype(nullptr)) const { return location == nullptr; } cannam@62: inline bool operator!=(decltype(nullptr)) const { return location != nullptr; } cannam@62: cannam@62: StructBuilder asStruct(StructSize size); cannam@62: // Interpret as a struct, or throw an exception if not a struct. cannam@62: cannam@62: ListBuilder asList(ElementSize elementSize); cannam@62: // Interpret as a list, or throw an exception if not a list. elementSize cannot be cannam@62: // INLINE_COMPOSITE -- use asStructList() instead. cannam@62: cannam@62: ListBuilder asStructList(StructSize elementSize); cannam@62: // Interpret as a struct list, or throw an exception if not a list. cannam@62: cannam@62: ListBuilder asListAnySize(); cannam@62: // For AnyList. cannam@62: cannam@62: Text::Builder asText(); cannam@62: Data::Builder asData(); cannam@62: // Interpret as a blob, or throw an exception if not a blob. cannam@62: cannam@62: StructReader asStructReader(StructSize size) const; cannam@62: ListReader asListReader(ElementSize elementSize) const; cannam@62: ListReader asListReaderAnySize() const; cannam@62: #if !CAPNP_LITE cannam@62: kj::Own asCapability() const; cannam@62: #endif // !CAPNP_LITE cannam@62: Text::Reader asTextReader() const; cannam@62: Data::Reader asDataReader() const; cannam@62: cannam@62: bool truncate(ElementCount size, bool isText) KJ_WARN_UNUSED_RESULT; cannam@62: // Resize the orphan list to the given size. Returns false if the list is currently empty but cannam@62: // the requested size is non-zero, in which case the caller will need to allocate a new list. cannam@62: cannam@62: void truncate(ElementCount size, ElementSize elementSize); cannam@62: void truncate(ElementCount size, StructSize elementSize); cannam@62: void truncateText(ElementCount size); cannam@62: // Versions of truncate() that know how to allocate a new list if needed. cannam@62: cannam@62: private: cannam@62: static_assert(ONE * POINTERS * WORDS_PER_POINTER == ONE * WORDS, cannam@62: "This struct assumes a pointer is one word."); cannam@62: word tag; cannam@62: // Contains an encoded WirePointer representing this object. WirePointer is defined in cannam@62: // layout.c++, but fits in a word. cannam@62: // cannam@62: // This may be a FAR pointer. Even in that case, `location` points to the eventual destination cannam@62: // of that far pointer. The reason we keep the far pointer around rather than just making `tag` cannam@62: // represent the final destination is because if the eventual adopter of the pointer is not in cannam@62: // the target's segment then it may be useful to reuse the far pointer landing pad. cannam@62: // cannam@62: // If `tag` is not a far pointer, its offset is garbage; only `location` points to the actual cannam@62: // target. cannam@62: cannam@62: SegmentBuilder* segment; cannam@62: // Segment in which the object resides. cannam@62: cannam@62: CapTableBuilder* capTable; cannam@62: // Table of capability indexes. cannam@62: cannam@62: word* location; cannam@62: // Pointer to the object, or nullptr if the pointer is null. For capabilities, we make this cannam@62: // 0x1 just so that it is non-null for operator==, but it is never used. cannam@62: cannam@62: inline OrphanBuilder(const void* tagPtr, SegmentBuilder* segment, cannam@62: CapTableBuilder* capTable, word* location) cannam@62: : segment(segment), capTable(capTable), location(location) { cannam@62: memcpy(&tag, tagPtr, sizeof(tag)); cannam@62: } cannam@62: cannam@62: inline WirePointer* tagAsPtr() { return reinterpret_cast(&tag); } cannam@62: inline const WirePointer* tagAsPtr() const { return reinterpret_cast(&tag); } cannam@62: cannam@62: void euthanize(); cannam@62: // Erase the target object, zeroing it out and possibly reclaiming the memory. Called when cannam@62: // the OrphanBuilder is being destroyed or overwritten and it is non-null. cannam@62: cannam@62: friend struct WireHelpers; cannam@62: }; cannam@62: cannam@62: // ======================================================================================= cannam@62: // Internal implementation details... cannam@62: cannam@62: // These are defined in the source file. cannam@62: template <> typename Text::Builder PointerBuilder::initBlob(ByteCount size); cannam@62: template <> void PointerBuilder::setBlob(typename Text::Reader value); cannam@62: template <> typename Text::Builder PointerBuilder::getBlob( cannam@62: const void* defaultValue, ByteCount defaultSize); cannam@62: template <> typename Text::Reader PointerReader::getBlob( cannam@62: const void* defaultValue, ByteCount defaultSize) const; cannam@62: cannam@62: template <> typename Data::Builder PointerBuilder::initBlob(ByteCount size); cannam@62: template <> void PointerBuilder::setBlob(typename Data::Reader value); cannam@62: template <> typename Data::Builder PointerBuilder::getBlob( cannam@62: const void* defaultValue, ByteCount defaultSize); cannam@62: template <> typename Data::Reader PointerReader::getBlob( cannam@62: const void* defaultValue, ByteCount defaultSize) const; cannam@62: cannam@62: inline PointerBuilder PointerBuilder::getRoot( cannam@62: SegmentBuilder* segment, CapTableBuilder* capTable, word* location) { cannam@62: return PointerBuilder(segment, capTable, reinterpret_cast(location)); cannam@62: } cannam@62: cannam@62: inline PointerReader PointerReader::getRootUnchecked(const word* location) { cannam@62: return PointerReader(nullptr, nullptr, cannam@62: reinterpret_cast(location), 0x7fffffff); cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: inline kj::ArrayPtr StructBuilder::getDataSectionAsBlob() { cannam@62: return kj::ArrayPtr(reinterpret_cast(data), cannam@62: unbound(dataSize / BITS_PER_BYTE / BYTES)); cannam@62: } cannam@62: cannam@62: inline _::ListBuilder StructBuilder::getPointerSectionAsList() { cannam@62: return _::ListBuilder(segment, capTable, pointers, ONE * POINTERS * BITS_PER_POINTER / ELEMENTS, cannam@62: pointerCount * (ONE * ELEMENTS / POINTERS), cannam@62: ZERO * BITS, ONE * POINTERS, ElementSize::POINTER); cannam@62: } cannam@62: cannam@62: template cannam@62: inline bool StructBuilder::hasDataField(StructDataOffset offset) { cannam@62: return getDataField>(offset) != 0; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline bool StructBuilder::hasDataField(StructDataOffset offset) { cannam@62: return false; cannam@62: } cannam@62: cannam@62: template cannam@62: inline T StructBuilder::getDataField(StructDataOffset offset) { cannam@62: return reinterpret_cast*>(data)[unbound(offset / ELEMENTS)].get(); cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline bool StructBuilder::getDataField(StructDataOffset offset) { cannam@62: BitCount32 boffset = offset * (ONE * BITS / ELEMENTS); cannam@62: byte* b = reinterpret_cast(data) + boffset / BITS_PER_BYTE; cannam@62: return (*reinterpret_cast(b) & cannam@62: unbound(ONE << (boffset % BITS_PER_BYTE / BITS))) != 0; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline Void StructBuilder::getDataField(StructDataOffset offset) { cannam@62: return VOID; cannam@62: } cannam@62: cannam@62: template cannam@62: inline T StructBuilder::getDataField(StructDataOffset offset, Mask mask) { cannam@62: return unmask(getDataField >(offset), mask); cannam@62: } cannam@62: cannam@62: template cannam@62: inline void StructBuilder::setDataField(StructDataOffset offset, kj::NoInfer value) { cannam@62: reinterpret_cast*>(data)[unbound(offset / ELEMENTS)].set(value); cannam@62: } cannam@62: cannam@62: #if CAPNP_CANONICALIZE_NAN cannam@62: // Use mask() on floats and doubles to make sure we canonicalize NaNs. cannam@62: template <> cannam@62: inline void StructBuilder::setDataField(StructDataOffset offset, float value) { cannam@62: setDataField(offset, mask(value, 0)); cannam@62: } cannam@62: template <> cannam@62: inline void StructBuilder::setDataField(StructDataOffset offset, double value) { cannam@62: setDataField(offset, mask(value, 0)); cannam@62: } cannam@62: #endif cannam@62: cannam@62: template <> cannam@62: inline void StructBuilder::setDataField(StructDataOffset offset, bool value) { cannam@62: auto boffset = offset * (ONE * BITS / ELEMENTS); cannam@62: byte* b = reinterpret_cast(data) + boffset / BITS_PER_BYTE; cannam@62: uint bitnum = unboundMaxBits<3>(boffset % BITS_PER_BYTE / BITS); cannam@62: *reinterpret_cast(b) = (*reinterpret_cast(b) & ~(1 << bitnum)) cannam@62: | (static_cast(value) << bitnum); cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline void StructBuilder::setDataField(StructDataOffset offset, Void value) {} cannam@62: cannam@62: template cannam@62: inline void StructBuilder::setDataField(StructDataOffset offset, cannam@62: kj::NoInfer value, Mask m) { cannam@62: setDataField >(offset, mask(value, m)); cannam@62: } cannam@62: cannam@62: inline PointerBuilder StructBuilder::getPointerField(StructPointerOffset ptrIndex) { cannam@62: // Hacky because WirePointer is defined in the .c++ file (so is incomplete here). cannam@62: return PointerBuilder(segment, capTable, reinterpret_cast( cannam@62: reinterpret_cast(pointers) + ptrIndex * WORDS_PER_POINTER)); cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: inline kj::ArrayPtr StructReader::getDataSectionAsBlob() { cannam@62: return kj::ArrayPtr(reinterpret_cast(data), cannam@62: unbound(dataSize / BITS_PER_BYTE / BYTES)); cannam@62: } cannam@62: cannam@62: inline _::ListReader StructReader::getPointerSectionAsList() { cannam@62: return _::ListReader(segment, capTable, pointers, pointerCount * (ONE * ELEMENTS / POINTERS), cannam@62: ONE * POINTERS * BITS_PER_POINTER / ELEMENTS, ZERO * BITS, ONE * POINTERS, cannam@62: ElementSize::POINTER, nestingLimit); cannam@62: } cannam@62: cannam@62: template cannam@62: inline bool StructReader::hasDataField(StructDataOffset offset) const { cannam@62: return getDataField>(offset) != 0; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline bool StructReader::hasDataField(StructDataOffset offset) const { cannam@62: return false; cannam@62: } cannam@62: cannam@62: template cannam@62: inline T StructReader::getDataField(StructDataOffset offset) const { cannam@62: if ((offset + ONE * ELEMENTS) * capnp::bitsPerElement() <= dataSize) { cannam@62: return reinterpret_cast*>(data)[unbound(offset / ELEMENTS)].get(); cannam@62: } else { cannam@62: return static_cast(0); cannam@62: } cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline bool StructReader::getDataField(StructDataOffset offset) const { cannam@62: auto boffset = offset * (ONE * BITS / ELEMENTS); cannam@62: if (boffset < dataSize) { cannam@62: const byte* b = reinterpret_cast(data) + boffset / BITS_PER_BYTE; cannam@62: return (*reinterpret_cast(b) & cannam@62: unbound(ONE << (boffset % BITS_PER_BYTE / BITS))) != 0; cannam@62: } else { cannam@62: return false; cannam@62: } cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline Void StructReader::getDataField(StructDataOffset offset) const { cannam@62: return VOID; cannam@62: } cannam@62: cannam@62: template cannam@62: T StructReader::getDataField(StructDataOffset offset, Mask mask) const { cannam@62: return unmask(getDataField >(offset), mask); cannam@62: } cannam@62: cannam@62: inline PointerReader StructReader::getPointerField(StructPointerOffset ptrIndex) const { cannam@62: if (ptrIndex < pointerCount) { cannam@62: // Hacky because WirePointer is defined in the .c++ file (so is incomplete here). cannam@62: return PointerReader(segment, capTable, reinterpret_cast( cannam@62: reinterpret_cast(pointers) + ptrIndex * WORDS_PER_POINTER), nestingLimit); cannam@62: } else{ cannam@62: return PointerReader(); cannam@62: } cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: inline ListElementCount ListBuilder::size() const { return elementCount; } cannam@62: cannam@62: template cannam@62: inline T ListBuilder::getDataElement(ElementCount index) { cannam@62: return reinterpret_cast*>( cannam@62: ptr + upgradeBound(index) * step / BITS_PER_BYTE)->get(); cannam@62: cannam@62: // TODO(perf): Benchmark this alternate implementation, which I suspect may make better use of cannam@62: // the x86 SIB byte. Also use it for all the other getData/setData implementations below, and cannam@62: // the various non-inline methods that look up pointers. cannam@62: // Also if using this, consider changing ptr back to void* instead of byte*. cannam@62: // return reinterpret_cast*>(ptr)[ cannam@62: // index / ELEMENTS * (step / capnp::bitsPerElement())].get(); cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline bool ListBuilder::getDataElement(ElementCount index) { cannam@62: // Ignore step for bit lists because bit lists cannot be upgraded to struct lists. cannam@62: auto bindex = index * (ONE * BITS / ELEMENTS); cannam@62: byte* b = ptr + bindex / BITS_PER_BYTE; cannam@62: return (*reinterpret_cast(b) & cannam@62: unbound(ONE << (bindex % BITS_PER_BYTE / BITS))) != 0; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline Void ListBuilder::getDataElement(ElementCount index) { cannam@62: return VOID; cannam@62: } cannam@62: cannam@62: template cannam@62: inline void ListBuilder::setDataElement(ElementCount index, kj::NoInfer value) { cannam@62: reinterpret_cast*>( cannam@62: ptr + upgradeBound(index) * step / BITS_PER_BYTE)->set(value); cannam@62: } cannam@62: cannam@62: #if CAPNP_CANONICALIZE_NAN cannam@62: // Use mask() on floats and doubles to make sure we canonicalize NaNs. cannam@62: template <> cannam@62: inline void ListBuilder::setDataElement(ElementCount index, float value) { cannam@62: setDataElement(index, mask(value, 0)); cannam@62: } cannam@62: template <> cannam@62: inline void ListBuilder::setDataElement(ElementCount index, double value) { cannam@62: setDataElement(index, mask(value, 0)); cannam@62: } cannam@62: #endif cannam@62: cannam@62: template <> cannam@62: inline void ListBuilder::setDataElement(ElementCount index, bool value) { cannam@62: // Ignore stepBytes for bit lists because bit lists cannot be upgraded to struct lists. cannam@62: auto bindex = index * (ONE * BITS / ELEMENTS); cannam@62: byte* b = ptr + bindex / BITS_PER_BYTE; cannam@62: auto bitnum = bindex % BITS_PER_BYTE / BITS; cannam@62: *reinterpret_cast(b) = (*reinterpret_cast(b) & ~(1 << unbound(bitnum))) cannam@62: | (static_cast(value) << unbound(bitnum)); cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline void ListBuilder::setDataElement(ElementCount index, Void value) {} cannam@62: cannam@62: inline PointerBuilder ListBuilder::getPointerElement(ElementCount index) { cannam@62: return PointerBuilder(segment, capTable, reinterpret_cast(ptr + cannam@62: upgradeBound(index) * step / BITS_PER_BYTE)); cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: inline ListElementCount ListReader::size() const { return elementCount; } cannam@62: cannam@62: template cannam@62: inline T ListReader::getDataElement(ElementCount index) const { cannam@62: return reinterpret_cast*>( cannam@62: ptr + upgradeBound(index) * step / BITS_PER_BYTE)->get(); cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline bool ListReader::getDataElement(ElementCount index) const { cannam@62: // Ignore step for bit lists because bit lists cannot be upgraded to struct lists. cannam@62: auto bindex = index * (ONE * BITS / ELEMENTS); cannam@62: const byte* b = ptr + bindex / BITS_PER_BYTE; cannam@62: return (*reinterpret_cast(b) & cannam@62: unbound(ONE << (bindex % BITS_PER_BYTE / BITS))) != 0; cannam@62: } cannam@62: cannam@62: template <> cannam@62: inline Void ListReader::getDataElement(ElementCount index) const { cannam@62: return VOID; cannam@62: } cannam@62: cannam@62: inline PointerReader ListReader::getPointerElement(ElementCount index) const { cannam@62: return PointerReader(segment, capTable, reinterpret_cast( cannam@62: ptr + upgradeBound(index) * step / BITS_PER_BYTE), nestingLimit); cannam@62: } cannam@62: cannam@62: // ------------------------------------------------------------------- cannam@62: cannam@62: inline OrphanBuilder::OrphanBuilder(OrphanBuilder&& other) noexcept cannam@62: : segment(other.segment), capTable(other.capTable), location(other.location) { cannam@62: memcpy(&tag, &other.tag, sizeof(tag)); // Needs memcpy to comply with aliasing rules. cannam@62: other.segment = nullptr; cannam@62: other.location = nullptr; cannam@62: } cannam@62: cannam@62: inline OrphanBuilder::~OrphanBuilder() noexcept(false) { cannam@62: if (segment != nullptr) euthanize(); cannam@62: } cannam@62: cannam@62: inline OrphanBuilder& OrphanBuilder::operator=(OrphanBuilder&& other) { cannam@62: // With normal smart pointers, it's important to handle the case where the incoming pointer cannam@62: // is actually transitively owned by this one. In this case, euthanize() would destroy `other` cannam@62: // before we copied it. This isn't possible in the case of `OrphanBuilder` because it only cannam@62: // owns message objects, and `other` is not itself a message object, therefore cannot possibly cannam@62: // be transitively owned by `this`. cannam@62: cannam@62: if (segment != nullptr) euthanize(); cannam@62: segment = other.segment; cannam@62: capTable = other.capTable; cannam@62: location = other.location; cannam@62: memcpy(&tag, &other.tag, sizeof(tag)); // Needs memcpy to comply with aliasing rules. cannam@62: other.segment = nullptr; cannam@62: other.location = nullptr; cannam@62: return *this; cannam@62: } cannam@62: cannam@62: } // namespace _ (private) cannam@62: } // namespace capnp cannam@62: cannam@62: #endif // CAPNP_LAYOUT_H_