C/C++ API Reference
Loading...
Searching...
No Matches
block_allocator.h
1// Copyright 2024 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <cstddef>
17#include <optional>
18
19#include "pw_allocator/allocator.h"
20#include "pw_allocator/block/basic.h"
21#include "pw_allocator/block/iterable.h"
22#include "pw_allocator/block/poisonable.h"
23#include "pw_allocator/block/result.h"
24#include "pw_allocator/block/with_layout.h"
25#include "pw_allocator/capability.h"
26#include "pw_allocator/config.h"
27#include "pw_allocator/fragmentation.h"
28#include "pw_allocator/hardening.h"
29#include "pw_assert/assert.h"
30#include "pw_bytes/span.h"
31#include "pw_result/result.h"
32#include "pw_status/status.h"
33
34namespace pw::allocator {
35namespace internal {
36
47 public:
48 // Not copyable or movable.
50 GenericBlockAllocator& operator=(const GenericBlockAllocator&) = delete;
52 GenericBlockAllocator& operator=(GenericBlockAllocator&&) = delete;
53
54 protected:
55 template <typename BlockType>
56 static constexpr Capabilities GetCapabilities() {
57 Capabilities common = kImplementsGetUsableLayout |
58 kImplementsGetAllocatedLayout |
59 kImplementsGetCapacity | kImplementsRecognizes;
60 if constexpr (has_layout_v<BlockType>) {
61 return common | kImplementsGetRequestedLayout;
62 } else {
63 return common;
64 }
65 }
66
67 constexpr explicit GenericBlockAllocator(Capabilities capabilities)
68 : Allocator(capabilities) {}
69
75 [[noreturn]] static void CrashOnAllocated(const void* allocated);
76
79 [[noreturn]] static void CrashOnOutOfRange(const void* freed);
80
82 [[noreturn]] static void CrashOnDoubleFree(const void* freed);
83};
84
85} // namespace internal
86
87namespace test {
88
89// Forward declaration for friending.
90template <typename, size_t>
92
93} // namespace test
94
96
106template <typename BlockType_>
108 private:
110
111 public:
112 using BlockType = BlockType_;
113 using Range = typename BlockType::Range;
114
115 static constexpr Capabilities kCapabilities =
116 Base::GetCapabilities<BlockType>();
117 static constexpr size_t kPoisonInterval = PW_ALLOCATOR_BLOCK_POISON_INTERVAL;
118
119 ~BlockAllocator() override;
120
122 Range blocks() const;
123
131 void Init(ByteSpan region);
132
154
157
158 protected:
159 constexpr explicit BlockAllocator() : Base(kCapabilities) {}
160
162 std::optional<Fragmentation> DoMeasureFragmentation() const override {
163 return MeasureFragmentation();
164 }
165
173 void Init(BlockType* begin);
174
186 template <typename Ptr>
187 internal::copy_const_ptr_t<Ptr, BlockType*> FromUsableSpace(Ptr ptr) const;
188
193 virtual void DeallocateBlock(BlockType*&& block);
194
195 private:
196 using BlockResultPrev = internal::GenericBlockResult::Prev;
197 using BlockResultNext = internal::GenericBlockResult::Next;
198
199 // Let unit tests call internal methods in order to "preallocate" blocks..
200 template <typename, size_t>
201 friend class test::BlockAllocatorTest;
202
204 void* DoAllocate(Layout layout) override;
205
207 void DoDeallocate(void* ptr) override;
208
210 void DoDeallocate(void* ptr, Layout) override { DoDeallocate(ptr); }
211
213 bool DoResize(void* ptr, size_t new_size) override;
214
216 size_t DoGetAllocated() const override { return allocated_; }
217
219 Result<Layout> DoGetInfo(InfoType info_type, const void* ptr) const override;
220
222 virtual size_t DoGetMaxAllocatable() = 0;
223
233
240 virtual void ReserveBlock(BlockType&) {}
241
248 virtual void RecycleBlock(BlockType&) {}
249
262 virtual void Flush() {}
263
265 static bool PrevIsFree(const BlockType* block) {
266 auto* prev = block->Prev();
267 return prev != nullptr && prev->IsFree();
268 }
269
271 static bool NextIsFree(const BlockType* block) {
272 auto* next = block->Next();
273 return next != nullptr && next->IsFree();
274 }
275
278 void UpdateLast(BlockType* block);
279
280 // Represents the range of blocks for this allocator.
281 size_t capacity_ = 0;
282 size_t allocated_ = 0;
283 BlockType* first_ = nullptr;
284 BlockType* last_ = nullptr;
285 uint16_t unpoisoned_ = 0;
286};
287
289
290// Template method implementations
291
292template <typename BlockType>
293BlockAllocator<BlockType>::~BlockAllocator() {
294 if constexpr (Hardening::kIncludesRobustChecks) {
295 for (auto* block : blocks()) {
296 if (!block->IsFree()) {
297 CrashOnAllocated(block);
298 }
299 }
300 }
301}
302
303template <typename BlockType>
304typename BlockAllocator<BlockType>::Range BlockAllocator<BlockType>::blocks()
305 const {
306 return Range(first_);
307}
308
309template <typename BlockType>
311 Result<BlockType*> result = BlockType::Init(region);
312 PW_ASSERT(result.ok());
313 Init(*result);
314}
315
316template <typename BlockType>
317void BlockAllocator<BlockType>::Init(BlockType* begin) {
318 if constexpr (Hardening::kIncludesRobustChecks) {
319 PW_ASSERT(begin != nullptr);
320 PW_ASSERT(begin->Prev() == nullptr);
321 }
322 first_ = begin;
323 for (auto* block : blocks()) {
324 last_ = block;
325 capacity_ += block->OuterSize();
326 if (block->IsFree()) {
327 RecycleBlock(*block);
328 }
329 }
330}
331
332template <typename BlockType>
334 if (capacity_ == 0) {
335 // Not initialized.
336 return nullptr;
337 }
338
339 if constexpr (Hardening::kIncludesDebugChecks) {
340 PW_ASSERT(last_->Next() == nullptr);
341 }
342 auto result = ChooseBlock(layout);
343 if (!result.ok()) {
344 // No valid block for request.
345 return nullptr;
346 }
347 BlockType* block = result.block();
348 allocated_ += block->OuterSize();
349 switch (result.prev()) {
350 case BlockResultPrev::kSplitNew:
351 // New free blocks may be created when allocating.
352 RecycleBlock(*(block->Prev()));
353 break;
354 case BlockResultPrev::kResizedLarger:
355 // Extra bytes may be appended to the previous block.
356 allocated_ += result.size();
357 break;
358 case BlockResultPrev::kUnchanged:
359 case BlockResultPrev::kResizedSmaller:
360 break;
361 }
362 if (result.next() == BlockResultNext::kSplitNew) {
363 RecycleBlock(*(block->Next()));
364 }
365
366 UpdateLast(block);
367 if constexpr (Hardening::kIncludesDebugChecks) {
368 PW_ASSERT(block <= last_);
369 }
370
371 return block->UsableSpace();
372}
373
374template <typename BlockType>
376 BlockType* block = FromUsableSpace(ptr);
377 if (block->IsFree()) {
378 if constexpr (Hardening::kIncludesBasicChecks) {
379 CrashOnDoubleFree(block);
380 } else {
381 return;
382 }
383 }
384 DeallocateBlock(std::move(block));
385}
386
387template <typename BlockType>
389 // Neighboring blocks may be merged when freeing.
390 if (auto* prev = block->Prev(); prev != nullptr && prev->IsFree()) {
391 ReserveBlock(*prev);
392 }
393 if (auto* next = block->Next(); next != nullptr && next->IsFree()) {
394 ReserveBlock(*next);
395 }
396
397 // Free the block and merge it with its neighbors, if possible.
398 allocated_ -= block->OuterSize();
399 auto free_result = BlockType::Free(std::move(block));
400 block = free_result.block();
401 UpdateLast(block);
402
403 if (free_result.prev() == BlockResultPrev::kResizedSmaller) {
404 // Bytes were reclaimed from the previous block.
405 allocated_ -= free_result.size();
406 }
407
408 if constexpr (is_poisonable_v<BlockType> && kPoisonInterval != 0) {
409 ++unpoisoned_;
410 if (unpoisoned_ >= kPoisonInterval) {
411 block->Poison();
412 unpoisoned_ = 0;
413 }
414 }
415
416 RecycleBlock(*block);
417}
418
419template <typename BlockType>
420bool BlockAllocator<BlockType>::DoResize(void* ptr, size_t new_size) {
421 BlockType* block = FromUsableSpace(ptr);
422
423 // Neighboring blocks may be merged when resizing.
424 if (auto* next = block->Next(); next != nullptr && next->IsFree()) {
425 ReserveBlock(*next);
426 }
427
428 size_t old_size = block->OuterSize();
429 if (!block->Resize(new_size).ok()) {
430 return false;
431 }
432 allocated_ -= old_size;
433 allocated_ += block->OuterSize();
434 UpdateLast(block);
435
436 if (auto* next = block->Next(); next != nullptr && next->IsFree()) {
437 RecycleBlock(*next);
438 }
439
440 return true;
441}
442
443template <typename BlockType>
445 const void* ptr) const {
446 // Handle types not related to a block first.
447 if (info_type == InfoType::kCapacity) {
448 return Layout(capacity_);
449 }
450 // Get a block from the given pointer.
451 if (ptr < first_->UsableSpace() || last_->UsableSpace() < ptr) {
452 return Status::NotFound();
453 }
454 const auto* block = BlockType::FromUsableSpace(ptr);
455 if (!block->IsValid()) {
456 return Status::DataLoss();
457 }
458 if (block->IsFree()) {
460 }
461 if constexpr (kCapabilities.has(kImplementsGetRequestedLayout)) {
462 if (info_type == InfoType::kRequestedLayoutOf) {
463 return block->RequestedLayout();
464 }
465 }
466 switch (info_type) {
467 case InfoType::kUsableLayoutOf:
468 return Layout(block->InnerSize(), BlockType::kAlignment);
469 case InfoType::kAllocatedLayoutOf:
470 return Layout(block->OuterSize(), BlockType::kAlignment);
471 case InfoType::kRecognizes:
472 return Layout();
473 case InfoType::kCapacity:
474 case InfoType::kRequestedLayoutOf:
475 default:
476 return Status::Unimplemented();
477 }
478}
479
480template <typename BlockType>
482 Fragmentation fragmentation;
483 for (auto block : blocks()) {
484 if (block->IsFree()) {
485 fragmentation.AddFragment(block->InnerSize() / BlockType::kAlignment);
486 }
487 }
488 return fragmentation;
489}
490
491template <typename BlockType>
492template <typename Ptr>
493internal::copy_const_ptr_t<Ptr, BlockType*>
495 if (ptr < first_->UsableSpace() || last_->UsableSpace() < ptr) {
496 if constexpr (Hardening::kIncludesBasicChecks) {
497 CrashOnOutOfRange(ptr);
498 }
499 return nullptr;
500 }
501 auto* block = BlockType::FromUsableSpace(ptr);
502 if (!block->IsValid()) {
503 if constexpr (Hardening::kIncludesBasicChecks) {
504 block->CheckInvariants();
505 }
506 return nullptr;
507 }
508 return block;
509}
510
511template <typename BlockType>
512void BlockAllocator<BlockType>::UpdateLast(BlockType* block) {
513 BlockType* next = block->Next();
514 if (next == nullptr) {
515 last_ = block;
516 } else if (next->Next() == nullptr) {
517 last_ = next;
518 }
519}
520
521} // namespace pw::allocator
Definition: allocator.h:45
constexpr Allocator()=default
TODO(b/326509341): Remove when downstream consumers migrate.
Definition: result.h:145
constexpr bool ok() const
Definition: result.h:451
static constexpr Status DataLoss()
Definition: status.h:316
static constexpr Status Unimplemented()
Definition: status.h:280
static constexpr Status FailedPrecondition()
Definition: status.h:243
static constexpr Status NotFound()
Definition: status.h:190
Definition: block_allocator.h:107
void * DoAllocate(Layout layout) override
Definition: block_allocator.h:333
size_t DoGetAllocated() const override
Definition: block_allocator.h:216
std::optional< Fragmentation > DoMeasureFragmentation() const override
Definition: block_allocator.h:162
Fragmentation MeasureFragmentation() const
Returns fragmentation information for the block allocator's memory region.
Definition: block_allocator.h:481
virtual size_t DoGetMaxAllocatable()=0
internal::copy_const_ptr_t< Ptr, BlockType * > FromUsableSpace(Ptr ptr) const
Definition: block_allocator.h:494
virtual BlockResult< BlockType > ChooseBlock(Layout layout)=0
virtual void ReserveBlock(BlockType &)
Definition: block_allocator.h:240
void DoDeallocate(void *ptr) override
Definition: block_allocator.h:375
virtual void DeallocateBlock(BlockType *&&block)
Definition: block_allocator.h:388
bool DoResize(void *ptr, size_t new_size) override
Definition: block_allocator.h:420
void Init(ByteSpan region)
Definition: block_allocator.h:310
void DoDeallocate(void *ptr, Layout) override
Definition: block_allocator.h:210
void Init(BlockType *begin)
Definition: block_allocator.h:317
virtual void Flush()
Definition: block_allocator.h:262
size_t GetMaxAllocatable()
Definition: block_allocator.h:153
virtual void RecycleBlock(BlockType &)
Definition: block_allocator.h:248
Range blocks() const
Returns a Range of blocks tracking the memory of this allocator.
Definition: block_allocator.h:304
Result< Layout > DoGetInfo(InfoType info_type, const void *ptr) const override
Definition: block_allocator.h:444
Definition: result.h:116
Definition: capability.h:65
Definition: detailed_block.h:88
Definition: layout.h:58
Definition: block_allocator.h:46
static void CrashOnOutOfRange(const void *freed)
static void CrashOnDoubleFree(const void *freed)
Crashes with an informational message that a given block was freed twice.
static void CrashOnAllocated(const void *allocated)
Definition: block_allocator.h:91
#define PW_ALLOCATOR_BLOCK_POISON_INTERVAL
Definition: config.h:30
Definition: fragmentation.h:46