CookMem 1.6.0
A C++ memory context / allocator
Loading...
Searching...
No Matches
pool.h
1/*
2 * Copyright (c) 2018-2026 Heng Yuan
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef COOK_MEM_POOL_H
17#define COOK_MEM_POOL_H
18
19#include <cstddef>
20#include <cstdint>
21#include <cstdio>
22#include <cstring>
23
24#ifdef _WIN32
25#include <windows.h>
26#endif /* _WIN32 */
27
28#include "config.h"
29#include "exception.h"
30#include "logger.h"
31#include "rbtree.h"
32#include "circularlist.h"
33
34namespace cookmem
35{
36
38// Bit helpers used by the bin maps (from dlmalloc). T is unsigned, and
39// ~x + 1 is -x without the overflow of negating INT_MIN as an int.
40template<class T>
41T least_bit(T x)
42{
43 return x & (~x + 1);
44}
45
46template<class T>
47T left_bits(T x)
48{
49 return (x << 1) | (~(x << 1) + 1);
50}
52
53/* Assign the tree bin index for size S to I. Use the compiler builtins or
54 intrinsics for the bit scan if possible. */
55#if defined(__GNUC__)
56#define cookmem_getLargeBinIndex(S, I)\
57{\
58 std::size_t X = S >> TREEBIN_SHIFT;\
59 if (X == 0)\
60 I = 0;\
61 else if (X > 0xFFFF)\
62 I = NTREEBINS-1;\
63 else {\
64 unsigned int K = (unsigned) sizeof(unsigned int)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz((unsigned int) X); \
65 I = (BinIndexType)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
66 }\
67}
68
69#elif defined (__INTEL_COMPILER)
70#define cookmem_getLargeBinIndex(S, I)\
71{\
72 std::size_t X = S >> TREEBIN_SHIFT;\
73 if (X == 0)\
74 I = 0;\
75 else if (X > 0xFFFF)\
76 I = NTREEBINS-1;\
77 else {\
78 unsigned int K = _bit_scan_reverse (X); \
79 I = (BinIndexType)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
80 }\
81}
82
83#elif defined(_MSC_VER) && _MSC_VER>=1300
84#define cookmem_getLargeBinIndex(S, I)\
85{\
86 std::size_t X = S >> TREEBIN_SHIFT;\
87 if (X == 0)\
88 I = 0;\
89 else if (X > 0xFFFF)\
90 I = NTREEBINS-1;\
91 else {\
92 unsigned int K;\
93 _BitScanReverse((DWORD *) &K, (DWORD) X);\
94 I = (BinIndexType)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
95 }\
96}
97
98#else /* GNUC */
99#define cookmem_getLargeBinIndex(S, I)\
100{\
101 std::size_t X = S >> TREEBIN_SHIFT;\
102 if (X == 0)\
103 I = 0;\
104 else if (X > 0xFFFF)\
105 I = NTREEBINS-1;\
106 else {\
107 unsigned int Y = (unsigned int)X;\
108 unsigned int N = ((Y - 0x100) >> 16) & 8;\
109 unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
110 N += K;\
111 N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
112 K = 14 - N + ((Y <<= K) >> 15);\
113 I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
114 }\
115}
116#endif /* GNUC */
117
118#if defined(__GNUC__)
119#define cookmem_bit2treeIndex(X, I)\
120{\
121 unsigned int J;\
122 J = __builtin_ctz(X); \
123 I = (BinIndexType)J;\
124}
125
126#elif defined (__INTEL_COMPILER)
127#define cookmem_bit2treeIndex(X, I)\
128{\
129 unsigned int J;\
130 J = _bit_scan_forward (X); \
131 I = (BinIndexType)J;\
132}
133
134#elif defined(_MSC_VER) && _MSC_VER>=1300
135#define cookmem_bit2treeIndex(X, I)\
136{\
137 unsigned int J;\
138 _BitScanForward((DWORD *) &J, X);\
139 I = (BinIndexType)J;\
140}
141
142#elif USE_BUILTIN_FFS
143#define cookmem_bit2treeIndex(X, I) I = ffs(X)-1
144
145#else
146#define cookmem_bit2treeIndex(X, I)\
147{\
148 unsigned int Y = X - 1;\
149 unsigned int K = Y >> (16-4) & 16;\
150 unsigned int N = K; Y >>= K;\
151 N += K = Y >> (8-3) & 8; Y >>= K;\
152 N += K = Y >> (4-2) & 4; Y >>= K;\
153 N += K = Y >> (2-1) & 2; Y >>= K;\
154 N += K = Y >> (1-0) & 1; Y >>= K;\
155 I = (BinIndexType)(N + Y);\
156}
157#endif /* GNUC */
158
166template<class Arena, class Logger, class TreeType = PtrRBTree, class T=void>
168{
169public:
171 typedef std::size_t size_type;
173 typedef std::ptrdiff_t difference_type;
175 typedef T value_type;
177 typedef T* pointer;
179 typedef const T* const_pointer;
180
181private:
182 typedef unsigned int BinIndexType;
183 typedef TreeType PtrTreeType;
184
185private:
194 class MemChunk
195 {
196 public:
201 static const size_type BIT_MASK = ~static_cast<size_type> (ALLOCATION_ALIGNMENT - 1);
202 static const size_type BIT_USED = 1;
203 static const size_type BIT_NOTEXACTSIZE = 2;
204
205 private:
206 size_type m_prevFootSize; /* Size of previous chunk (if free). */
207 size_type m_size; /* Size */
208
209 public:
210 inline size_type
211 getChunkSize () const
212 {
213 return m_size & BIT_MASK;
214 }
215
216 inline size_type
217 getPrevChunkSize () const
218 {
219 return m_prevFootSize & BIT_MASK;
220 }
221
222 inline void
223 setFreeChunkSize (size_type chunkSize)
224 {
225 m_size = chunkSize;
226 getNextChunk (chunkSize)->m_prevFootSize = chunkSize;
227 }
228
229 inline void
230 setFence ()
231 {
232 m_size = BIT_USED;
233 }
234
240 inline void
241 clearUsed ()
242 {
243 m_size &= ~BIT_USED;
244 }
245
246 inline bool
247 isUsed () const
248 {
249 return m_size & BIT_USED;
250 }
251
252 inline bool
253 isPrevChunkUsed () const
254 {
255 return m_prevFootSize & BIT_USED;
256 }
257
258 inline size_type
259 getUserSize () const
260 {
261 size_type chunkSize = getChunkSize ();
262 if (m_size & BIT_NOTEXACTSIZE)
263 {
264 char diff = *((char*)(this) + chunkSize - 1);
265 if (diff <= 0)
266 {
267 throw Exception (MEM_ERROR_PADDING, "Invalid padding byte value", __FILE__, __LINE__);
268 }
269 return chunkSize - CHUNK_OVERHEAD - diff;
270 }
271 return chunkSize - CHUNK_OVERHEAD;
272 }
273
274 inline void
275 setUsedSize (bool storingExactSize, size_type userSize)
276 {
277 size_type chunkSize = getChunkSize ();
278 // Reset the flags, since the chunk may have been in use with a
279 // different size (see reallocate ()).
280 m_size = chunkSize | BIT_USED;
281 if (storingExactSize)
282 {
283 userSize += CHUNK_OVERHEAD;
284 if (userSize != chunkSize)
285 {
286 m_size |= BIT_NOTEXACTSIZE;
287 char diff = (char)(chunkSize - userSize);
288 *(((char*)this) + chunkSize - 1) = diff;
289 }
290 }
291 getNextChunk (chunkSize)->m_prevFootSize = chunkSize | BIT_USED;
292 }
293
294 inline MemChunk*
295 getPrevChunk ()
296 {
297 return (MemChunk*)((char*)this - getPrevChunkSize ());
298 }
299
300 inline MemChunk*
301 getNextChunk (size_type chunkSize)
302 {
303 return (MemChunk*)((char*)this + chunkSize);
304 }
305
306 inline const MemChunk*
307 getNextChunk () const
308 {
309 return (const MemChunk*)((char*)this + getChunkSize ());
310 }
311
312 bool
313 isValidSize ()
314 {
315 const MemChunk* nextChunk = getNextChunk (getChunkSize ());
316 return getChunkSize () == nextChunk->getPrevChunkSize () &&
317 isUsed () == nextChunk->isPrevChunkUsed ();
318 }
319
320 void
321 print () const
322 {
323 printf ("-- chunk[ %p ]: size: %zu, used = %s, exact size: %zu\n",
324 static_cast<const void*> (this),
325 getChunkSize (),
326 (isUsed () ? "true " : "false"),
327 getUserSize ());
328 }
329 };
330
334 struct SmallMemChunk : public MemChunk
335 {
336 SmallMemChunk* next; /* double links -- used only if free. */
337 SmallMemChunk* prev;
338 };
339
340 class MemSegment
341 {
342 // MemPool takes the offset of m_pad (see SEGMENT_HEADER).
343 friend class MemPool;
344
345 private:
349 size_type m_size;
353 MemSegment* m_next;
359 size_type m_pad;
360
361 public:
369 MemChunk*
370 init (size_type segSize)
371 {
372 m_size = segSize;
373 m_pad = MemChunk::BIT_USED;
374
375 // We do not initiate m_next since it will be assigned
376 // by the caller anyways.
377
378 size_type chunkSize = getMaxChunkSize ();
379 MemChunk* chunk = getFirstChunk ();
380 chunk->setFreeChunkSize (chunkSize);
381 chunk->getNextChunk (chunkSize)->setFence ();
382 return chunk;
383 }
384
385 MemChunk*
386 getFirstChunk ()
387 {
388 return (MemChunk*)(((char*)this) + offsetof (MemSegment, m_pad));
389 }
390
391 const MemChunk*
392 getFirstChunk () const
393 {
394 return (const MemChunk*)(((char*)this) + offsetof (MemSegment, m_pad));
395 }
396
397 MemChunk*
398 getPastLastChunk ()
399 {
400 return (MemChunk*)(((char*)getFirstChunk ()) + getMaxChunkSize ());
401 }
402
403 const MemChunk*
404 getPastLastChunk () const
405 {
406 return (MemChunk*)(((char*)getFirstChunk ()) + getMaxChunkSize ());
407 }
408
410 getSize () const
411 {
412 return m_size;
413 }
414
415 MemSegment*
416 getNext () const
417 {
418 return m_next;
419 }
420
421 void
422 setNext (MemSegment* seg)
423 {
424 m_next = seg;
425 }
426
428 getMaxChunkSize () const
429 {
430 return (m_size - SEGMENT_OVERHEAD) & MemChunk::BIT_MASK;
431 }
432
433 void
434 print () const
435 {
436 printf ("== segment %p, size: %zu, header: %zu, footer: %zu\n", static_cast<const void*> (this), m_size, offsetof(MemSegment, m_pad), sizeof(MemChunk));
437 const MemChunk* chunk = getFirstChunk ();
438 const MemChunk* lastChunk = getPastLastChunk ();
439 for (;;)
440 {
441 if (chunk < lastChunk)
442 {
443 chunk->print ();
444 chunk = chunk->getNextChunk ();
445 }
446 else
447 {
448 printf ("-- chunk[ %p ]: size: %zu\n",
449 static_cast<const void*> (chunk),
450 chunk->getChunkSize ());
451 break;
452 }
453 }
454 }
455 };
456
457private:
464 static const size_type ALIGNMENT = ALLOCATION_ALIGNMENT;
468 static const size_type ALIGN_MASK = ALIGNMENT - 1;
469 // MemChunk stores BIT_USED and BIT_NOTEXACTSIZE in the low bits of chunk
470 // sizes, so the alignment must leave at least two low bits free.
471 static_assert (ALIGNMENT >= 4, "ALLOCATION_ALIGNMENT must be at least 4.");
472 static_assert (ALIGN_MASK == ~MemChunk::BIT_MASK,
473 "ALLOCATION_ALIGNMENT must match MemChunk::BIT_MASK.");
480 static const size_type NSMALLBINS = 32;
484 static const size_type NTREEBINS = 32;
488 static const size_type SMALLBIN_SHIFT = 3;
492 static const size_type TREEBIN_SHIFT = 8;
496 static const size_type MIN_LARGE_SIZE = (1UL << TREEBIN_SHIFT);
500 static const size_type CHUNK_OVERHEAD = sizeof(MemChunk);
504 static const size_type MIN_LARGE_REQUEST = MIN_LARGE_SIZE - CHUNK_OVERHEAD - ALIGN_MASK;
508 static const size_type MIN_CHUNK_SIZE = ((sizeof(SmallMemChunk) + ALIGN_MASK) & ~ALIGN_MASK);
512 static const size_type MAX_REQUEST = (static_cast<size_type>(-static_cast<long>(MIN_CHUNK_SIZE)) << 2);
517 static const size_type MIN_REQUEST = MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
523 static const size_type SEGMENT_HEADER = offsetof (MemSegment, m_pad);
527 static const size_type SEGMENT_OVERHEAD = ((((SEGMENT_HEADER + ALIGN_MASK) & ~ALIGN_MASK) + sizeof(MemChunk) + +ALIGN_MASK) & ~ALIGN_MASK);
528private:
532 Arena& m_arena;
536 Logger& m_logger;
537
541 size_type m_footprintLimit;
542
546 MemSegment* m_segList;
550 size_type m_trimEmptySegmentsInterval;
554 size_type m_numFrees;
559 size_type m_immediateReleaseThreshold;
560 BinIndexType m_smallMap;
561 BinIndexType m_treeMap;
565 MemChunk* m_dv;
566 size_type m_dvSize;
567
571 CircularList<SmallMemChunk> m_smallLists[NSMALLBINS];
575 PtrTreeType m_largeTrees[NTREEBINS];
576
577 // memory foot print tracking
581 size_type m_footprint;
585 size_type m_maxFootprint;
589 bool m_storingExactSize;
595 const std::uint8_t m_padding;
599 char m_paddingByte;
600public:
612 MemPool (Arena& arena,
613 Logger& logger,
614 std::uint8_t paddingSize = DEFAULT_PADDING_SIZE)
615 : m_arena (arena),
616 m_logger (logger),
617 m_footprintLimit (0),
618 m_segList (nullptr),
619 m_trimEmptySegmentsInterval (DEFAULT_TRIM_EMPTY_SEGMENTS_INTERVAL),
620 m_numFrees (0),
621 m_immediateReleaseThreshold (DEFAULT_IMMEDIATE_RELEASE_THRESHOLD),
622 m_smallMap (0),
623 m_treeMap (0),
624 m_dv (nullptr),
625 m_dvSize (0),
626 m_smallLists (),
627 m_largeTrees (),
628 m_footprint (0),
629 m_maxFootprint (0),
630 m_storingExactSize (paddingSize != 0),
631 m_padding (paddingSize),
632 m_paddingByte (DEFAULT_PADDING_BYTE)
633 {
634 if (m_padding > MAX_PADDING_SIZE)
635 {
636 reportError (nullptr, MEM_ERROR_GENERAL, "padding size cannot exceed 8 bytes.", __FILE__, __LINE__);
637 }
638 }
639
646 {
647 MemSegment* seg = m_segList;
648 while (seg)
649 {
650 void* ptr = seg;
651 size_type size = seg->getSize ();
652 seg = seg->getNext ();
653 m_logger.logFreeSegment (ptr, size);
654 m_arena.freeSegment (ptr, size);
655 }
656 }
657
666 void
668 {
669 m_footprintLimit = footprintLimit;
670 }
671
679 {
680 return m_footprintLimit;
681 }
682
696 void
698 {
699 m_trimEmptySegmentsInterval = interval;
700 }
701
710 {
711 return m_trimEmptySegmentsInterval;
712 }
713
729 void
731 {
732 m_immediateReleaseThreshold = threshold;
733 }
734
743 {
744 return m_immediateReleaseThreshold;
745 }
746
755 T*
757 {
758 MemAllocType_et allocType;
759 MemChunk* chunk = allocateChunk (getMinAllocSize (userSize), allocType);
760 if (chunk == nullptr)
761 {
762 m_logger.logAllocation (nullptr, userSize, MEM_ALLOC_BIG);
763 return nullptr;
764 }
765 setUsed (chunk, userSize);
766 return getUserPointer (chunk, allocType);
767 }
768
785 T*
786 allocateAligned (size_type userSize, size_type alignment)
787 {
788 if (alignment == 0 || (alignment & (alignment - 1)) != 0)
789 {
790 m_logger.logAllocation (nullptr, userSize, MEM_ALLOC_BIG);
791 return nullptr;
792 }
793 if (alignment <= ALIGNMENT)
794 {
795 return allocate (userSize);
796 }
797
798 size_type allocSize = getMinAllocSize (userSize);
799 if (allocSize >= MAX_REQUEST || alignment >= MAX_REQUEST - allocSize)
800 {
801 m_logger.logAllocation (nullptr, userSize, MEM_ALLOC_BIG);
802 return nullptr;
803 }
804 size_type chunkSize = (allocSize < MIN_REQUEST) ? MIN_CHUNK_SIZE : calcChunkSize (allocSize);
805
806 // Allocate enough room to find an aligned position inside the chunk
807 // that leaves a free chunk of at least MIN_CHUNK_SIZE in front of it.
808 MemAllocType_et allocType;
809 MemChunk* chunk = allocateChunk (chunkSize + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD, allocType);
810 if (chunk == nullptr)
811 {
812 m_logger.logAllocation (nullptr, userSize, MEM_ALLOC_BIG);
813 return nullptr;
814 }
815
816 std::uintptr_t mem = reinterpret_cast<std::uintptr_t> (chunk2Mem (chunk));
817 if ((mem & (alignment - 1)) != 0)
818 {
819 // Free the memory in front of the aligned position. The chunk
820 // before it is in use, since free chunks are always coalesced,
821 // so the leading chunk does not need to be coalesced.
822 std::uintptr_t alignedMem = (mem + alignment - 1) & ~static_cast<std::uintptr_t> (alignment - 1);
823 size_type leadSize = static_cast<size_type> (alignedMem - mem);
824 if (leadSize < MIN_CHUNK_SIZE)
825 {
826 leadSize += alignment;
827 }
828 MemChunk* alignedChunk = chunk->getNextChunk (leadSize);
829 size_type alignedSize = chunk->getChunkSize () - leadSize;
830
831 chunk->setFreeChunkSize (leadSize);
832 addChunk (chunk);
833 alignedChunk->setFreeChunkSize (alignedSize);
834 chunk = alignedChunk;
835 }
836
837 // Free the memory after the requested size.
838 size_type remainSize = chunk->getChunkSize () - chunkSize;
839 if (remainSize >= MIN_CHUNK_SIZE)
840 {
841 MemChunk* remainChunk = chunk->getNextChunk (chunkSize);
842 MemChunk* nextChunk = remainChunk->getNextChunk (remainSize);
843 if (!nextChunk->isUsed ())
844 {
845 removeChunk (nextChunk);
846 remainSize += nextChunk->getChunkSize ();
847 }
848 chunk->setFreeChunkSize (chunkSize);
849 remainChunk->setFreeChunkSize (remainSize);
850 addChunk (remainChunk);
851 }
852
853 setUsed (chunk, userSize);
854 return getUserPointer (chunk, allocType);
855 }
856
872 T*
873 reallocate (T* ptr, size_type newUserSize)
874 {
875 if (ptr == nullptr)
876 {
877 return allocate (newUserSize);
878 }
879
880 if (resizeInPlace (ptr, newUserSize))
881 {
882 return ptr;
883 }
884
885 // allocate () fails for a request too large to represent.
886 size_type oldUserSize = mem2Chunk (ptr)->getUserSize ();
887 T* newPtr = allocate (newUserSize);
888 if (newPtr)
889 {
890 memcpy (newPtr, ptr, oldUserSize);
891 deallocate (ptr);
892 }
893 return newPtr;
894 }
895
910 bool
911 resizeInPlace (T* ptr, size_type newUserSize)
912 {
913 if (ptr == nullptr)
914 {
915 return false;
916 }
917
918 MemChunk* chunk = mem2Chunk (ptr);
919
920 // The new chunk must also hold the padding, and a request too large
921 // to represent must not wrap around to a small chunk size.
922 size_type newAllocSize = getMinAllocSize (newUserSize);
923 if (newAllocSize >= MAX_REQUEST)
924 {
925 return false;
926 }
927 size_type newChunkSize = (newAllocSize < MIN_REQUEST) ? MIN_CHUNK_SIZE : calcChunkSize (newAllocSize);
928
929 size_type chunkSize = chunk->getChunkSize ();
930 if (chunkSize < newChunkSize)
931 {
932 // Grow in place if the next chunk is free and large enough.
933 MemChunk* nextChunk = chunk->getNextChunk (chunkSize);
934 if (nextChunk->isUsed () ||
935 chunkSize + nextChunk->getChunkSize () < newChunkSize)
936 {
937 return false;
938 }
939
940 // The size before, as logged; read it before setUsed () changes it.
941 size_type oldUserSize = chunk->getUserSize ();
942 size_type mergedSize = chunkSize + nextChunk->getChunkSize ();
943 removeChunk (nextChunk);
944
945 // The chunk after nextChunk is in use, since free chunks are
946 // always coalesced, so the remainder does not need merging.
947 size_type remainSize = mergedSize - newChunkSize;
948 if (remainSize >= MIN_CHUNK_SIZE)
949 {
950 chunk->setFreeChunkSize (newChunkSize);
951 MemChunk* remainChunk = chunk->getNextChunk (newChunkSize);
952 remainChunk->setFreeChunkSize (remainSize);
953 addChunk (remainChunk);
954 }
955 else
956 {
957 chunk->setFreeChunkSize (mergedSize);
958 }
959 setUsed (chunk, newUserSize);
960 m_logger.logReallocation (ptr, oldUserSize, chunk->getUserSize ());
961 return true;
962 }
963
964 // Shrink, freeing the unused tail if it is large enough, merged with
965 // the next chunk if that one is free.
966 size_type oldUserSize = chunk->getUserSize ();
967 size_type remainSize = chunkSize - newChunkSize;
968 if (remainSize >= MIN_CHUNK_SIZE)
969 {
970 MemChunk* remainChunk = chunk->getNextChunk (newChunkSize);
971 MemChunk* nextChunk = remainChunk->getNextChunk (remainSize);
972
973 if (!nextChunk->isUsed ())
974 {
975 removeChunk (nextChunk);
976 remainSize += nextChunk->getChunkSize ();
977 }
978
979 chunk->setFreeChunkSize (newChunkSize);
980 setUsed (chunk, newUserSize);
981 remainChunk->setFreeChunkSize (remainSize);
982 addChunk (remainChunk);
983 }
984 else
985 {
986 setUsed (chunk, newUserSize);
987 }
988 m_logger.logReallocation (ptr, oldUserSize, chunk->getUserSize ());
989 return true;
990 }
991
1002 T*
1004 {
1005 if (num != 0 && size > (MAX_REQUEST / num))
1006 {
1007 m_logger.logAllocation (nullptr, MAX_REQUEST, MEM_ALLOC_BIG);
1008 return nullptr;
1009 }
1010 size_type totalSize = size * num;
1011 T* ptr = allocate (totalSize);
1012 if (ptr)
1013 {
1014 memset (ptr, 0, totalSize);
1015 }
1016 return ptr;
1017 }
1018
1027 void
1028 deallocate (T* ptr, size_type size = 0)
1029 {
1030 if (ptr != nullptr)
1031 {
1032 MemChunk* chunk = mem2Chunk (ptr);
1033 if (!chunk->isUsed())
1034 {
1035 reportError (ptr, MEM_ERROR_DOUBLE_FREE, "potentially freeing an unused pointer", __FILE__, __LINE__);
1036 }
1037 COOKMEM_ASSERT (chunk->isValidSize ());
1038 size_type chunkSize = chunk->getChunkSize ();
1039 if (m_padding != 0)
1040 {
1041 COOKMEM_ASSERT (chunkSize > CHUNK_OVERHEAD);
1042 size_type userSize = chunk->getUserSize () + CHUNK_OVERHEAD;
1043 COOKMEM_ASSERT (userSize < chunkSize);
1044#if COOKMEM_DEBUG > 0
1045 char diff = (char)(chunkSize - userSize);
1046 COOKMEM_ASSERT ((diff > 0) && ((userSize + diff) == chunkSize));
1047 COOKMEM_ASSERT (*(((char*)chunk) + chunkSize - 1) == diff);
1048#endif // COOKMEM_DEBUG
1049
1050 char* paddingPtr = ((char*)chunk) + userSize;
1051 for (std::uint8_t i = 0; i < m_padding; ++i)
1052 {
1053 if (paddingPtr[i] != m_paddingByte)
1054 {
1055 reportError (ptr, MEM_ERROR_PADDING, "padding byte got modified.", __FILE__, __LINE__);
1056 }
1057 }
1058 }
1059 m_logger.logDeallocation (ptr, chunk->getUserSize ());
1060 chunk->clearUsed ();
1061
1062 bool prevChunkUsed = chunk->isPrevChunkUsed ();
1063 MemChunk* nextChunk = chunk->getNextChunk (chunkSize);
1064 bool nextChunkUsed = nextChunk->isUsed ();
1065
1066 MemChunk* freeChunk;
1067
1068 // Fast path: when only the previous chunk is free, it may be able
1069 // to absorb this chunk without being moved to a different place.
1070 // This is common when memory is freed in allocation order.
1071 if (!prevChunkUsed &&
1072 nextChunkUsed &&
1073 growFreeChunkInPlace (chunk->getPrevChunk (), chunkSize))
1074 {
1075 freeChunk = chunk->getPrevChunk ();
1076 }
1077 else
1078 {
1079 freeChunk = chunk;
1080 size_type freeChunkSize = chunkSize;
1081
1082 if (!prevChunkUsed)
1083 {
1084 MemChunk* prevChunk = chunk->getPrevChunk ();
1085 removeChunk (prevChunk);
1086 freeChunk = prevChunk;
1087 freeChunkSize += prevChunk->getChunkSize ();
1088 }
1089
1090 if (!nextChunkUsed)
1091 {
1092 freeChunkSize += nextChunk->getChunkSize ();
1093 removeChunk (nextChunk);
1094 }
1095
1096 freeChunk->setFreeChunkSize (freeChunkSize);
1097 addChunk (freeChunk);
1098 }
1099
1100 // A large allocation that had a segment of its own is returned
1101 // to the arena right away, rather than at the next trimming pass.
1102 if (m_immediateReleaseThreshold != 0 &&
1103 chunkSize >= m_immediateReleaseThreshold &&
1104 isWholeSegment (freeChunk))
1105 {
1106 releaseSegment (freeChunk);
1107 }
1108
1109 ++m_numFrees;
1110 if (m_numFrees >= m_trimEmptySegmentsInterval)
1111 {
1112 trimEmptySegments ();
1113 }
1114 }
1115 else
1116 {
1117 m_logger.logDeallocation (ptr, size);
1118 }
1119 }
1120
1134 bool
1135 contains (T* ptr, bool checkUsed = false)
1136 {
1137 MemSegment* seg = m_segList;
1138 while (seg)
1139 {
1140 if (reinterpret_cast<char*>(ptr) >= reinterpret_cast<char*>(seg) &&
1141 reinterpret_cast<char*>(ptr) <= (reinterpret_cast<char*>(seg) + seg->getSize ()))
1142 {
1143 if (checkUsed)
1144 {
1145 MemChunk* chunk = mem2Chunk (ptr);
1146 return chunk->isUsed ();
1147 }
1148 return true;
1149 }
1150 seg = seg->getNext ();
1151 }
1152 return false;
1153 }
1154
1158 void
1160 {
1161 COOKMEM_ASSERT ((m_dv == nullptr && m_dvSize == 0) ||
1162 (m_dv != nullptr &&
1163 !m_dv->isUsed () &&
1164 m_dv->getChunkSize () == m_dvSize));
1165
1166 // A tree bin is marked in the tree map if and only if its tree is
1167 // not empty.
1168 for (BinIndexType binIndex = 0; binIndex < NTREEBINS; ++binIndex)
1169 {
1170 COOKMEM_ASSERT (isTreeMapMarked (binIndex) == !treeAt (binIndex).isEmpty ());
1171 }
1172
1173 MemSegment* seg = m_segList;
1174 while (seg)
1175 {
1176 size_type segSize = seg->getSize ();
1177 size_type remainSize = segSize;
1178
1179 MemChunk* firstChunk = seg->getFirstChunk ();
1180 MemChunk* chunk = seg->getPastLastChunk ();
1181
1182 do
1183 {
1184 size_type prevChunkSize = chunk->getPrevChunkSize ();
1185
1186 if (prevChunkSize == 0)
1187 {
1188 break;
1189 }
1190
1191 COOKMEM_ASSERT (prevChunkSize < remainSize);
1192 remainSize -= prevChunkSize;
1193
1194 MemChunk* prevChunk = chunk->getPrevChunk ();
1195 COOKMEM_ASSERT (prevChunkSize == prevChunk->getChunkSize ());
1196
1197 if (!chunk->isPrevChunkUsed ())
1198 {
1199 COOKMEM_ASSERT (isValidChunk (prevChunk));
1200 // Free chunks are always coalesced.
1201 COOKMEM_ASSERT (chunk->isUsed ());
1202 }
1203
1204 chunk = prevChunk;
1205 }
1206 while (chunk >= firstChunk);
1207
1208 COOKMEM_ASSERT (remainSize == SEGMENT_OVERHEAD &&
1209 chunk == firstChunk);
1210 // Only used by the assertions, which release builds omit.
1211 (void) remainSize;
1212
1213 seg = seg->getNext ();
1214 }
1215 }
1216
1217
1232 size_type
1234 {
1235 if (ptr == nullptr)
1236 {
1237 return 0;
1238 }
1239 MemChunk* chunk = mem2Chunk (ptr);
1240 if (chunk->isUsed ())
1241 {
1242 return chunk->getUserSize ();
1243 }
1244 return 0;
1245 }
1246
1262 template<class Visitor>
1263 size_type
1264 forEachAllocation (Visitor visitor) const
1265 {
1266 size_type count = 0;
1267 for (const MemSegment* seg = m_segList; seg != nullptr; seg = seg->getNext ())
1268 {
1269 const MemChunk* lastChunk = seg->getPastLastChunk ();
1270 for (const MemChunk* chunk = seg->getFirstChunk ();
1271 chunk < lastChunk;
1272 chunk = chunk->getNextChunk ())
1273 {
1274 if (chunk->isUsed ())
1275 {
1276 visitor (chunk2Mem (const_cast<MemChunk*> (chunk)), chunk->getUserSize ());
1277 ++count;
1278 }
1279 }
1280 }
1281 return count;
1282 }
1283
1287 void
1289 {
1290 MemSegment* seg = m_segList;
1291 while (seg)
1292 {
1293 void* ptr = seg;
1294 size_type size = seg->getSize ();
1295 seg = seg->getNext ();
1296 m_logger.logFreeSegment (ptr, size);
1297 m_arena.freeSegment (ptr, size);
1298 }
1299 m_segList = nullptr;
1300 m_smallMap = 0;
1301 m_treeMap = 0;
1302 m_footprint = 0;
1303 m_dv = nullptr;
1304 m_dvSize = 0;
1305 memset ((void*)m_largeTrees, 0, sizeof(m_largeTrees));
1306 memset ((void*)m_smallLists, 0, sizeof(m_smallLists));
1307 }
1308
1314 size_type
1316 {
1317 return m_footprint;
1318 }
1319
1325 size_type
1327 {
1328 return m_maxFootprint;
1329 }
1330
1336 bool
1338 {
1339 return m_storingExactSize;
1340 }
1341
1350 void
1352 {
1353 if (m_padding == 0)
1354 {
1355 m_storingExactSize = b;
1356 }
1357 }
1358
1366 bool
1367 isPadding () const
1368 {
1369 return m_padding != 0;
1370 }
1371
1375 std::uint8_t
1377 {
1378 return m_padding;
1379 }
1380
1386 std::uint8_t
1388 {
1389 return (std::uint8_t)m_paddingByte;
1390 }
1391
1398 void
1399 setPaddingByte (std::uint8_t paddingByte)
1400 {
1401 m_paddingByte = (char)paddingByte;
1402 }
1403
1413 static unsigned int
1415 {
1416 BinIndexType binIndex;
1417 cookmem_getLargeBinIndex (chunkSize, binIndex);
1418 return binIndex;
1419 }
1420
1425 void
1426 print () const
1427 {
1428 printf ("**** context: %p ****\n", static_cast<const void*> (this));
1429
1430 MemSegment* seg = m_segList;
1431 while (seg)
1432 {
1433 seg->print ();
1434 seg = seg->getNext ();
1435 }
1436 }
1437
1438private:
1444 void
1445 trimEmptySegments ()
1446 {
1447 m_logger.logTrimEmptySegments ();
1448 MemSegment* seg = m_segList;
1449 MemSegment* prevSeg = nullptr;
1450 while (seg)
1451 {
1452 MemSegment* nextSeg = seg->getNext ();
1453
1454 size_type segSize = seg->getSize ();
1455 MemChunk* firstChunk = seg->getFirstChunk ();
1456 if (!firstChunk->isUsed () &&
1457 firstChunk->getChunkSize () == seg->getMaxChunkSize ())
1458 {
1459 // The entire segment is free, so we can just release the
1460 // segment.
1461 //
1462 // If users want to keep the segment around for caching, they
1463 // can always use CacheMemArena.
1464 removeChunk (firstChunk);
1465
1466 m_footprint -= segSize;
1467 m_logger.logFreeSegment (seg, segSize);
1468 m_arena.freeSegment (seg, segSize);
1469
1470 if (prevSeg == nullptr)
1471 {
1472 m_segList = nextSeg;
1473 }
1474 if (prevSeg != nullptr)
1475 {
1476 prevSeg->setNext (nextSeg);
1477 }
1478 }
1479 else
1480 {
1481 prevSeg = seg;
1482 }
1483 seg = nextSeg;
1484 }
1485 m_numFrees = 0;
1486 }
1487
1495 static inline bool
1496 isWholeSegment (MemChunk* chunk)
1497 {
1498 // Only the first chunk of a segment has a previous size of 0, and
1499 // only the fence at the end of a segment has a size of 0.
1500 return chunk->getPrevChunkSize () == 0 &&
1501 chunk->getNextChunk (chunk->getChunkSize ())->getChunkSize () == 0;
1502 }
1503
1510 void
1511 releaseSegment (MemChunk* chunk)
1512 {
1513 MemSegment* seg = reinterpret_cast<MemSegment*> (reinterpret_cast<char*> (chunk) - SEGMENT_HEADER);
1514 COOKMEM_ASSERT (seg->getFirstChunk () == chunk &&
1515 chunk->getChunkSize () == seg->getMaxChunkSize ());
1516
1517 MemSegment* prevSeg = nullptr;
1518 for (MemSegment* s = m_segList; s != seg; s = s->getNext ())
1519 {
1520 COOKMEM_ASSERT (s != nullptr);
1521 prevSeg = s;
1522 }
1523 if (prevSeg == nullptr)
1524 {
1525 m_segList = seg->getNext ();
1526 }
1527 else
1528 {
1529 prevSeg->setNext (seg->getNext ());
1530 }
1531
1532 removeChunk (chunk);
1533
1534 size_type segSize = seg->getSize ();
1535 m_footprint -= segSize;
1536 m_logger.logFreeSegment (seg, segSize);
1537 m_arena.freeSegment (seg, segSize);
1538 }
1539
1540 static inline BinIndexType
1541 idx2bit (BinIndexType binIndex)
1542 {
1543 return ((BinIndexType) (1) << (binIndex));
1544 }
1545
1552 static inline T*
1553 chunk2Mem (MemChunk* chunk)
1554 {
1555 return ((T*)((char*)(chunk) + sizeof(MemChunk)));
1556 }
1557
1564 static inline MemChunk*
1565 mem2Chunk (T* mem)
1566 {
1567 return ((MemChunk*)((char*)(mem) - sizeof(MemChunk)));
1568 }
1569
1578 static inline size_type
1579 calcChunkSize (size_type requestSize)
1580 {
1581 return (((requestSize) + CHUNK_OVERHEAD + ALIGN_MASK) & ~ALIGN_MASK);
1582 }
1583
1584 static inline size_type
1585 getSmallBinSize (BinIndexType binIndex)
1586 {
1587 return ((binIndex) << SMALLBIN_SHIFT);
1588 }
1589
1590 static inline BinIndexType
1591 getSmallBinIndex (size_type size)
1592 {
1593 return (BinIndexType) ((size) >> SMALLBIN_SHIFT);
1594 }
1595
1596 static inline bool
1597 isSmallChunk (size_type size)
1598 {
1599 return ((size) >> SMALLBIN_SHIFT) < NSMALLBINS;
1600 }
1601
1602 inline PtrTreeType&
1603 treeAt (BinIndexType i)
1604 {
1605 return m_largeTrees[i];
1606 }
1607
1615 static inline size_type
1616 getTreeBinMinSize (BinIndexType binIndex)
1617 {
1618 return (static_cast<size_type> (1) << ((binIndex >> 1) + TREEBIN_SHIFT)) |
1619 (static_cast<size_type> (binIndex & 1) << ((binIndex >> 1) + TREEBIN_SHIFT - 1));
1620 }
1621
1633 inline MemChunk*
1634 treeMalloc (size_type size, size_type limit)
1635 {
1636 MemChunk* chunk = nullptr;
1637 size_type actualSize = size;
1638
1639 BinIndexType binIndex;
1640 cookmem_getLargeBinIndex (size, binIndex);
1641
1642 // Visit only the non-empty bins, starting from the bin of the size,
1643 // using the tree map. Bins hold increasing sizes, so stop at a bin
1644 // whose chunks are all at least the limit.
1645 BinIndexType bits = m_treeMap & ~(idx2bit (binIndex) - 1);
1646 while (bits != 0)
1647 {
1648 cookmem_bit2treeIndex (least_bit (bits), binIndex);
1649 if (getTreeBinMinSize (binIndex) >= limit)
1650 {
1651 break;
1652 }
1653 PtrTreeType& tree = treeAt (binIndex);
1654 COOKMEM_ASSERT (!tree.isEmpty ());
1655 chunk = reinterpret_cast<MemChunk*>(tree.remove(actualSize, limit));
1656 if (chunk != nullptr)
1657 {
1658 if (tree.isEmpty ())
1659 {
1660 clearTreeMap (binIndex);
1661 }
1662 break;
1663 }
1664 bits &= bits - 1;
1665 }
1666
1667 if (chunk != nullptr)
1668 {
1669 return splitChunk (chunk, size);
1670 }
1671 return nullptr;
1672 }
1673
1684 inline MemChunk*
1685 allocateChunk (size_type allocSize, MemAllocType_et& allocType)
1686 {
1687 size_type chunkSize;
1688
1689 if (allocSize < MIN_LARGE_REQUEST)
1690 {
1691 BinIndexType binIndex;
1692 BinIndexType smallBits;
1693 chunkSize = (allocSize < MIN_REQUEST) ? MIN_CHUNK_SIZE : calcChunkSize (allocSize);
1694 binIndex = getSmallBinIndex (chunkSize);
1695 smallBits = m_smallMap >> binIndex;
1696
1697 /*
1698 * Check if two smallest chunk lists that can satisfy the request.
1699 * Note that since the chunk is quite tight, it is not necessary
1700 * to split the chunk since there will not be enough rooms.
1701 */
1702 if ((smallBits & 0x3U) != 0)
1703 {
1704 MemChunk* chunk;
1705 binIndex += ~smallBits & 1; /* Uses next bin if idx empty */
1706
1707 chunk = removeSmallChunkList (binIndex);
1708 COOKMEM_ASSERT(chunk != nullptr && chunk->getChunkSize () == getSmallBinSize (binIndex));
1709
1710 allocType = MEM_ALLOC_SMALL;
1711 return chunk;
1712 }
1713 else
1714 {
1715 if (chunkSize > m_dvSize &&
1716 smallBits != 0)
1717 {
1718 /* Use chunk in next nonempty smallbin */
1719 MemChunk* chunk;
1720 BinIndexType i;
1721 BinIndexType leftbits = (smallBits << binIndex) & left_bits(idx2bit(binIndex));
1722 BinIndexType leastbit = least_bit(leftbits);
1723 cookmem_bit2treeIndex(leastbit, i);
1724
1725 chunk = removeSmallChunkList (i);
1726 COOKMEM_ASSERT(chunk != nullptr && chunk->getChunkSize () == getSmallBinSize (i));
1727
1728 allocType = MEM_ALLOC_SMALL;
1729 return splitChunk (chunk, chunkSize);
1730 }
1731 }
1732 }
1733 else if (allocSize >= MAX_REQUEST)
1734 {
1735 // The request size is too big.
1736 return nullptr;
1737 }
1738 else
1739 {
1740 chunkSize = calcChunkSize (allocSize);
1741 }
1742
1743 MemChunk* chunk;
1744
1745 if (allocSize < MIN_LARGE_REQUEST &&
1746 m_dvSize >= chunkSize)
1747 {
1748 allocType = MEM_ALLOC_DV;
1749 return takeDesignatedVictim (chunkSize);
1750 }
1751
1752 allocType = MEM_ALLOC_NONE;
1753
1754 /*
1755 * Check if we have enough space in existing chunks.
1756 */
1757 if (m_treeMap != 0)
1758 {
1759 // As in dlmalloc, a tree chunk is only used if it fits better
1760 // than the designated victim.
1761 chunk = treeMalloc (chunkSize, (m_dvSize >= chunkSize) ? m_dvSize : ~static_cast<size_type> (0));
1762 if (chunk != nullptr)
1763 {
1764 allocType = MEM_ALLOC_TREE;
1765 }
1766 }
1767 else
1768 {
1769 chunk = nullptr;
1770 }
1771
1772 if (chunk == nullptr &&
1773 m_dvSize >= chunkSize)
1774 {
1775 chunk = takeDesignatedVictim (chunkSize);
1776 allocType = MEM_ALLOC_DV;
1777 }
1778
1779 /*
1780 * At this point, we have to allocate memory from arena.
1781 */
1782 if (chunk == nullptr)
1783 {
1784 chunk = arenaAlloc (chunkSize);
1785 allocType = MEM_ALLOC_ARENA;
1786 }
1787
1788 return chunk;
1789 }
1790
1791
1802 inline MemChunk*
1803 splitChunk (MemChunk* chunk, size_type size)
1804 {
1805 // the size of the 2nd half after the split
1806 size_type remainSize = chunk->getChunkSize () - size;
1807
1808 if (remainSize >= MIN_CHUNK_SIZE)
1809 {
1810 MemChunk* remainChunk = (MemChunk*)((char*)chunk + size);
1811
1812 chunk->setFreeChunkSize (size);
1813
1814 remainChunk->setFreeChunkSize (remainSize);
1815
1816 addChunk (remainChunk);
1817 }
1818 return chunk;
1819 }
1820
1831 inline MemChunk*
1832 takeDesignatedVictim (size_type size)
1833 {
1834 MemChunk* chunk = m_dv;
1835 size_type remainSize = m_dvSize - size;
1836
1837 if (remainSize >= MIN_CHUNK_SIZE)
1838 {
1839 MemChunk* remainChunk = (MemChunk*)((char*)chunk + size);
1840 chunk->setFreeChunkSize (size);
1841 remainChunk->setFreeChunkSize (remainSize);
1842
1843 if (!isSmallChunk (remainSize))
1844 {
1845 // The remainder is still a large chunk, so it simply becomes
1846 // the new designated victim.
1847 m_dv = remainChunk;
1848 m_dvSize = remainSize;
1849 return chunk;
1850 }
1851
1852 m_dv = nullptr;
1853 m_dvSize = 0;
1854 addSmallChunk (remainChunk);
1855 return chunk;
1856 }
1857
1858 m_dv = nullptr;
1859 m_dvSize = 0;
1860 return chunk;
1861 }
1862
1871 MemChunk*
1872 arenaAlloc (size_type chunkSize)
1873 {
1874 size_type estSize; /* allocation size */
1875
1876 estSize = chunkSize + SEGMENT_OVERHEAD;
1877 if (estSize <= chunkSize)
1878 {
1879 // Technically can never reach here due to the MAX_REQUEST value
1880 //
1881 // However it is always good to have a check.
1882 return nullptr;
1883 }
1884
1885 /*
1886 * Check user specified foot print limit
1887 */
1888 if (m_footprintLimit != 0)
1889 {
1890 size_type fp = m_footprint + estSize;
1891 if (fp > m_footprint && fp > m_footprintLimit)
1892 {
1893 // Empty segments count toward the footprint until the next
1894 // trimming pass. Release them before giving up.
1895 trimEmptySegments ();
1896 fp = m_footprint + estSize;
1897 }
1898 if (fp <= m_footprint || fp > m_footprintLimit)
1899 {
1900 return nullptr;
1901 }
1902 }
1903
1904 /*
1905 * Request memory segments from arena.
1906 */
1907 size_type segSize = estSize;
1908 MemSegment* seg = (MemSegment*)m_arena.getSegment (segSize);
1909 m_logger.logGetSegment (seg, segSize);
1910
1911 /*
1912 * Initialize the segment obtained.
1913 */
1914 if (seg)
1915 {
1916 if ((m_footprint += segSize) > m_maxFootprint)
1917 {
1918 m_maxFootprint = m_footprint;
1919 }
1920
1921 MemChunk* chunk = seg->init (segSize);
1922
1923 if (m_segList == nullptr)
1924 {
1925 m_segList = seg;
1926 seg->setNext (nullptr);
1927 }
1928 else
1929 {
1930 seg->setNext (m_segList);
1931 m_segList = seg;
1932 }
1933
1934 return splitChunk (chunk, chunkSize);
1935 }
1936 return nullptr;
1937 }
1938
1939 inline CircularList<SmallMemChunk>&
1940 getSmallChunkList (BinIndexType binIndex)
1941 {
1942 return m_smallLists[binIndex];
1943 }
1944
1945 inline void
1946 addSmallChunk (MemChunk* chunk)
1947 {
1948 BinIndexType I = getSmallBinIndex(chunk->getChunkSize());
1949
1950 CircularList<SmallMemChunk>& freeList = getSmallChunkList(I);
1951 freeList.add ((SmallMemChunk*)chunk);
1952 if (!isSmallMapMarked(I))
1953 markSmallMap(I);
1954 }
1955
1956 inline MemChunk*
1957 removeSmallChunkList (BinIndexType binIndex)
1958 {
1959 CircularList<SmallMemChunk>& freeList = getSmallChunkList (binIndex);
1960 SmallMemChunk* chunk = freeList.remove();
1961 if (freeList.isEmpty ())
1962 {
1963 clearSmallMap (binIndex);
1964 }
1965 return chunk;
1966 }
1967
1968 inline void
1969 removeSmallChunk (MemChunk* chunk)
1970 {
1971 BinIndexType binIndex = getSmallBinIndex (chunk->getChunkSize ());
1972
1973 CircularList<SmallMemChunk>& freeList = getSmallChunkList (binIndex);
1974 if (freeList.remove ((SmallMemChunk*)chunk))
1975 {
1976 clearSmallMap (binIndex);
1977 }
1978 }
1979
1980 inline void
1981 markSmallMap (BinIndexType binIndex)
1982 {
1983 m_smallMap |= idx2bit(binIndex);
1984 }
1985
1986 inline void
1987 clearSmallMap (BinIndexType binIndex)
1988 {
1989 m_smallMap &= ~idx2bit(binIndex);
1990 }
1991
1992 inline bool
1993 isSmallMapMarked (BinIndexType binIndex)
1994 {
1995 return m_smallMap & idx2bit (binIndex);
1996 }
1997
1998 inline void
1999 markTreeMap (BinIndexType binIndex)
2000 {
2001 m_treeMap |= idx2bit (binIndex);
2002 }
2003
2004 inline void
2005 clearTreeMap (BinIndexType binIndex)
2006 {
2007 m_treeMap &= ~idx2bit (binIndex);
2008 }
2009
2010 inline bool
2011 isTreeMapMarked (BinIndexType binIndex)
2012 {
2013 return m_treeMap & idx2bit (binIndex);
2014 }
2015
2016 void
2017 addLargeChunk (MemChunk* chunk)
2018 {
2019 BinIndexType treeBinIndex;
2020 cookmem_getLargeBinIndex(chunk->getChunkSize(), treeBinIndex);
2021 PtrTreeType& tree = treeAt (treeBinIndex);
2022 if (!isTreeMapMarked (treeBinIndex))
2023 {
2024 markTreeMap (treeBinIndex);
2025 }
2026 tree.add(chunk, chunk->getChunkSize());
2027 }
2028
2029 inline void
2030 removeLargeChunk (MemChunk* chunk)
2031 {
2032 BinIndexType treeBinIndex;
2033 cookmem_getLargeBinIndex (chunk->getChunkSize(), treeBinIndex);
2034 PtrTreeType& tree = treeAt (treeBinIndex);
2035
2036 tree.remove (chunk);
2037 if (tree.isEmpty ())
2038 {
2039 clearTreeMap (treeBinIndex);
2040 }
2041 }
2042
2043 inline bool
2044 isValidChunk (MemChunk* chunk)
2045 {
2046 if (chunk == m_dv)
2047 {
2048 return true;
2049 }
2050
2051 if (isSmallChunk (chunk->getChunkSize ()))
2052 {
2053 BinIndexType I = getSmallBinIndex (chunk->getChunkSize ());
2054
2055 CircularList<SmallMemChunk>& freeList = getSmallChunkList (I);
2056 return freeList.contains ((SmallMemChunk*)chunk);
2057 }
2058 else
2059 {
2060 BinIndexType treeBinIndex;
2061 cookmem_getLargeBinIndex (chunk->getChunkSize (), treeBinIndex);
2062 PtrTreeType& tree = treeAt (treeBinIndex);
2063 return tree.contains (chunk);
2064 }
2065 }
2066
2082 inline bool
2083 growFreeChunkInPlace (MemChunk* chunk, size_type extraSize)
2084 {
2085 size_type oldSize = chunk->getChunkSize ();
2086 size_type newSize = oldSize + extraSize;
2087
2088 if (chunk == m_dv)
2089 {
2090 chunk->setFreeChunkSize (newSize);
2091 m_dvSize = newSize;
2092 return true;
2093 }
2094
2095 if (isSmallChunk (oldSize))
2096 {
2097 return false;
2098 }
2099
2100 // The tree bin is determined by the two most significant bits of the
2101 // size (see cookmem_getLargeBinIndex). If the bits that differ are
2102 // all below oldSize / 4, the two most significant bits are unchanged,
2103 // so the chunk stays in the same bin. This check is conservative.
2104 if ((oldSize ^ newSize) > (oldSize >> 2))
2105 {
2106 return false;
2107 }
2108
2109 BinIndexType treeBinIndex;
2110 cookmem_getLargeBinIndex (oldSize, treeBinIndex);
2111 if (!treeAt (treeBinIndex).canGrowInPlace (chunk, newSize))
2112 {
2113 return false;
2114 }
2115
2116 // The size field of the chunk is also the value of its tree node, so
2117 // this updates the tree as well.
2118 chunk->setFreeChunkSize (newSize);
2119 return true;
2120 }
2121
2122 inline void
2123 addChunk (MemChunk* chunk)
2124 {
2125 if (isSmallChunk(chunk->getChunkSize ()))
2126 {
2127 addSmallChunk (chunk);
2128 }
2129 else if (m_dv == nullptr)
2130 {
2131 m_dv = chunk;
2132 m_dvSize = chunk->getChunkSize ();
2133 }
2134 else
2135 {
2136 addLargeChunk (chunk);
2137 }
2138 }
2139
2140 inline void
2141 removeChunk (MemChunk* chunk)
2142 {
2143 if (chunk == m_dv)
2144 {
2145 m_dv = nullptr;
2146 m_dvSize = 0;
2147 }
2148 else if (isSmallChunk (chunk->getChunkSize ()))
2149 {
2150 removeSmallChunk (chunk);
2151 }
2152 else
2153 {
2154 removeLargeChunk (chunk);
2155 }
2156 }
2157
2161 inline size_t
2162 getMinAllocSize (size_type userSize)
2163 {
2164 if (m_padding == 0)
2165 {
2166 return userSize;
2167 }
2168 if (userSize > (MAX_REQUEST - m_padding - 1))
2169 {
2170 return MAX_REQUEST;
2171 }
2172 // +1 for the size metadata
2173 return userSize + m_padding + 1;
2174 }
2175
2176 inline void
2177 setUsed (MemChunk* chunk, size_type userSize)
2178 {
2179 chunk->setUsedSize (m_storingExactSize, userSize);
2180
2181 // if we are padding, userSize will always be smaller
2182 // than the chunkSize
2183 if (m_padding != 0)
2184 {
2185 char* paddingPtr = ((char*)chunk) + userSize + CHUNK_OVERHEAD;
2186 for (std::uint8_t i = 0; i < m_padding; ++i)
2187 {
2188 paddingPtr[i] = m_paddingByte;
2189 }
2190 }
2191 }
2192
2209#if defined(_MSC_VER)
2210#pragma warning(push)
2211// The loggers of CookMem always throw, so MSVC finds the throw below
2212// unreachable (C4702). It is needed for loggers that return.
2213#pragma warning(disable: 4702)
2214#endif
2215 void
2216 reportError (void* ptr, MemError_et error, const char* message, const char* file, int line)
2217 {
2218 m_logger.logError (ptr, error, message, file, line);
2219 throw Exception (error, message, file, line);
2220 }
2221#if defined(_MSC_VER)
2222#pragma warning(pop)
2223#endif
2224
2225 inline T*
2226 getUserPointer (MemChunk* chunk, MemAllocType_et allocType)
2227 {
2228 T* userPtr = chunk2Mem (chunk);
2229 // Log the size the chunk reports, which deallocate () logs too.
2230 // Without the exact size, it is the requested size rounded up.
2231 m_logger.logAllocation (userPtr, chunk->getUserSize (), allocType);
2232 return userPtr;
2233 }
2234};
2235
2236#undef cookmem_getLargeBinIndex
2237#undef cookmem_bit2treeIndex
2238
2239} // namespace cookmem
2240
2241#endif // COOK_MEM_POOL_H
Definition exception.h:39
size_type getFootprintLimit() const
Definition pool.h:678
void setTrimEmptySegmentsInterval(size_type interval)
Definition pool.h:697
bool contains(T *ptr, bool checkUsed=false)
Definition pool.h:1135
bool isStoringExactSize() const
Definition pool.h:1337
~MemPool()
Definition pool.h:645
static unsigned int getTreeBinIndex(size_type chunkSize)
Definition pool.h:1414
size_type getUserSize(T *ptr)
Definition pool.h:1233
size_type forEachAllocation(Visitor visitor) const
Definition pool.h:1264
T * callocate(size_type num, size_type size)
Definition pool.h:1003
void setStoringExactSize(bool b)
Definition pool.h:1351
void validate()
Definition pool.h:1159
T * reallocate(T *ptr, size_type newUserSize)
Definition pool.h:873
void print() const
Definition pool.h:1426
bool resizeInPlace(T *ptr, size_type newUserSize)
Definition pool.h:911
std::uint8_t getPaddingSize() const
Definition pool.h:1376
std::uint8_t getPaddingByte() const
Definition pool.h:1387
std::size_t size_type
Definition pool.h:171
MemPool(Arena &arena, Logger &logger, std::uint8_t paddingSize=DEFAULT_PADDING_SIZE)
Definition pool.h:612
const T * const_pointer
Definition pool.h:179
void deallocate(T *ptr, size_type size=0)
Definition pool.h:1028
size_type getFootprint() const
Definition pool.h:1315
void setImmediateReleaseThreshold(size_type threshold)
Definition pool.h:730
void releaseAll()
Definition pool.h:1288
size_type getImmediateReleaseThreshold() const
Definition pool.h:742
size_type getMaxFootprint() const
Definition pool.h:1326
void setPaddingByte(std::uint8_t paddingByte)
Definition pool.h:1399
std::ptrdiff_t difference_type
Definition pool.h:173
size_type getTrimEmptySegmentsInterval() const
Definition pool.h:709
bool isPadding() const
Definition pool.h:1367
T * allocateAligned(size_type userSize, size_type alignment)
Definition pool.h:786
T * allocate(size_type userSize)
Definition pool.h:756
void setFootprintLimit(size_type footprintLimit)
Definition pool.h:667
Definition allocator.h:29
const char DEFAULT_PADDING_BYTE
Definition config.h:64
const std::size_t DEFAULT_IMMEDIATE_RELEASE_THRESHOLD
Definition config.h:46
MemError_et
Definition exception.h:28
@ MEM_ERROR_PADDING
padding bytes after an allocation were overwritten
Definition exception.h:32
@ MEM_ERROR_GENERAL
general error
Definition exception.h:29
@ MEM_ERROR_DOUBLE_FREE
freeing an already free pointer
Definition exception.h:31
const std::size_t DEFAULT_TRIM_EMPTY_SEGMENTS_INTERVAL
Definition config.h:41
const std::uint8_t DEFAULT_PADDING_SIZE
Definition config.h:56
const std::uint8_t MAX_PADDING_SIZE
Definition config.h:60
MemAllocType_et
Definition logger.h:31
@ MEM_ALLOC_TREE
Definition logger.h:37
@ MEM_ALLOC_BIG
Definition logger.h:43
@ MEM_ALLOC_ARENA
Definition logger.h:41
@ MEM_ALLOC_DV
Definition logger.h:39
@ MEM_ALLOC_SMALL
Definition logger.h:35
@ MEM_ALLOC_NONE
Definition logger.h:33
const std::size_t ALLOCATION_ALIGNMENT
Definition config.h:36