/** *SkBlockAllocatorprovideslow-levelsupportforablockallocatedarenawithadynamictailthat *tracksspacereservationswithineachblock.ItsAPIsprovidetheabilitytoreservespace, *resizereservations,andreleasereservations.Itwillautomaticallycreatenewblocksifneeded *anddestroyallremainingblockswhenitisdestructed.Itassumesthatanythingallocatedwithin *itsblockshasitsdestructorscalledexternally.ItisrecommendedthatSkBlockAllocatoris *wrappedbyahigher-levelallocatorthatusesthelow-levelAPIstoimplementasimpler, *purpose-focusedAPIw/ohavingtoworryasmuchaboutbyte-levelconcerns. * *SkBlockAllocatorhasnolimittoitstotalsize,buteachallocationislimitedto512MB(which *shouldbesufficientforSkia'susecases).Thisupperallocationlimitallowsallinternal *operationstobeperformedusing'int'andavoidmanyoverflowchecks.Staticassertsareused *toensurethatthoseoperationswouldnotoverflowwhenusingthelargestpossiblevalues. * *Possibleusemodes: *1.Noupfrontallocation,eitheronthestackorasafield *SkBlockAllocatorallocator(policy,heapAllocSize); * *2.In-placenew'd *void*mem=operatornew(totalSize); *SkBlockAllocator*allocator=new(mem)SkBlockAllocator(policy,heapAllocSize, *totalSize-sizeof(SkBlockAllocator)); *deleteallocator; * *3.UseSkSBlockAllocatortoincreasethepreallocationsize *SkSBlockAllocator<1024>allocator(policy,heapAllocSize); *sizeof(allocator)==1024;
*/ // TODO(michaelludwig) - While API is different, this shares similarities to SkArenaAlloc and // SkFibBlockSizes, so we should work to integrate them. class SkBlockAllocator final : SkNoncopyable {
public: // Largest size that can be requested from allocate(), chosen because it's the largest pow-2 // that is less than int32_t::max()/2. inlinestatic constexpr int kMaxAllocationSize = 1 << 29;
enumclass GrowthPolicy : int {
kFixed, // Next block size = N
kLinear, // = #blocks * N
kFibonacci, // = fibonacci(#blocks) * N
kExponential, // = 2^#blocks * N
kLast = kExponential
}; inlinestatic constexpr int kGrowthPolicyCount = static_cast<int>(GrowthPolicy::kLast) + 1;
class Block final {
public:
~Block(); voidoperatordelete(void* p) { ::operatordelete(p); }
// Return the maximum allocation size with the given alignment that can fit in this block. template <size_t Align = 1, size_t Padding = 0> int avail() const { return std::max(0, fSize - this->cursor<Align, Padding>()); }
// Return the aligned offset of the first allocation, assuming it was made with the // specified Align, and Padding. The returned offset does not mean a valid allocation // starts at that offset, this is a utility function for classes built on top to manage // indexing into a block effectively. template <size_t Align = 1, size_t Padding = 0> int firstAlignedOffset() const { return this->alignedOffset<Align, Padding>(kDataStart); }
// Convert an offset into this block's storage into a usable pointer. void* ptr(int offset) {
SkASSERT(offset >= kDataStart && offset < fSize); return reinterpret_cast<char*>(this) + offset;
} constvoid* ptr(int offset) const { returnconst_cast<Block*>(this)->ptr(offset); }
// Every block has an extra 'int' for clients to use however they want. It will start // at 0 when a new block is made, or when the head block is reset. int metadata() const { return fMetadata; } void setMetadata(int value) { fMetadata = value; }
// We poison the unallocated space in a Block to allow ASAN to catch invalid writes. void poisonRange(int start, int end) {
sk_asan_poison_memory_region(reinterpret_cast<char*>(this) + start, end - start);
} void unpoisonRange(int start, int end) {
sk_asan_unpoison_memory_region(reinterpret_cast<char*>(this) + start, end - start);
}
// Get fCursor, but aligned such that ptr(rval) satisfies Align. template <size_t Align, size_t Padding> int cursor() const { return this->alignedOffset<Align, Padding>(fCursor); }
template <size_t Align, size_t Padding> int alignedOffset(int offset) const;
SkDEBUGCODE(uint32_t fSentinel;) // known value to check for bad back pointers to blocks
Block* fNext; // doubly-linked list of blocks
Block* fPrev;
// Each block tracks its own cursor because as later blocks are released, an older block // may become the active tail again. int fSize; // includes the size of the BlockHeader and requested metadata int fCursor; // (this + fCursor) points to next available allocation int fMetadata;
// On release builds, a Block's other 2 pointers and 3 int fields leaves 4 bytes of padding // for 8 and 16 aligned systems. Currently this is only manipulated in the head block for // an allocator-level metadata and is explicitly not reset when the head block is "released" // Down the road we could instead choose to offer multiple metadata slots per block. int fAllocatorMetadata;
};
// Tuple representing a range of bytes, marking the unaligned start, the first aligned point // after any padding, and the upper limit depending on requested size. struct ByteRange {
Block* fBlock; // Owning block int fStart; // Inclusive byte lower limit of byte range int fAlignedOffset; // >= start, matching alignment requirement (i.e. first real byte) int fEnd; // Exclusive upper limit of byte range
};
// The size of the head block is determined by 'additionalPreallocBytes'. Subsequent heap blocks // are determined by 'policy' and 'blockIncrementBytes', although 'blockIncrementBytes' will be // aligned to std::max_align_t. // // When 'additionalPreallocBytes' > 0, the allocator assumes that many extra bytes immediately // after the allocator can be used by its inline head block. This is useful when the allocator // is in-place new'ed into a larger block of memory, but it should remain set to 0 if stack // allocated or if the class layout does not guarantee that space is present.
SkBlockAllocator(GrowthPolicy policy, size_t blockIncrementBytes,
size_t additionalPreallocBytes = 0);
enum ReserveFlags : unsigned { // If provided to reserve(), the input 'size' will be rounded up to the next size determined // by the growth policy of the SkBlockAllocator. If not, 'size' will be aligned to max_align
kIgnoreGrowthPolicy_Flag = 0b01, // If provided to reserve(), the number of available bytes of the current block will not // be used to satisfy the reservation (assuming the contiguous range was long enough to // begin with).
kIgnoreExistingBytes_Flag = 0b10,
inlinestatic constexpr int kDataStart = sizeof(Block); #ifdef SK_FORCE_8_BYTE_ALIGNMENT // This is an issue for WASM builds using emscripten, which had std::max_align_t = 16, but // was returning pointers only aligned to 8 bytes. // https://github.com/emscripten-core/emscripten/issues/10072 // // Setting this to 8 will let SkBlockAllocator properly correct for the pointer address if // a 16-byte aligned allocation is requested in wasm (unlikely since we don't use long // doubles). static constexpr size_t kAddressAlign = 8; #else // The alignment Block addresses will be at when created using operator new // (spec-compliant is pointers are aligned to max_align_t). static constexpr size_t kAddressAlign = alignof(std::max_align_t); #endif
// Calculates the size of a new Block required to store a kMaxAllocationSize request for the // given alignment and padding bytes. Also represents maximum valid fCursor value in a Block. template<size_t Align, size_t Padding> static constexpr size_t MaxBlockSize();
static constexpr int BaseHeadBlockSize() { returnsizeof(SkBlockAllocator) - offsetof(SkBlockAllocator, fHead);
}
// Append a new block to the end of the block linked list, updating fTail. 'minSize' must // have enough room for sizeof(Block). 'maxSize' is the upper limit of fSize for the new block // that will preserve the static guarantees SkBlockAllocator makes. void addBlock(int minSize, int maxSize);
Block* fTail; // All non-head blocks are heap allocated; tail will never be null.
// All remaining state is packed into 64 bits to keep SkBlockAllocator at 16 bytes + head block // (on a 64-bit system).
// Growth of the block size is controlled by four factors: BlockIncrement, N0 and N1, and a // policy defining how N0 is updated. When a new block is needed, we calculate N1' = N0 + N1. // Depending on the policy, N0' = N0 (no growth or linear growth), or N0' = N1 (Fibonacci), or // N0' = N1' (exponential). The size of the new block is N1' * BlockIncrement * MaxAlign, // after which fN0 and fN1 store N0' and N1' clamped into 23 bits. With current bit allocations, // N1' is limited to 2^24, and assuming MaxAlign=16, then BlockIncrement must be '2' in order to // eventually reach the hard 2^29 size limit of SkBlockAllocator.
// Inline head block, must be at the end so that it can utilize any additional reserved space // from the initial allocation. // The head block's prev pointer may be non-null, which signifies a scratch block that may be // reused instead of allocating an entirely new block (this helps when allocate+release calls // bounce back and forth across the capacity of a block).
alignas(kAddressAlign) Block fHead;
static_assert(kGrowthPolicyCount <= 4);
};
// A wrapper around SkBlockAllocator that includes preallocated storage for the head block. // N will be the preallocSize() reported by the allocator. template<size_t N> class SkSBlockAllocator : SkNoncopyable {
public:
using GrowthPolicy = SkBlockAllocator::GrowthPolicy;
SkSBlockAllocator() { new (fStorage) SkBlockAllocator(GrowthPolicy::kFixed, N, N - sizeof(SkBlockAllocator));
} explicit SkSBlockAllocator(GrowthPolicy policy) { new (fStorage) SkBlockAllocator(policy, N, N - sizeof(SkBlockAllocator));
}
SkSBlockAllocator(GrowthPolicy policy, size_t blockIncrementBytes) { new (fStorage) SkBlockAllocator(policy, blockIncrementBytes, N - sizeof(SkBlockAllocator));
}
template<size_t Align, size_t Padding>
constexpr size_t SkBlockAllocator::Overhead() { // NOTE: On most platforms, SkBlockAllocator is packed; this is not the case on debug builds // due to extra fields, or on WASM due to 4byte pointers but 16byte max align. return std::max(sizeof(SkBlockAllocator),
offsetof(SkBlockAllocator, fHead) + BlockOverhead<Align, Padding>());
}
template<size_t Align, size_t Padding>
constexpr size_t SkBlockAllocator::MaxBlockSize() { // Without loss of generality, assumes 'align' will be the largest encountered alignment for the // allocator (if it's not, the largest align will be encountered by the compiler and pass/fail // the same set of static asserts). return BlockOverhead<Align, Padding>() + kMaxAllocationSize;
}
template<size_t Align, size_t Padding> void SkBlockAllocator::reserve(size_t size, ReserveFlags flags) { if (size > kMaxAllocationSize) {
SK_ABORT("Allocation too large (%zu bytes requested)", size);
} int iSize = (int) size; if ((flags & kIgnoreExistingBytes_Flag) ||
this->currentBlock()->avail<Align, Padding>() < iSize) {
SkDEBUGCODE(auto oldTail = fTail;)
this->addBlock(blockSize, maxSize);
SkASSERT(fTail != oldTail); // Releasing the just added block will move it into scratch space, allowing the original // tail's bytes to be used first before the scratch block is activated.
this->releaseBlock(fTail);
}
}
template <size_t Align, size_t Padding>
SkBlockAllocator::ByteRange SkBlockAllocator::allocate(size_t size) { // Amount of extra space for a new block to make sure the allocation can succeed. static constexpr int kBlockOverhead = (int) BlockOverhead<Align, Padding>();
// Ensures 'offset' and 'end' calculations will be valid
static_assert((kMaxAllocationSize + SkAlignTo(MaxBlockSize<Align, Padding>(), Align))
<= (size_t) std::numeric_limits<int32_t>::max()); // Ensures size + blockOverhead + addBlock's alignment operations will be valid
static_assert(kMaxAllocationSize + kBlockOverhead + ((1 << 12) - 1) // 4K align for large blocks
<= std::numeric_limits<int32_t>::max());
if (size > kMaxAllocationSize) {
SK_ABORT("Allocation too large (%zu bytes requested)", size);
}
int iSize = (int) size; int offset = fTail->cursor<Align, Padding>(); int end = offset + iSize; if (end > fTail->fSize) {
this->addBlock(iSize + kBlockOverhead, MaxBlockSize<Align, Padding>());
offset = fTail->cursor<Align, Padding>();
end = offset + iSize;
}
template <size_t Align, size_t Padding>
SkBlockAllocator::Block* SkBlockAllocator::owningBlock(constvoid* p, int start) { // 'p' was originally formed by aligning 'block + start + Padding', producing the inequality: // block + start + Padding <= p <= block + start + Padding + Align-1 // Rearranging this yields: // block <= p - start - Padding <= block + Align-1 // Masking these terms by ~(Align-1) reconstructs 'block' if the alignment of the block is // greater than or equal to Align (since block & ~(Align-1) == (block + Align-1) & ~(Align-1) // in that case). Overalignment does not reduce to inequality unfortunately. if/* constexpr */ (Align <= kAddressAlign) {
Block* block = reinterpret_cast<Block*>(
(reinterpret_cast<uintptr_t>(p) - start - Padding) & ~(Align - 1));
SkASSERT(block->fSentinel == kAssignedMarker); return block;
} else { // There's not a constant-time expression available to reconstruct the block from 'p', // but this is unlikely to happen frequently. return this->findOwningBlock(p);
}
}
template <size_t Align, size_t Padding> int SkBlockAllocator::Block::alignedOffset(int offset) const {
static_assert(SkIsPow2(Align)); // Aligning adds (Padding + Align - 1) as an intermediate step, so ensure that can't overflow
static_assert(MaxBlockSize<Align, Padding>() + Padding + Align - 1
<= (size_t) std::numeric_limits<int32_t>::max());
if/* constexpr */ (Align <= kAddressAlign) { // Same as SkAlignTo, but operates on ints instead of size_t return (offset + Padding + Align - 1) & ~(Align - 1);
} else { // Must take into account that 'this' may be starting at a pointer that doesn't satisfy the // larger alignment request, so must align the entire pointer, not just offset
uintptr_t blockPtr = reinterpret_cast<uintptr_t>(this);
uintptr_t alignedPtr = (blockPtr + offset + Padding + Align - 1) & ~(Align - 1);
SkASSERT(alignedPtr - blockPtr <= (uintptr_t) std::numeric_limits<int32_t>::max()); return (int) (alignedPtr - blockPtr);
}
}
bool SkBlockAllocator::Block::resize(int start, int end, int deltaBytes) {
SkASSERT(fSentinel == kAssignedMarker);
SkASSERT(start >= kDataStart && end <= fSize && start < end);
if (deltaBytes > kMaxAllocationSize || deltaBytes < -kMaxAllocationSize) { // Cannot possibly satisfy the resize and could overflow subsequent math returnfalse;
} if (fCursor == end) { int nextCursor = end + deltaBytes;
SkASSERT(nextCursor >= start); // We still check nextCursor >= start for release builds that wouldn't assert. if (nextCursor <= fSize && nextCursor >= start) { if (nextCursor < fCursor) { // The allocation got smaller; poison the space that can no longer be used.
this->poisonRange(nextCursor + 1, end);
} else { // The allocation got larger; unpoison the space that can now be used.
this->unpoisonRange(end, nextCursor);
}
// NOTE: release is equivalent to resize(start, end, start - end), and the compiler can optimize // most of the operations away, but it wasn't able to remove the unnecessary branch comparing the // new cursor to the block size or old start, so release() gets a specialization. bool SkBlockAllocator::Block::release(int start, int end) {
SkASSERT(fSentinel == kAssignedMarker);
SkASSERT(start >= kDataStart && end <= fSize && start < end);
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.