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