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