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