1 //===-- sanitizer_allocator_primary32.h -------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Part of the Sanitizer Allocator.
12 //===----------------------------------------------------------------------===//
13 #ifndef SANITIZER_ALLOCATOR_H
14 #error This file must be included inside sanitizer_allocator.h
17 template<class SizeClassAllocator> struct SizeClassAllocator32LocalCache;
19 // SizeClassAllocator32 -- allocator for 32-bit address space.
20 // This allocator can theoretically be used on 64-bit arch, but there it is less
21 // efficient than SizeClassAllocator64.
23 // [kSpaceBeg, kSpaceBeg + kSpaceSize) is the range of addresses which can
24 // be returned by MmapOrDie().
27 // a result of a single call to MmapAlignedOrDieOnFatalError(kRegionSize,
29 // Since the regions are aligned by kRegionSize, there are exactly
30 // kNumPossibleRegions possible regions in the address space and so we keep
31 // a ByteMap possible_regions to store the size classes of each Region.
32 // 0 size class means the region is not used by the allocator.
34 // One Region is used to allocate chunks of a single size class.
35 // A Region looks like this:
36 // UserChunk1 .. UserChunkN <gap> MetaChunkN .. MetaChunk1
38 // In order to avoid false sharing the objects of this class should be
39 // chache-line aligned.
41 struct SizeClassAllocator32FlagMasks { // Bit masks.
43 kRandomShuffleChunks = 1,
44 kUseSeparateSizeClassForBatch = 2,
48 template <class Params>
49 class SizeClassAllocator32 {
51 static const uptr kSpaceBeg = Params::kSpaceBeg;
52 static const u64 kSpaceSize = Params::kSpaceSize;
53 static const uptr kMetadataSize = Params::kMetadataSize;
54 typedef typename Params::SizeClassMap SizeClassMap;
55 static const uptr kRegionSizeLog = Params::kRegionSizeLog;
56 typedef typename Params::ByteMap ByteMap;
57 typedef typename Params::MapUnmapCallback MapUnmapCallback;
59 static const bool kRandomShuffleChunks = Params::kFlags &
60 SizeClassAllocator32FlagMasks::kRandomShuffleChunks;
61 static const bool kUseSeparateSizeClassForBatch = Params::kFlags &
62 SizeClassAllocator32FlagMasks::kUseSeparateSizeClassForBatch;
64 struct TransferBatch {
65 static const uptr kMaxNumCached = SizeClassMap::kMaxNumCachedHint - 2;
66 void SetFromArray(void *batch[], uptr count) {
67 DCHECK_LE(count, kMaxNumCached);
69 for (uptr i = 0; i < count; i++)
72 uptr Count() const { return count_; }
73 void Clear() { count_ = 0; }
75 batch_[count_++] = ptr;
76 DCHECK_LE(count_, kMaxNumCached);
78 void CopyToArray(void *to_batch[]) const {
79 for (uptr i = 0, n = Count(); i < n; i++)
80 to_batch[i] = batch_[i];
83 // How much memory do we need for a batch containing n elements.
84 static uptr AllocationSizeRequiredForNElements(uptr n) {
85 return sizeof(uptr) * 2 + sizeof(void *) * n;
87 static uptr MaxCached(uptr size) {
88 return Min(kMaxNumCached, SizeClassMap::MaxCachedHint(size));
95 void *batch_[kMaxNumCached];
98 static const uptr kBatchSize = sizeof(TransferBatch);
99 COMPILER_CHECK((kBatchSize & (kBatchSize - 1)) == 0);
100 COMPILER_CHECK(kBatchSize == SizeClassMap::kMaxNumCachedHint * sizeof(uptr));
102 static uptr ClassIdToSize(uptr class_id) {
103 return (class_id == SizeClassMap::kBatchClassID) ?
104 kBatchSize : SizeClassMap::Size(class_id);
107 typedef SizeClassAllocator32<Params> ThisT;
108 typedef SizeClassAllocator32LocalCache<ThisT> AllocatorCache;
110 void Init(s32 release_to_os_interval_ms) {
111 possible_regions.Init();
112 internal_memset(size_class_info_array, 0, sizeof(size_class_info_array));
115 s32 ReleaseToOSIntervalMs() const {
116 return kReleaseToOSIntervalNever;
119 void SetReleaseToOSIntervalMs(s32 release_to_os_interval_ms) {
120 // This is empty here. Currently only implemented in 64-bit allocator.
123 void ForceReleaseToOS() {
124 // Currently implemented in 64-bit allocator only.
127 void *MapWithCallback(uptr size) {
128 void *res = MmapOrDie(size, PrimaryAllocatorName);
129 MapUnmapCallback().OnMap((uptr)res, size);
133 void UnmapWithCallback(uptr beg, uptr size) {
134 MapUnmapCallback().OnUnmap(beg, size);
135 UnmapOrDie(reinterpret_cast<void *>(beg), size);
138 static bool CanAllocate(uptr size, uptr alignment) {
139 return size <= SizeClassMap::kMaxSize &&
140 alignment <= SizeClassMap::kMaxSize;
143 void *GetMetaData(const void *p) {
144 CHECK(PointerIsMine(p));
145 uptr mem = reinterpret_cast<uptr>(p);
146 uptr beg = ComputeRegionBeg(mem);
147 uptr size = ClassIdToSize(GetSizeClass(p));
148 u32 offset = mem - beg;
149 uptr n = offset / (u32)size; // 32-bit division
150 uptr meta = (beg + kRegionSize) - (n + 1) * kMetadataSize;
151 return reinterpret_cast<void*>(meta);
154 NOINLINE TransferBatch *AllocateBatch(AllocatorStats *stat, AllocatorCache *c,
156 DCHECK_LT(class_id, kNumClasses);
157 SizeClassInfo *sci = GetSizeClassInfo(class_id);
158 SpinMutexLock l(&sci->mutex);
159 if (sci->free_list.empty()) {
160 if (UNLIKELY(!PopulateFreeList(stat, c, sci, class_id)))
162 DCHECK(!sci->free_list.empty());
164 TransferBatch *b = sci->free_list.front();
165 sci->free_list.pop_front();
169 NOINLINE void DeallocateBatch(AllocatorStats *stat, uptr class_id,
171 DCHECK_LT(class_id, kNumClasses);
172 CHECK_GT(b->Count(), 0);
173 SizeClassInfo *sci = GetSizeClassInfo(class_id);
174 SpinMutexLock l(&sci->mutex);
175 sci->free_list.push_front(b);
178 bool PointerIsMine(const void *p) {
179 uptr mem = reinterpret_cast<uptr>(p);
180 if (mem < kSpaceBeg || mem >= kSpaceBeg + kSpaceSize)
182 return GetSizeClass(p) != 0;
185 uptr GetSizeClass(const void *p) {
186 return possible_regions[ComputeRegionId(reinterpret_cast<uptr>(p))];
189 void *GetBlockBegin(const void *p) {
190 CHECK(PointerIsMine(p));
191 uptr mem = reinterpret_cast<uptr>(p);
192 uptr beg = ComputeRegionBeg(mem);
193 uptr size = ClassIdToSize(GetSizeClass(p));
194 u32 offset = mem - beg;
195 u32 n = offset / (u32)size; // 32-bit division
196 uptr res = beg + (n * (u32)size);
197 return reinterpret_cast<void*>(res);
200 uptr GetActuallyAllocatedSize(void *p) {
201 CHECK(PointerIsMine(p));
202 return ClassIdToSize(GetSizeClass(p));
205 uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); }
207 uptr TotalMemoryUsed() {
208 // No need to lock here.
210 for (uptr i = 0; i < kNumPossibleRegions; i++)
211 if (possible_regions[i])
216 void TestOnlyUnmap() {
217 for (uptr i = 0; i < kNumPossibleRegions; i++)
218 if (possible_regions[i])
219 UnmapWithCallback((i * kRegionSize), kRegionSize);
222 // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
223 // introspection API.
225 for (uptr i = 0; i < kNumClasses; i++) {
226 GetSizeClassInfo(i)->mutex.Lock();
231 for (int i = kNumClasses - 1; i >= 0; i--) {
232 GetSizeClassInfo(i)->mutex.Unlock();
236 // Iterate over all existing chunks.
237 // The allocator must be locked when calling this function.
238 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
239 for (uptr region = 0; region < kNumPossibleRegions; region++)
240 if (possible_regions[region]) {
241 uptr chunk_size = ClassIdToSize(possible_regions[region]);
242 uptr max_chunks_in_region = kRegionSize / (chunk_size + kMetadataSize);
243 uptr region_beg = region * kRegionSize;
244 for (uptr chunk = region_beg;
245 chunk < region_beg + max_chunks_in_region * chunk_size;
246 chunk += chunk_size) {
247 // Too slow: CHECK_EQ((void *)chunk, GetBlockBegin((void *)chunk));
248 callback(chunk, arg);
255 static uptr AdditionalSize() { return 0; }
257 typedef SizeClassMap SizeClassMapT;
258 static const uptr kNumClasses = SizeClassMap::kNumClasses;
261 static const uptr kRegionSize = 1 << kRegionSizeLog;
262 static const uptr kNumPossibleRegions = kSpaceSize / kRegionSize;
264 struct ALIGNED(SANITIZER_CACHE_LINE_SIZE) SizeClassInfo {
265 StaticSpinMutex mutex;
266 IntrusiveList<TransferBatch> free_list;
269 COMPILER_CHECK(sizeof(SizeClassInfo) % kCacheLineSize == 0);
271 uptr ComputeRegionId(uptr mem) {
272 const uptr res = mem >> kRegionSizeLog;
273 CHECK_LT(res, kNumPossibleRegions);
277 uptr ComputeRegionBeg(uptr mem) {
278 return mem & ~(kRegionSize - 1);
281 uptr AllocateRegion(AllocatorStats *stat, uptr class_id) {
282 DCHECK_LT(class_id, kNumClasses);
283 const uptr res = reinterpret_cast<uptr>(MmapAlignedOrDieOnFatalError(
284 kRegionSize, kRegionSize, PrimaryAllocatorName));
287 MapUnmapCallback().OnMap(res, kRegionSize);
288 stat->Add(AllocatorStatMapped, kRegionSize);
289 CHECK(IsAligned(res, kRegionSize));
290 possible_regions.set(ComputeRegionId(res), static_cast<u8>(class_id));
294 SizeClassInfo *GetSizeClassInfo(uptr class_id) {
295 DCHECK_LT(class_id, kNumClasses);
296 return &size_class_info_array[class_id];
299 bool PopulateBatches(AllocatorCache *c, SizeClassInfo *sci, uptr class_id,
300 TransferBatch **current_batch, uptr max_count,
301 uptr *pointers_array, uptr count) {
302 // If using a separate class for batches, we do not need to shuffle it.
303 if (kRandomShuffleChunks && (!kUseSeparateSizeClassForBatch ||
304 class_id != SizeClassMap::kBatchClassID))
305 RandomShuffle(pointers_array, count, &sci->rand_state);
306 TransferBatch *b = *current_batch;
307 for (uptr i = 0; i < count; i++) {
309 b = c->CreateBatch(class_id, this, (TransferBatch*)pointers_array[i]);
314 b->Add((void*)pointers_array[i]);
315 if (b->Count() == max_count) {
316 sci->free_list.push_back(b);
324 bool PopulateFreeList(AllocatorStats *stat, AllocatorCache *c,
325 SizeClassInfo *sci, uptr class_id) {
326 const uptr region = AllocateRegion(stat, class_id);
327 if (UNLIKELY(!region))
329 if (kRandomShuffleChunks)
330 if (UNLIKELY(sci->rand_state == 0))
331 // The random state is initialized from ASLR (PIE) and time.
332 sci->rand_state = reinterpret_cast<uptr>(sci) ^ NanoTime();
333 const uptr size = ClassIdToSize(class_id);
334 const uptr n_chunks = kRegionSize / (size + kMetadataSize);
335 const uptr max_count = TransferBatch::MaxCached(size);
336 DCHECK_GT(max_count, 0);
337 TransferBatch *b = nullptr;
338 constexpr uptr kShuffleArraySize = 48;
339 uptr shuffle_array[kShuffleArraySize];
341 for (uptr i = region; i < region + n_chunks * size; i += size) {
342 shuffle_array[count++] = i;
343 if (count == kShuffleArraySize) {
344 if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count,
345 shuffle_array, count)))
351 if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count,
352 shuffle_array, count)))
356 CHECK_GT(b->Count(), 0);
357 sci->free_list.push_back(b);
362 ByteMap possible_regions;
363 SizeClassInfo size_class_info_array[kNumClasses];