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