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