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