blob: ff81c9af0a8940899e6e7daa9abce4459ac34cfb [file] [log] [blame]
James Kuszmaulf5eb4682023-09-22 17:16:59 -07001#ifndef AOS_FLATBUFFERS_BASE_H_
2#define AOS_FLATBUFFERS_BASE_H_
Stephan Pleines6191f1d2024-05-30 20:44:45 -07003#include <stdint.h>
4#include <sys/types.h>
5
6#include <cstring>
James Kuszmaulf5eb4682023-09-22 17:16:59 -07007#include <memory>
8#include <optional>
Stephan Pleines6191f1d2024-05-30 20:44:45 -07009#include <ostream>
James Kuszmaulf5eb4682023-09-22 17:16:59 -070010#include <span>
Stephan Pleines6191f1d2024-05-30 20:44:45 -070011#include <utility>
12#include <vector>
James Kuszmaulf5eb4682023-09-22 17:16:59 -070013
14#include "flatbuffers/base.h"
15#include "glog/logging.h"
Stephan Pleines6191f1d2024-05-30 20:44:45 -070016
James Kuszmaulf5eb4682023-09-22 17:16:59 -070017namespace aos::fbs {
18using ::flatbuffers::soffset_t;
19using ::flatbuffers::uoffset_t;
20using ::flatbuffers::voffset_t;
21
22// Returns the smallest multiple of alignment that is greater than or equal to
23// size.
24constexpr size_t PaddedSize(size_t size, size_t alignment) {
25 // We can be clever with bitwise operations by assuming that aligment is a
26 // power of two. Or we can just be clearer about what we mean and eat a few
27 // integer divides.
28 return (((size - 1) / alignment) + 1) * alignment;
29}
30
31// Used as a parameter to methods where we are messing with memory and may or
32// may not want to clear it to zeroes.
33enum class SetZero { kYes, kNo };
34
35class Allocator;
36
37// Parent type of any object that may need to dynamically change size at
38// runtime. Used by the static table and vector types to request additional
39// blocks of memory when needed.
40//
41// The way that this works is that every ResizeableObject has some number of
42// children that are themselves ResizeableObject's and whose memory is entirely
43// contained within their parent's memory. A ResizeableObject without a parent
44// instead has an Allocator that it can use to allocate additional blocks
45// of memory. Whenever a child needs to grow in size, it will make a call to
46// InsertBytes() on its parent, which will percolate up until InsertBytes() gets
47// called on the root allocator. If the insert succeeds, then every single child
48// through the entire tree will get notified (this is because the allocator may
49// have shifted the entire memory buffer, so any pointers may need to be
50// updated). Child types will provide implementations of the GetObjects() method
51// to both allow tree traversal as well as to allow the various internal offsets
52// to be updated appropriately.
53class ResizeableObject {
54 public:
55 // Returns the underlying memory buffer into which the flatbuffer will be
56 // serialized.
57 std::span<uint8_t> buffer() { return buffer_; }
58 std::span<const uint8_t> buffer() const { return buffer_; }
59
60 // Updates the underlying memory buffer to new_buffer, with an indication of
61 // where bytes were inserted/removed from the buffer. It is assumed that
62 // new_buffer already has the state of the serialized flatbuffer
63 // copied into it.
64 // * When bytes have been inserted, modification_point will point to the first
65 // of the inserted bytes in new_buffer and bytes_inserted will be the number
66 // of new bytes.
67 // * Buffer shrinkage is not currently supported.
68 // * When bytes_inserted is zero, modification_point is ignored.
69 void UpdateBuffer(std::span<uint8_t> new_buffer, void *modification_point,
70 ssize_t bytes_inserted);
71
72 protected:
73 // Data associated with a sub-object of this object.
74 struct SubObject {
75 // A direct pointer to the inline entry in the flatbuffer table data. The
76 // pointer must be valid, but the entry itself may be zero if the object is
77 // not actually populated.
78 // If *inline_entry is non-zero, this will get updated if any new memory got
79 // added/removed in-between inline_entry and the actual data pointed to be
80 // inline_entry.
81 uoffset_t *inline_entry;
82 // The actual child object. Should be nullptr if *inline_entry is zero; must
83 // be valid if *inline_entry is non-zero.
84 ResizeableObject *object;
85 // The nominal offset from buffer_.data() to object->buffer_.data().
86 // Must be provided, and must always be valid, even if *inline_entry is
87 // zero.
88 // I.e., the following holds when object is not nullptr:
89 // SubObject object = parent.GetSubObject(index);
90 // CHECK_EQ(parent.buffer()->data() + *object.absolute_offset,
91 // object.object->buffer().data());
92 size_t *absolute_offset;
93 };
94
95 ResizeableObject(std::span<uint8_t> buffer, ResizeableObject *parent)
96 : buffer_(buffer), parent_(parent) {}
97 ResizeableObject(std::span<uint8_t> buffer, Allocator *allocator)
98 : buffer_(buffer), allocator_(allocator) {}
99 ResizeableObject(std::span<uint8_t> buffer,
100 std::unique_ptr<Allocator> allocator)
101 : buffer_(buffer),
102 owned_allocator_(std::move(allocator)),
103 allocator_(owned_allocator_.get()) {}
104 ResizeableObject(const ResizeableObject &) = delete;
105 ResizeableObject &operator=(const ResizeableObject &) = delete;
106 // Users do not end up using the move constructor; however, it is needed to
107 // handle the fact that a ResizeableObject may be a member of an std::vector
108 // in the various generated types.
James Kuszmauld4b4f1d2024-03-13 15:57:35 -0700109 ResizeableObject(ResizeableObject &&other);
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700110 // Required alignment of this object.
111 virtual size_t Alignment() const = 0;
112 // Offset from the start of buffer() to the actual start of the object in
113 // question (this is important for vectors, where the vector itself cannot
114 // have internal padding, and so the start of the vector may be offset from
115 // the start of the buffer to handle alignment).
116 virtual size_t AbsoluteOffsetOffset() const = 0;
117 // Causes bytes bytes to be inserted between insertion_point - 1 and
118 // insertion_point.
119 // If requested, the new bytes will be cleared to zero; otherwise they will be
120 // left uninitialized.
121 // The insertion_point may not be equal to this->buffer_.data(); it may be a
122 // pointer just past the end of the buffer. This is to ease the
123 // implementation, and is merely a requirement that any buffer growth occur
124 // only on the inside or past the end of the vector, and not prior to the
125 // start of the vector.
126 // Returns true on success, false on failure (e.g., if the allocator has no
127 // memory available).
128 bool InsertBytes(void *insertion_point, size_t bytes, SetZero set_zero);
129 // Called *after* the internal buffer_ has been swapped out and *after* the
130 // object tree has been traversed and fixed.
131 virtual void ObserveBufferModification() {}
132
133 // Returns the index'th sub object of this object.
134 // index must be less than NumberOfSubObjects().
135 // This will include objects which are not currently populated but which may
136 // be populated in the future (so that we can track what the necessary offsets
137 // are when we do populate it).
138 virtual SubObject GetSubObject(size_t index) = 0;
139 // Number of sub-objects of this object. May be zero.
140 virtual size_t NumberOfSubObjects() const = 0;
141
142 // Treating the supplied absolute_offset as an offset into the internal memory
143 // buffer, return the pointer to the underlying memory.
144 const void *PointerForAbsoluteOffset(const size_t absolute_offset) {
145 return buffer_.data() + absolute_offset;
146 }
147 // Returns a span at the requested offset into the buffer. terminal_alignment
148 // does not align the start of the buffer; instead, it ensures that the memory
149 // from absolute_offset + size until the next multiple of terminal_alignment
150 // is set to all zeroes.
151 std::span<uint8_t> BufferForObject(size_t absolute_offset, size_t size,
152 size_t terminal_alignment);
153 // When memory has been inserted/removed, this iterates over the sub-objects
154 // and notifies/adjusts them appropriately.
155 // This will be called after buffer_ has been updated, and:
156 // * For insertion, modification_point will point into the new buffer_ to the
157 // first of the newly inserted bytes.
158 // * Removal is not entirely implemented yet, but for removal,
159 // modification_point should point to the first byte after the removed
160 // chunk.
161 void FixObjects(void *modification_point, ssize_t bytes_inserted);
162
163 Allocator *allocator() { return allocator_; }
164
165 std::span<uint8_t> buffer_;
166
167 private:
168 ResizeableObject *parent_ = nullptr;
169 std::unique_ptr<Allocator> owned_allocator_;
170 Allocator *allocator_ = nullptr;
171};
172
173// Interface to represent a memory allocator for use with ResizeableObject.
174class Allocator {
175 public:
176 virtual ~Allocator() {}
177 // Allocates memory of the requested size and alignment. alignment is not
178 // guaranteed.
179 // On failure to allocate the requested size, returns nullopt;
180 // Never returns a partial span.
181 // The span will be initialized to zero upon request.
182 // Once Allocate() has been called once, it may not be called again until
183 // Deallocate() has been called. In order to adjust the size of the buffer,
184 // call InsertBytes() and RemoveBytes().
185 [[nodiscard]] virtual std::optional<std::span<uint8_t>> Allocate(
186 size_t size, size_t alignment_hint, SetZero set_zero) = 0;
187 // Identical to Allocate(), but dies on failure.
188 [[nodiscard]] std::span<uint8_t> AllocateOrDie(size_t size,
189 size_t alignment_hint,
190 SetZero set_zero) {
191 std::optional<std::span<uint8_t>> span =
192 Allocate(size, alignment_hint, set_zero);
193 CHECK(span.has_value()) << ": Failed to allocate " << size << " bytes.";
194 CHECK_EQ(size, span.value().size())
195 << ": Failed to allocate " << size << " bytes.";
196 return span.value();
197 }
198 // Increases the size of the buffer by inserting bytes bytes immediately
199 // before insertion_point.
200 // alignment_hint specifies the alignment of the entire buffer, not of the
201 // inserted bytes.
202 // The returned span may or may not overlap with the original buffer in
203 // memory.
204 // The inserted bytes will be set to zero or uninitialized depending on the
205 // value of SetZero.
206 // insertion_point must be in (or 1 past the end of) the buffer.
207 // Returns nullopt on a failure to allocate the requested bytes.
208 [[nodiscard]] virtual std::optional<std::span<uint8_t>> InsertBytes(
209 void *insertion_point, size_t bytes, size_t alignment_hint,
210 SetZero set_zero) = 0;
211 // Removes the requested span of bytes from the buffer, returning the new
212 // buffer.
213 [[nodiscard]] virtual std::span<uint8_t> RemoveBytes(
214 std::span<uint8_t> remove_bytes) = 0;
215 // Deallocates the currently allocated buffer. The provided buffer must match
216 // the latest version of the buffer.
217 // If Allocate() has been called, Deallocate() must be called prior to
218 // destroying the Allocator.
219 virtual void Deallocate(std::span<uint8_t> buffer) = 0;
220};
221
222// Allocator that uses an std::vector to allow arbitrary-sized allocations.
223// Does not provide any alignment guarantees.
224class VectorAllocator : public Allocator {
225 public:
226 VectorAllocator() {}
227 ~VectorAllocator() {
228 CHECK(buffer_.empty())
229 << ": Must deallocate before destroying the VectorAllocator.";
230 }
231 std::optional<std::span<uint8_t>> Allocate(size_t size, size_t /*alignment*/,
232 SetZero set_zero) override;
233 std::optional<std::span<uint8_t>> InsertBytes(void *insertion_point,
234 size_t bytes,
235 size_t /*alignment*/,
236 SetZero /*set_zero*/) override;
237 std::span<uint8_t> RemoveBytes(std::span<uint8_t> remove_bytes) override;
238
239 void Deallocate(std::span<uint8_t>) override {
240 CHECK(!buffer_.empty())
241 << ": Called Deallocate() without a prior allocation.";
242 buffer_.resize(0);
243 }
244
245 private:
246 std::vector<uint8_t> buffer_;
247};
248
249// Allocator that allocates all of its memory within a provided span. To match
250// the behavior of the FlatBufferBuilder, it will start its allocations at the
251// end of the provided span.
252//
253// Attempts to allocate more memory than is present in the provided buffer will
254// fail.
255class SpanAllocator : public Allocator {
256 public:
257 SpanAllocator(std::span<uint8_t> buffer) : buffer_(buffer) {}
258 ~SpanAllocator() {
259 CHECK(!allocated_)
260 << ": Must deallocate before destroying the SpanAllocator.";
261 }
262
263 std::optional<std::span<uint8_t>> Allocate(size_t size, size_t /*alignment*/,
264 SetZero set_zero) override;
265
266 std::optional<std::span<uint8_t>> InsertBytes(void *insertion_point,
267 size_t bytes,
268 size_t /*alignment*/,
269 SetZero set_zero) override;
270
271 std::span<uint8_t> RemoveBytes(std::span<uint8_t> remove_bytes) override;
272
273 void Deallocate(std::span<uint8_t>) override;
274
275 private:
276 std::span<uint8_t> buffer_;
277 bool allocated_ = false;
278 size_t allocated_size_ = 0;
279};
280
Maxwell Hendersonfb1e3bc2024-02-04 13:55:22 -0800281// Allocates and owns a fixed-size memory buffer on the stack.
282//
283// This provides a convenient Allocator for use with the aos::fbs::Builder
284// in realtime code instead of trying to use the VectorAllocator.
285template <std::size_t N>
286class FixedStackAllocator : public SpanAllocator {
287 public:
288 FixedStackAllocator() : SpanAllocator({buffer_, sizeof(buffer_)}) {}
289
290 private:
291 uint8_t buffer_[N];
292};
293
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700294namespace internal {
295std::ostream &DebugBytes(std::span<const uint8_t> span, std::ostream &os);
296inline void ClearSpan(std::span<uint8_t> span) {
297 memset(span.data(), 0, span.size());
298}
299// std::span::subspan does not do bounds checking.
300template <typename T>
301inline std::span<T> GetSubSpan(std::span<T> span, size_t offset,
302 size_t count = std::dynamic_extent) {
303 if (count != std::dynamic_extent) {
304 CHECK_LE(offset + count, span.size());
305 }
306 return span.subspan(offset, count);
307}
308// Normal users should never move any of the special flatbuffer types that we
309// provide. However, they do need to be moveable in order to support the use of
310// resizeable vectors. As such, we make all the move constructors private and
311// friend the TableMover struct. The TableMover struct is then used in places
312// that need to have moveable objects. It should never be used by a user.
313template <typename T>
314struct TableMover {
315 TableMover(std::span<uint8_t> buffer, ResizeableObject *parent)
316 : t(buffer, parent) {}
317 TableMover(std::span<uint8_t> buffer, Allocator *allocator)
318 : t(buffer, allocator) {}
319 TableMover(std::span<uint8_t> buffer, ::std::unique_ptr<Allocator> allocator)
320 : t(buffer, ::std::move(allocator)) {}
321 TableMover(TableMover &&) = default;
322 T t;
323};
324} // namespace internal
325} // namespace aos::fbs
326#endif // AOS_FLATBUFFERS_BASE_H_