Chris@64: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@64: // Licensed under the MIT License: Chris@64: // Chris@64: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@64: // of this software and associated documentation files (the "Software"), to deal Chris@64: // in the Software without restriction, including without limitation the rights Chris@64: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@64: // copies of the Software, and to permit persons to whom the Software is Chris@64: // furnished to do so, subject to the following conditions: Chris@64: // Chris@64: // The above copyright notice and this permission notice shall be included in Chris@64: // all copies or substantial portions of the Software. Chris@64: // Chris@64: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@64: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@64: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@64: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@64: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@64: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@64: // THE SOFTWARE. Chris@64: Chris@64: #ifndef CAPNP_ORPHAN_H_ Chris@64: #define CAPNP_ORPHAN_H_ Chris@64: Chris@64: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) Chris@64: #pragma GCC system_header Chris@64: #endif Chris@64: Chris@64: #include "layout.h" Chris@64: Chris@64: namespace capnp { Chris@64: Chris@64: class StructSchema; Chris@64: class ListSchema; Chris@64: struct DynamicStruct; Chris@64: struct DynamicList; Chris@64: namespace _ { struct OrphanageInternal; } Chris@64: Chris@64: template Chris@64: class Orphan { Chris@64: // Represents an object which is allocated within some message builder but has no pointers Chris@64: // pointing at it. An Orphan can later be "adopted" by some other object as one of that object's Chris@64: // fields, without having to copy the orphan. For a field `foo` of pointer type, the generated Chris@64: // code will define builder methods `void adoptFoo(Orphan)` and `Orphan disownFoo()`. Chris@64: // Orphans can also be created independently of any parent using an Orphanage. Chris@64: // Chris@64: // `Orphan` can be moved but not copied, like `Own`, so that it is impossible for one Chris@64: // orphan to be adopted multiple times. If an orphan is destroyed without being adopted, its Chris@64: // contents are zero'd out (and possibly reused, if we ever implement the ability to reuse space Chris@64: // in a message arena). Chris@64: Chris@64: public: Chris@64: Orphan() = default; Chris@64: KJ_DISALLOW_COPY(Orphan); Chris@64: Orphan(Orphan&&) = default; Chris@64: Orphan& operator=(Orphan&&) = default; Chris@64: inline Orphan(_::OrphanBuilder&& builder): builder(kj::mv(builder)) {} Chris@64: Chris@64: inline BuilderFor get(); Chris@64: // Get the underlying builder. If the orphan is null, this will allocate and return a default Chris@64: // object rather than crash. This is done for security -- otherwise, you might enable a DoS Chris@64: // attack any time you disown a field and fail to check if it is null. In the case of structs, Chris@64: // this means that the orphan is no longer null after get() returns. In the case of lists, Chris@64: // no actual object is allocated since a simple empty ListBuilder can be returned. Chris@64: Chris@64: inline ReaderFor getReader() const; Chris@64: Chris@64: inline bool operator==(decltype(nullptr)) const { return builder == nullptr; } Chris@64: inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; } Chris@64: Chris@64: inline void truncate(uint size); Chris@64: // Resize an object (which must be a list or a blob) to the given size. Chris@64: // Chris@64: // If the new size is less than the original, the remaining elements will be discarded. The Chris@64: // list is never moved in this case. If the list happens to be located at the end of its segment Chris@64: // (which is always true if the list was the last thing allocated), the removed memory will be Chris@64: // reclaimed (reducing the messag size), otherwise it is simply zeroed. The reclaiming behavior Chris@64: // is particularly useful for allocating buffer space when you aren't sure how much space you Chris@64: // actually need: you can pre-allocate, say, a 4k byte array, read() from a file into it, and Chris@64: // then truncate it back to the amount of space actually used. Chris@64: // Chris@64: // If the new size is greater than the original, the list is extended with default values. If Chris@64: // the list is the last object in its segment *and* there is enough space left in the segment to Chris@64: // extend it to cover the new values, then the list is extended in-place. Otherwise, it must be Chris@64: // moved to a new location, leaving a zero'd hole in the previous space that won't be filled. Chris@64: // This copy is shallow; sub-objects will simply be reparented, not copied. Chris@64: // Chris@64: // Any existing readers or builders pointing at the object are invalidated by this call (even if Chris@64: // it doesn't move). You must call `get()` or `getReader()` again to get the new, valid pointer. Chris@64: Chris@64: private: Chris@64: _::OrphanBuilder builder; Chris@64: Chris@64: template Chris@64: friend struct _::PointerHelpers; Chris@64: template Chris@64: friend struct List; Chris@64: template Chris@64: friend class Orphan; Chris@64: friend class Orphanage; Chris@64: friend class MessageBuilder; Chris@64: }; Chris@64: Chris@64: class Orphanage: private kj::DisallowConstCopy { Chris@64: // Use to directly allocate Orphan objects, without having a parent object allocate and then Chris@64: // disown the object. Chris@64: Chris@64: public: Chris@64: inline Orphanage(): arena(nullptr) {} Chris@64: Chris@64: template Chris@64: static Orphanage getForMessageContaining(BuilderType builder); Chris@64: // Construct an Orphanage that allocates within the message containing the given Builder. This Chris@64: // allows the constructed Orphans to be adopted by objects within said message. Chris@64: // Chris@64: // This constructor takes the builder rather than having the builder have a getOrphanage() method Chris@64: // because this is an advanced feature and we don't want to pollute the builder APIs with it. Chris@64: // Chris@64: // Note that if you have a direct pointer to the `MessageBuilder`, you can simply call its Chris@64: // `getOrphanage()` method. Chris@64: Chris@64: template Chris@64: Orphan newOrphan() const; Chris@64: // Allocate a new orphaned struct. Chris@64: Chris@64: template Chris@64: Orphan newOrphan(uint size) const; Chris@64: // Allocate a new orphaned list or blob. Chris@64: Chris@64: Orphan newOrphan(StructSchema schema) const; Chris@64: // Dynamically create an orphan struct with the given schema. You must Chris@64: // #include to use this. Chris@64: Chris@64: Orphan newOrphan(ListSchema schema, uint size) const; Chris@64: // Dynamically create an orphan list with the given schema. You must #include Chris@64: // to use this. Chris@64: Chris@64: template Chris@64: Orphan> newOrphanCopy(Reader copyFrom) const; Chris@64: // Allocate a new orphaned object (struct, list, or blob) and initialize it as a copy of the Chris@64: // given object. Chris@64: Chris@64: template Chris@64: Orphan>>> newOrphanConcat(kj::ArrayPtr lists) const; Chris@64: template Chris@64: Orphan>>> newOrphanConcat(kj::ArrayPtr lists) const; Chris@64: // Given an array of List readers, copy and concatenate the lists, creating a new Orphan. Chris@64: // Chris@64: // Note that compared to allocating the list yourself and using `setWithCaveats()` to set each Chris@64: // item, this method avoids the "caveats": the new list will be allocated with the element size Chris@64: // being the maximum of that from all the input lists. This is particularly important when Chris@64: // concatenating struct lists: if the lists were created using a newer version of the protocol Chris@64: // in which some new fields had been added to the struct, using `setWithCaveats()` would Chris@64: // truncate off those new fields. Chris@64: Chris@64: Orphan referenceExternalData(Data::Reader data) const; Chris@64: // Creates an Orphan that points at an existing region of memory (e.g. from another message) Chris@64: // without copying it. There are some SEVERE restrictions on how this can be used: Chris@64: // - The memory must remain valid until the `MessageBuilder` is destroyed (even if the orphan is Chris@64: // abandoned). Chris@64: // - Because the data is const, you will not be allowed to obtain a `Data::Builder` Chris@64: // for this blob. Any call which would return such a builder will throw an exception. You Chris@64: // can, however, obtain a Reader, e.g. via orphan.getReader() or from a parent Reader (once Chris@64: // the orphan is adopted). It is your responsibility to make sure your code can deal with Chris@64: // these problems when using this optimization; if you can't, allocate a copy instead. Chris@64: // - `data.begin()` must be aligned to a machine word boundary (32-bit or 64-bit depending on Chris@64: // the CPU). Any pointer returned by malloc() as well as any data blob obtained from another Chris@64: // Cap'n Proto message satisfies this. Chris@64: // - If `data.size()` is not a multiple of 8, extra bytes past data.end() up until the next 8-byte Chris@64: // boundary will be visible in the raw message when it is written out. Thus, there must be no Chris@64: // secrets in these bytes. Data blobs obtained from other Cap'n Proto messages should be safe Chris@64: // as these bytes should be zero (unless the sender had the same problem). Chris@64: // Chris@64: // The array will actually become one of the message's segments. The data can thus be adopted Chris@64: // into the message tree without copying it. This is particularly useful when referencing very Chris@64: // large blobs, such as whole mmap'd files. Chris@64: Chris@64: private: Chris@64: _::BuilderArena* arena; Chris@64: _::CapTableBuilder* capTable; Chris@64: Chris@64: inline explicit Orphanage(_::BuilderArena* arena, _::CapTableBuilder* capTable) Chris@64: : arena(arena), capTable(capTable) {} Chris@64: Chris@64: template Chris@64: struct GetInnerBuilder; Chris@64: template Chris@64: struct GetInnerReader; Chris@64: template Chris@64: struct NewOrphanListImpl; Chris@64: Chris@64: friend class MessageBuilder; Chris@64: friend struct _::OrphanageInternal; Chris@64: }; Chris@64: Chris@64: // ======================================================================================= Chris@64: // Inline implementation details. Chris@64: Chris@64: namespace _ { // private Chris@64: Chris@64: template Chris@64: struct OrphanGetImpl; Chris@64: Chris@64: template Chris@64: struct OrphanGetImpl { Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, _::elementSizeForType()); Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: struct OrphanGetImpl { Chris@64: static inline typename T::Builder apply(_::OrphanBuilder& builder) { Chris@64: return typename T::Builder(builder.asStruct(_::structSize())); Chris@64: } Chris@64: static inline typename T::Reader applyReader(const _::OrphanBuilder& builder) { Chris@64: return typename T::Reader(builder.asStructReader(_::structSize())); Chris@64: } Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, _::structSize()); Chris@64: } Chris@64: }; Chris@64: Chris@64: #if !CAPNP_LITE Chris@64: template Chris@64: struct OrphanGetImpl { Chris@64: static inline typename T::Client apply(_::OrphanBuilder& builder) { Chris@64: return typename T::Client(builder.asCapability()); Chris@64: } Chris@64: static inline typename T::Client applyReader(const _::OrphanBuilder& builder) { Chris@64: return typename T::Client(builder.asCapability()); Chris@64: } Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, ElementSize::POINTER); Chris@64: } Chris@64: }; Chris@64: #endif // !CAPNP_LITE Chris@64: Chris@64: template Chris@64: struct OrphanGetImpl, Kind::LIST> { Chris@64: static inline typename List::Builder apply(_::OrphanBuilder& builder) { Chris@64: return typename List::Builder(builder.asList(_::ElementSizeForType::value)); Chris@64: } Chris@64: static inline typename List::Reader applyReader(const _::OrphanBuilder& builder) { Chris@64: return typename List::Reader(builder.asListReader(_::ElementSizeForType::value)); Chris@64: } Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, ElementSize::POINTER); Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: struct OrphanGetImpl, Kind::LIST> { Chris@64: static inline typename List::Builder apply(_::OrphanBuilder& builder) { Chris@64: return typename List::Builder(builder.asStructList(_::structSize())); Chris@64: } Chris@64: static inline typename List::Reader applyReader(const _::OrphanBuilder& builder) { Chris@64: return typename List::Reader(builder.asListReader(_::ElementSizeForType::value)); Chris@64: } Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, ElementSize::POINTER); Chris@64: } Chris@64: }; Chris@64: Chris@64: template <> Chris@64: struct OrphanGetImpl { Chris@64: static inline Text::Builder apply(_::OrphanBuilder& builder) { Chris@64: return Text::Builder(builder.asText()); Chris@64: } Chris@64: static inline Text::Reader applyReader(const _::OrphanBuilder& builder) { Chris@64: return Text::Reader(builder.asTextReader()); Chris@64: } Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, ElementSize::POINTER); Chris@64: } Chris@64: }; Chris@64: Chris@64: template <> Chris@64: struct OrphanGetImpl { Chris@64: static inline Data::Builder apply(_::OrphanBuilder& builder) { Chris@64: return Data::Builder(builder.asData()); Chris@64: } Chris@64: static inline Data::Reader applyReader(const _::OrphanBuilder& builder) { Chris@64: return Data::Reader(builder.asDataReader()); Chris@64: } Chris@64: static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { Chris@64: builder.truncate(size, ElementSize::POINTER); Chris@64: } Chris@64: }; Chris@64: Chris@64: struct OrphanageInternal { Chris@64: static inline _::BuilderArena* getArena(Orphanage orphanage) { return orphanage.arena; } Chris@64: static inline _::CapTableBuilder* getCapTable(Orphanage orphanage) { return orphanage.capTable; } Chris@64: }; Chris@64: Chris@64: } // namespace _ (private) Chris@64: Chris@64: template Chris@64: inline BuilderFor Orphan::get() { Chris@64: return _::OrphanGetImpl::apply(builder); Chris@64: } Chris@64: Chris@64: template Chris@64: inline ReaderFor Orphan::getReader() const { Chris@64: return _::OrphanGetImpl::applyReader(builder); Chris@64: } Chris@64: Chris@64: template Chris@64: inline void Orphan::truncate(uint size) { Chris@64: _::OrphanGetImpl>::truncateListOf(builder, bounded(size) * ELEMENTS); Chris@64: } Chris@64: Chris@64: template <> Chris@64: inline void Orphan::truncate(uint size) { Chris@64: builder.truncateText(bounded(size) * ELEMENTS); Chris@64: } Chris@64: Chris@64: template <> Chris@64: inline void Orphan::truncate(uint size) { Chris@64: builder.truncate(bounded(size) * ELEMENTS, ElementSize::BYTE); Chris@64: } Chris@64: Chris@64: template Chris@64: struct Orphanage::GetInnerBuilder { Chris@64: static inline _::StructBuilder apply(typename T::Builder& t) { Chris@64: return t._builder; Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: struct Orphanage::GetInnerBuilder { Chris@64: static inline _::ListBuilder apply(typename T::Builder& t) { Chris@64: return t.builder; Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: Orphanage Orphanage::getForMessageContaining(BuilderType builder) { Chris@64: auto inner = GetInnerBuilder>::apply(builder); Chris@64: return Orphanage(inner.getArena(), inner.getCapTable()); Chris@64: } Chris@64: Chris@64: template Chris@64: Orphan Orphanage::newOrphan() const { Chris@64: return Orphan(_::OrphanBuilder::initStruct(arena, capTable, _::structSize())); Chris@64: } Chris@64: Chris@64: template Chris@64: struct Orphanage::NewOrphanListImpl> { Chris@64: static inline _::OrphanBuilder apply( Chris@64: _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { Chris@64: return _::OrphanBuilder::initList( Chris@64: arena, capTable, bounded(size) * ELEMENTS, _::ElementSizeForType::value); Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: struct Orphanage::NewOrphanListImpl> { Chris@64: static inline _::OrphanBuilder apply( Chris@64: _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { Chris@64: return _::OrphanBuilder::initStructList( Chris@64: arena, capTable, bounded(size) * ELEMENTS, _::structSize()); Chris@64: } Chris@64: }; Chris@64: Chris@64: template <> Chris@64: struct Orphanage::NewOrphanListImpl { Chris@64: static inline _::OrphanBuilder apply( Chris@64: _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { Chris@64: return _::OrphanBuilder::initText(arena, capTable, bounded(size) * BYTES); Chris@64: } Chris@64: }; Chris@64: Chris@64: template <> Chris@64: struct Orphanage::NewOrphanListImpl { Chris@64: static inline _::OrphanBuilder apply( Chris@64: _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { Chris@64: return _::OrphanBuilder::initData(arena, capTable, bounded(size) * BYTES); Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: Orphan Orphanage::newOrphan(uint size) const { Chris@64: return Orphan(NewOrphanListImpl::apply(arena, capTable, size)); Chris@64: } Chris@64: Chris@64: template Chris@64: struct Orphanage::GetInnerReader { Chris@64: static inline _::StructReader apply(const typename T::Reader& t) { Chris@64: return t._reader; Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: struct Orphanage::GetInnerReader { Chris@64: static inline _::ListReader apply(const typename T::Reader& t) { Chris@64: return t.reader; Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: struct Orphanage::GetInnerReader { Chris@64: static inline const typename T::Reader& apply(const typename T::Reader& t) { Chris@64: return t; Chris@64: } Chris@64: }; Chris@64: Chris@64: template Chris@64: inline Orphan> Orphanage::newOrphanCopy(Reader copyFrom) const { Chris@64: return Orphan>(_::OrphanBuilder::copy( Chris@64: arena, capTable, GetInnerReader>::apply(copyFrom))); Chris@64: } Chris@64: Chris@64: template Chris@64: inline Orphan>>> Chris@64: Orphanage::newOrphanConcat(kj::ArrayPtr lists) const { Chris@64: return newOrphanConcat(kj::implicitCast>(lists)); Chris@64: } Chris@64: template Chris@64: inline Orphan>>> Chris@64: Orphanage::newOrphanConcat(kj::ArrayPtr lists) const { Chris@64: // Optimization / simplification: Rely on List::Reader containing nothing except a Chris@64: // _::ListReader. Chris@64: static_assert(sizeof(T) == sizeof(_::ListReader), "lists are not bare readers?"); Chris@64: kj::ArrayPtr raw( Chris@64: reinterpret_cast(lists.begin()), lists.size()); Chris@64: typedef ListElementType> Element; Chris@64: return Orphan>( Chris@64: _::OrphanBuilder::concat(arena, capTable, Chris@64: _::elementSizeForType(), Chris@64: _::minStructSizeForElement(), raw)); Chris@64: } Chris@64: Chris@64: inline Orphan Orphanage::referenceExternalData(Data::Reader data) const { Chris@64: return Orphan(_::OrphanBuilder::referenceExternalData(arena, data)); Chris@64: } Chris@64: Chris@64: } // namespace capnp Chris@64: Chris@64: #endif // CAPNP_ORPHAN_H_