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