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