constsize_t kDataAlignment = 1 << 8; // 256 Bytes For data align, must be 2^n constsize_t kDataAlignmentMask = kDataAlignment - 1; // Maximum allocation size (16 MB) (user limit not program limit). constsize_t kMaxAllocationSize = (16ull << 20);
constsize_t kMemorySize = ARENA_SIZE; // size to mmap once
constsize_t WORD_LENGTH = sizeof(size_t);
size_t memory_size = 0; // mark how many we have allocated
Data Structure
In the pool, there are several blocks, each block representing a part of memory.
All blocks are linked as a linked list
1 2 3 4 5 6 7 8 9 10 11
typedefstructBlock { size_t occupied; structBlock *nxt; structBlock *nxt_mmap; size_t data_length; void *data_ptr; // 64 bytes for Block Meta data, on 64-bit machine // block address is write before data_ptr sizeof(size_t) } Block; constsize_t kBlockMetadataSize = sizeof(Block) + WORD_LENGTH + kDataAlignmentMask & ~kDataAlignmentMask;
Member Values:
In a Block there are two parts:
Block meta data
padding area for align address
user’s data
integer occupied is a boolean(0/1), indicating if these block is in using or freed
pointer *nxt is the next block
pointer *nxt_mmap is the block which is the header of next mmap part
integer data_length is user’s required data length
pointer *data_ptr is the begin address of user’s data
Block Composition
A Block structure need 5 Words(5*8=40 bytes on 64 bit machine) for meta data, after that, there are padding and then data field.
Data field will align at least 64 bytes, so there are 24 bytes padding.
地址至少以64bytes对齐,对齐后还剩24bytes padding,够放3个int,最后一个int(也就是data_ptr - 1)存Block的地址,用于从帮助data ptr直接快速找到对应的block ptr
1 2
|------------|-----------|---------|------------ |Block meta | Padding |Block ptr|Data ptr
Utility Functions
calculate aligned address by round up/down pointer with MASK