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