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