/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_FLATBUFFER_BUILDER_H_ #define FLATBUFFERS_FLATBUFFER_BUILDER_H_ #include #include #include #include #include #include "flatbuffers/allocator.h" #include "flatbuffers/array.h" #include "flatbuffers/base.h" #include "flatbuffers/buffer.h" #include "flatbuffers/buffer_ref.h" #include "flatbuffers/default_allocator.h" #include "flatbuffers/detached_buffer.h" #include "flatbuffers/stl_emulation.h" #include "flatbuffers/string.h" #include "flatbuffers/struct.h" #include "flatbuffers/table.h" #include "flatbuffers/vector.h" #include "flatbuffers/vector_downward.h" #include "flatbuffers/verifier.h" namespace flatbuffers { // Converts a Field ID to a virtual table offset. inline voffset_t FieldIndexToOffset(voffset_t field_id) { // Should correspond to what EndTable() below builds up. const voffset_t fixed_fields = 2 * sizeof(voffset_t); // Vtable size and Object Size. size_t offset = fixed_fields + field_id * sizeof(voffset_t); FLATBUFFERS_ASSERT(offset < std::numeric_limits::max()); return static_cast(offset);} template> const T *data(const std::vector &v) { // Eventually the returned pointer gets passed down to memcpy, so // we need it to be non-null to avoid undefined behavior. static uint8_t t; return v.empty() ? reinterpret_cast(&t) : &v.front(); } template> T *data(std::vector &v) { // Eventually the returned pointer gets passed down to memcpy, so // we need it to be non-null to avoid undefined behavior. static uint8_t t; return v.empty() ? reinterpret_cast(&t) : &v.front(); } /// @addtogroup flatbuffers_cpp_api /// @{ /// @class FlatBufferBuilder /// @brief Helper class to hold data needed in creation of a FlatBuffer. /// To serialize data, you typically call one of the `Create*()` functions in /// the generated code, which in turn call a sequence of `StartTable`/ /// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/ /// `CreateVector` functions. Do this is depth-first order to build up a tree to /// the root. `Finish()` wraps up the buffer ready for transport. template class FlatBufferBuilderImpl { public: // This switches the size type of the builder, based on if its 64-bit aware // (uoffset64_t) or not (uoffset_t). typedef typename std::conditional::type SizeT; /// @brief Default constructor for FlatBufferBuilder. /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults /// to `1024`. /// @param[in] allocator An `Allocator` to use. If null will use /// `DefaultAllocator`. /// @param[in] own_allocator Whether the builder/vector should own the /// allocator. Defaults to / `false`. /// @param[in] buffer_minalign Force the buffer to be aligned to the given /// minimum alignment upon reallocation. Only needed if you intend to store /// types with custom alignment AND you wish to read the buffer in-place /// directly after creation. explicit FlatBufferBuilderImpl( size_t initial_size = 1024, Allocator *allocator = nullptr, bool own_allocator = false, size_t buffer_minalign = AlignOf()) : buf_(initial_size, allocator, own_allocator, buffer_minalign, static_cast(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE : FLATBUFFERS_MAX_BUFFER_SIZE)), num_field_loc(0), max_voffset_(0), length_of_64_bit_region_(0), nested(false), finished(false), minalign_(1), force_defaults_(false), dedup_vtables_(true), string_pool(nullptr) { EndianCheck(); } /// @brief Move constructor for FlatBufferBuilder. FlatBufferBuilderImpl(FlatBufferBuilderImpl &&other) noexcept : buf_(1024, nullptr, false, AlignOf(), static_cast(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE : FLATBUFFERS_MAX_BUFFER_SIZE)), num_field_loc(0), max_voffset_(0), length_of_64_bit_region_(0), nested(false), finished(false), minalign_(1), force_defaults_(false), dedup_vtables_(true), string_pool(nullptr) { EndianCheck(); // Default construct and swap idiom. // Lack of delegating constructors in vs2010 makes it more verbose than // needed. Swap(other); } /// @brief Move assignment operator for FlatBufferBuilder. FlatBufferBuilderImpl &operator=(FlatBufferBuilderImpl &&other) noexcept { // Move construct a temporary and swap idiom FlatBufferBuilderImpl temp(std::move(other)); Swap(temp); return *this; } void Swap(FlatBufferBuilderImpl &other) { using std::swap; buf_.swap(other.buf_); swap(num_field_loc, other.num_field_loc); swap(max_voffset_, other.max_voffset_); swap(length_of_64_bit_region_, other.length_of_64_bit_region_); swap(nested, other.nested); swap(finished, other.finished); swap(minalign_, other.minalign_); swap(force_defaults_, other.force_defaults_); swap(dedup_vtables_, other.dedup_vtables_); swap(string_pool, other.string_pool); } ~FlatBufferBuilderImpl() { if (string_pool) delete string_pool; } void Reset() { Clear(); // clear builder state buf_.reset(); // deallocate buffer } /// @brief Reset all the state in this FlatBufferBuilder so it can be reused /// to construct another buffer. void Clear() { ClearOffsets(); buf_.clear(); nested = false; finished = false; minalign_ = 1; length_of_64_bit_region_ = 0; if (string_pool) string_pool->clear(); } /// @brief The current size of the serialized buffer, counting from the end. /// @return Returns an `SizeT` with the current size of the buffer. SizeT GetSize() const { return buf_.size(); } /// @brief The current size of the serialized buffer relative to the end of /// the 32-bit region. /// @return Returns an `uoffset_t` with the current size of the buffer. template // Only enable this method for the 64-bit builder, as only that builder is // concerned with the 32/64-bit boundary, and should be the one to bare any // run time costs. typename std::enable_if::type GetSizeRelative32BitRegion() const { //[32-bit region][64-bit region] // [XXXXXXXXXXXXXXXXXXX] GetSize() // [YYYYYYYYYYYYY] length_of_64_bit_region_ // [ZZZZ] return size return static_cast(GetSize() - length_of_64_bit_region_); } template // Only enable this method for the 32-bit builder. typename std::enable_if::type GetSizeRelative32BitRegion() const { return static_cast(GetSize()); } /// @brief Get the serialized buffer (after you call `Finish()`). /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the /// buffer. uint8_t *GetBufferPointer() const { Finished(); return buf_.data(); } /// @brief Get the serialized buffer (after you call `Finish()`) as a span. /// @return Returns a constructed flatbuffers::span that is a view over the /// FlatBuffer data inside the buffer. flatbuffers::span GetBufferSpan() const { Finished(); return flatbuffers::span(buf_.data(), buf_.size()); } /// @brief Get a pointer to an unfinished buffer. /// @return Returns a `uint8_t` pointer to the unfinished buffer. uint8_t *GetCurrentBufferPointer() const { return buf_.data(); } /// @brief Get the released DetachedBuffer. /// @return A `DetachedBuffer` that owns the buffer and its allocator. DetachedBuffer Release() { Finished(); DetachedBuffer buffer = buf_.release(); Clear(); return buffer; } /// @brief Get the released pointer to the serialized buffer. /// @param size The size of the memory block containing /// the serialized `FlatBuffer`. /// @param offset The offset from the released pointer where the finished /// `FlatBuffer` starts. /// @return A raw pointer to the start of the memory block containing /// the serialized `FlatBuffer`. /// @remark If the allocator is owned, it gets deleted when the destructor is /// called. uint8_t *ReleaseRaw(size_t &size, size_t &offset) { Finished(); uint8_t* raw = buf_.release_raw(size, offset); Clear(); return raw; } /// @brief get the minimum alignment this buffer needs to be accessed /// properly. This is only known once all elements have been written (after /// you call Finish()). You can use this information if you need to embed /// a FlatBuffer in some other buffer, such that you can later read it /// without first having to copy it into its own buffer. size_t GetBufferMinAlignment() const { Finished(); return minalign_; } /// @cond FLATBUFFERS_INTERNAL void Finished() const { // If you get this assert, you're attempting to get access a buffer // which hasn't been finished yet. Be sure to call // FlatBufferBuilder::Finish with your root table. // If you really need to access an unfinished buffer, call // GetCurrentBufferPointer instead. FLATBUFFERS_ASSERT(finished); } /// @endcond /// @brief In order to save space, fields that are set to their default value /// don't get serialized into the buffer. /// @param[in] fd When set to `true`, always serializes default values that /// are set. Optional fields which are not set explicitly, will still not be /// serialized. void ForceDefaults(bool fd) { force_defaults_ = fd; } /// @brief By default vtables are deduped in order to save space. /// @param[in] dedup When set to `true`, dedup vtables. void DedupVtables(bool dedup) { dedup_vtables_ = dedup; } /// @cond FLATBUFFERS_INTERNAL void Pad(size_t num_bytes) { buf_.fill(num_bytes); } void TrackMinAlign(size_t elem_size) { if (elem_size > minalign_) minalign_ = elem_size; } void Align(size_t elem_size) { TrackMinAlign(elem_size); buf_.fill(PaddingBytes(buf_.size(), elem_size)); } void PushFlatBuffer(const uint8_t *bytes, size_t size) { PushBytes(bytes, size); finished = true; } void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); } void PopBytes(size_t amount) { buf_.pop(amount); } template void AssertScalarT() { // The code assumes power of 2 sizes and endian-swap-ability. static_assert(flatbuffers::is_scalar::value, "T must be a scalar type"); } // Write a single aligned scalar to the buffer template ReturnT PushElement(T element) { AssertScalarT(); Align(sizeof(T)); buf_.push_small(EndianScalar(element)); return CalculateOffset(); } template class OffsetT = Offset> uoffset_t PushElement(OffsetT off) { // Special case for offsets: see ReferTo below. return PushElement(ReferTo(off.o)); } // When writing fields, we track where they are, so we can create correct // vtables later. void TrackField(voffset_t field, uoffset_t off) { FieldLoc fl = { off, field }; buf_.scratch_push_small(fl); num_field_loc++; if (field > max_voffset_) { max_voffset_ = field; } } // Like PushElement, but additionally tracks the field this represents. template void AddElement(voffset_t field, T e, T def) { // We don't serialize values equal to the default. if (IsTheSameAs(e, def) && !force_defaults_) return; TrackField(field, PushElement(e)); } template void AddElement(voffset_t field, T e) { TrackField(field, PushElement(e)); } template void AddOffset(voffset_t field, Offset off) { if (off.IsNull()) return; // Don't store. AddElement(field, ReferTo(off.o), static_cast(0)); } template void AddOffset(voffset_t field, Offset64 off) { if (off.IsNull()) return; // Don't store. AddElement(field, ReferTo(off.o), static_cast(0)); } template void AddStruct(voffset_t field, const T *structptr) { if (!structptr) return; // Default, don't store. Align(AlignOf()); buf_.push_small(*structptr); TrackField(field, CalculateOffset()); } void AddStructOffset(voffset_t field, uoffset_t off) { TrackField(field, off); } // Offsets initially are relative to the end of the buffer (downwards). // This function converts them to be relative to the current location // in the buffer (when stored here), pointing upwards. uoffset_t ReferTo(uoffset_t off) { // Align to ensure GetSizeRelative32BitRegion() below is correct. Align(sizeof(uoffset_t)); // 32-bit offsets are relative to the tail of the 32-bit region of the // buffer. For most cases (without 64-bit entities) this is equivalent to // size of the whole buffer (e.g. GetSize()) return ReferTo(off, GetSizeRelative32BitRegion()); } uoffset64_t ReferTo(uoffset64_t off) { // Align to ensure GetSize() below is correct. Align(sizeof(uoffset64_t)); // 64-bit offsets are relative to tail of the whole buffer return ReferTo(off, GetSize()); } template T ReferTo(const T off, const T2 size) { FLATBUFFERS_ASSERT(off && off <= size); return size - off + static_cast(sizeof(T)); } template T ReferTo(const T off, const T size) { FLATBUFFERS_ASSERT(off && off <= size); return size - off + static_cast(sizeof(T)); } void NotNested() { // If you hit this, you're trying to construct a Table/Vector/String // during the construction of its parent table (between the MyTableBuilder // and table.Finish(). // Move the creation of these sub-objects to above the MyTableBuilder to // not get this assert. // Ignoring this assert may appear to work in simple cases, but the reason // it is here is that storing objects in-line may cause vtable offsets // to not fit anymore. It also leads to vtable duplication. FLATBUFFERS_ASSERT(!nested); // If you hit this, fields were added outside the scope of a table. FLATBUFFERS_ASSERT(!num_field_loc); } // From generated code (or from the parser), we call StartTable/EndTable // with a sequence of AddElement calls in between. uoffset_t StartTable() { NotNested(); nested = true; return GetSizeRelative32BitRegion(); } // This finishes one serialized object by generating the vtable if it's a // table, comparing it against existing vtables, and writing the // resulting vtable offset. uoffset_t EndTable(uoffset_t start) { // If you get this assert, a corresponding StartTable wasn't called. FLATBUFFERS_ASSERT(nested); // Write the vtable offset, which is the start of any Table. // We fill its value later. // This is relative to the end of the 32-bit region. const uoffset_t vtable_offset_loc = static_cast(PushElement(0)); // Write a vtable, which consists entirely of voffset_t elements. // It starts with the number of offsets, followed by a type id, followed // by the offsets themselves. In reverse: // Include space for the last offset and ensure empty tables have a // minimum size. max_voffset_ = (std::max)(static_cast(max_voffset_ + sizeof(voffset_t)), FieldIndexToOffset(0)); buf_.fill_big(max_voffset_); const uoffset_t table_object_size = vtable_offset_loc - start; // Vtable use 16bit offsets. FLATBUFFERS_ASSERT(table_object_size < 0x10000); WriteScalar(buf_.data() + sizeof(voffset_t), static_cast(table_object_size)); WriteScalar(buf_.data(), max_voffset_); // Write the offsets into the table for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc); it < buf_.scratch_end(); it += sizeof(FieldLoc)) { auto field_location = reinterpret_cast(it); const voffset_t pos = static_cast(vtable_offset_loc - field_location->off); // If this asserts, it means you've set a field twice. FLATBUFFERS_ASSERT( !ReadScalar(buf_.data() + field_location->id)); WriteScalar(buf_.data() + field_location->id, pos); } ClearOffsets(); auto vt1 = reinterpret_cast(buf_.data()); auto vt1_size = ReadScalar(vt1); auto vt_use = GetSizeRelative32BitRegion(); // See if we already have generated a vtable with this exact same // layout before. If so, make it point to the old one, remove this one. if (dedup_vtables_) { for (auto it = buf_.scratch_data(); it < buf_.scratch_end(); it += sizeof(uoffset_t)) { auto vt_offset_ptr = reinterpret_cast(it); auto vt2 = reinterpret_cast(buf_.data_at(*vt_offset_ptr)); auto vt2_size = ReadScalar(vt2); if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue; vt_use = *vt_offset_ptr; buf_.pop(GetSizeRelative32BitRegion() - vtable_offset_loc); break; } } // If this is a new vtable, remember it. if (vt_use == GetSizeRelative32BitRegion()) { buf_.scratch_push_small(vt_use); } // Fill the vtable offset we created above. // The offset points from the beginning of the object to where the vtable is // stored. // Offsets default direction is downward in memory for future format // flexibility (storing all vtables at the start of the file). WriteScalar(buf_.data_at(vtable_offset_loc + length_of_64_bit_region_), static_cast(vt_use) - static_cast(vtable_offset_loc)); nested = false; return vtable_offset_loc; } FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]]) uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) { return EndTable(start); } // This checks a required field has been set in a given table that has // just been constructed. template void Required(Offset table, voffset_t field) { auto table_ptr = reinterpret_cast(buf_.data_at(table.o)); bool ok = table_ptr->GetOptionalFieldOffset(field) != 0; // If this fails, the caller will show what field needs to be set. FLATBUFFERS_ASSERT(ok); (void)ok; } uoffset_t StartStruct(size_t alignment) { Align(alignment); return GetSizeRelative32BitRegion(); } uoffset_t EndStruct() { return GetSizeRelative32BitRegion(); } void ClearOffsets() { buf_.scratch_pop(num_field_loc * sizeof(FieldLoc)); num_field_loc = 0; max_voffset_ = 0; } // Aligns such that when "len" bytes are written, an object can be written // after it (forward in the buffer) with "alignment" without padding. void PreAlign(size_t len, size_t alignment) { if (len == 0) return; TrackMinAlign(alignment); buf_.fill(PaddingBytes(GetSize() + len, alignment)); } // Aligns such than when "len" bytes are written, an object of type `AlignT` // can be written after it (forward in the buffer) without padding. template void PreAlign(size_t len) { AssertScalarT(); PreAlign(len, AlignOf()); } /// @endcond /// @brief Store a string in the buffer, which can contain any binary data. /// @param[in] str A const char pointer to the data to be stored as a string. /// @param[in] len The number of bytes that should be stored from `str`. /// @return Returns the offset in the buffer where the string starts. template class OffsetT = Offset> OffsetT CreateString(const char *str, size_t len) { CreateStringImpl(str, len); return OffsetT( CalculateOffset::offset_type>()); } /// @brief Store a string in the buffer, which is null-terminated. /// @param[in] str A const char pointer to a C-string to add to the buffer. /// @return Returns the offset in the buffer where the string starts. template class OffsetT = Offset> OffsetT CreateString(const char *str) { return CreateString(str, strlen(str)); } /// @brief Store a string in the buffer, which is null-terminated. /// @param[in] str A char pointer to a C-string to add to the buffer. /// @return Returns the offset in the buffer where the string starts. template class OffsetT = Offset> OffsetT CreateString(char *str) { return CreateString(str, strlen(str)); } /// @brief Store a string in the buffer, which can contain any binary data. /// @param[in] str A const reference to a std::string to store in the buffer. /// @return Returns the offset in the buffer where the string starts. template class OffsetT = Offset> OffsetT CreateString(const std::string &str) { return CreateString(str.c_str(), str.length()); } // clang-format off #ifdef FLATBUFFERS_HAS_STRING_VIEW /// @brief Store a string in the buffer, which can contain any binary data. /// @param[in] str A const string_view to copy in to the buffer. /// @return Returns the offset in the buffer where the string starts. template