]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_primary32.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_allocator_primary32.h
1 //===-- sanitizer_allocator_primary32.h -------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Part of the Sanitizer Allocator.
11 //
12 //===----------------------------------------------------------------------===//
13 #ifndef SANITIZER_ALLOCATOR_H
14 #error This file must be included inside sanitizer_allocator.h
15 #endif
16
17 template<class SizeClassAllocator> struct SizeClassAllocator32LocalCache;
18
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.
22 //
23 // [kSpaceBeg, kSpaceBeg + kSpaceSize) is the range of addresses which can
24 // be returned by MmapOrDie().
25 //
26 // Region:
27 //   a result of a single call to MmapAlignedOrDieOnFatalError(kRegionSize,
28 //                                                             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.
33 //
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
37 //
38 // In order to avoid false sharing the objects of this class should be
39 // chache-line aligned.
40
41 struct SizeClassAllocator32FlagMasks {  //  Bit masks.
42   enum {
43     kRandomShuffleChunks = 1,
44     kUseSeparateSizeClassForBatch = 2,
45   };
46 };
47
48 template <class Params>
49 class SizeClassAllocator32 {
50  public:
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;
58
59   static const bool kRandomShuffleChunks = Params::kFlags &
60       SizeClassAllocator32FlagMasks::kRandomShuffleChunks;
61   static const bool kUseSeparateSizeClassForBatch = Params::kFlags &
62       SizeClassAllocator32FlagMasks::kUseSeparateSizeClassForBatch;
63
64   struct TransferBatch {
65     static const uptr kMaxNumCached = SizeClassMap::kMaxNumCachedHint - 2;
66     void SetFromArray(void *batch[], uptr count) {
67       DCHECK_LE(count, kMaxNumCached);
68       count_ = count;
69       for (uptr i = 0; i < count; i++)
70         batch_[i] = batch[i];
71     }
72     uptr Count() const { return count_; }
73     void Clear() { count_ = 0; }
74     void Add(void *ptr) {
75       batch_[count_++] = ptr;
76       DCHECK_LE(count_, kMaxNumCached);
77     }
78     void CopyToArray(void *to_batch[]) const {
79       for (uptr i = 0, n = Count(); i < n; i++)
80         to_batch[i] = batch_[i];
81     }
82
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;
86     }
87     static uptr MaxCached(uptr size) {
88       return Min(kMaxNumCached, SizeClassMap::MaxCachedHint(size));
89     }
90
91     TransferBatch *next;
92
93    private:
94     uptr count_;
95     void *batch_[kMaxNumCached];
96   };
97
98   static const uptr kBatchSize = sizeof(TransferBatch);
99   COMPILER_CHECK((kBatchSize & (kBatchSize - 1)) == 0);
100   COMPILER_CHECK(kBatchSize == SizeClassMap::kMaxNumCachedHint * sizeof(uptr));
101
102   static uptr ClassIdToSize(uptr class_id) {
103     return (class_id == SizeClassMap::kBatchClassID) ?
104         kBatchSize : SizeClassMap::Size(class_id);
105   }
106
107   typedef SizeClassAllocator32<Params> ThisT;
108   typedef SizeClassAllocator32LocalCache<ThisT> AllocatorCache;
109
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));
113   }
114
115   s32 ReleaseToOSIntervalMs() const {
116     return kReleaseToOSIntervalNever;
117   }
118
119   void SetReleaseToOSIntervalMs(s32 release_to_os_interval_ms) {
120     // This is empty here. Currently only implemented in 64-bit allocator.
121   }
122
123   void ForceReleaseToOS() {
124     // Currently implemented in 64-bit allocator only.
125   }
126
127   void *MapWithCallback(uptr size) {
128     void *res = MmapOrDie(size, PrimaryAllocatorName);
129     MapUnmapCallback().OnMap((uptr)res, size);
130     return res;
131   }
132
133   void UnmapWithCallback(uptr beg, uptr size) {
134     MapUnmapCallback().OnUnmap(beg, size);
135     UnmapOrDie(reinterpret_cast<void *>(beg), size);
136   }
137
138   static bool CanAllocate(uptr size, uptr alignment) {
139     return size <= SizeClassMap::kMaxSize &&
140       alignment <= SizeClassMap::kMaxSize;
141   }
142
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);
152   }
153
154   NOINLINE TransferBatch *AllocateBatch(AllocatorStats *stat, AllocatorCache *c,
155                                         uptr class_id) {
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)))
161         return nullptr;
162       DCHECK(!sci->free_list.empty());
163     }
164     TransferBatch *b = sci->free_list.front();
165     sci->free_list.pop_front();
166     return b;
167   }
168
169   NOINLINE void DeallocateBatch(AllocatorStats *stat, uptr class_id,
170                                 TransferBatch *b) {
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);
176   }
177
178   bool PointerIsMine(const void *p) {
179     uptr mem = reinterpret_cast<uptr>(p);
180     if (mem < kSpaceBeg || mem >= kSpaceBeg + kSpaceSize)
181       return false;
182     return GetSizeClass(p) != 0;
183   }
184
185   uptr GetSizeClass(const void *p) {
186     return possible_regions[ComputeRegionId(reinterpret_cast<uptr>(p))];
187   }
188
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);
198   }
199
200   uptr GetActuallyAllocatedSize(void *p) {
201     CHECK(PointerIsMine(p));
202     return ClassIdToSize(GetSizeClass(p));
203   }
204
205   uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); }
206
207   uptr TotalMemoryUsed() {
208     // No need to lock here.
209     uptr res = 0;
210     for (uptr i = 0; i < kNumPossibleRegions; i++)
211       if (possible_regions[i])
212         res += kRegionSize;
213     return res;
214   }
215
216   void TestOnlyUnmap() {
217     for (uptr i = 0; i < kNumPossibleRegions; i++)
218       if (possible_regions[i])
219         UnmapWithCallback((i * kRegionSize), kRegionSize);
220   }
221
222   // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
223   // introspection API.
224   void ForceLock() {
225     for (uptr i = 0; i < kNumClasses; i++) {
226       GetSizeClassInfo(i)->mutex.Lock();
227     }
228   }
229
230   void ForceUnlock() {
231     for (int i = kNumClasses - 1; i >= 0; i--) {
232       GetSizeClassInfo(i)->mutex.Unlock();
233     }
234   }
235
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);
249         }
250       }
251   }
252
253   void PrintStats() {}
254
255   static uptr AdditionalSize() { return 0; }
256
257   typedef SizeClassMap SizeClassMapT;
258   static const uptr kNumClasses = SizeClassMap::kNumClasses;
259
260  private:
261   static const uptr kRegionSize = 1 << kRegionSizeLog;
262   static const uptr kNumPossibleRegions = kSpaceSize / kRegionSize;
263
264   struct ALIGNED(SANITIZER_CACHE_LINE_SIZE) SizeClassInfo {
265     StaticSpinMutex mutex;
266     IntrusiveList<TransferBatch> free_list;
267     u32 rand_state;
268   };
269   COMPILER_CHECK(sizeof(SizeClassInfo) % kCacheLineSize == 0);
270
271   uptr ComputeRegionId(uptr mem) {
272     const uptr res = mem >> kRegionSizeLog;
273     CHECK_LT(res, kNumPossibleRegions);
274     return res;
275   }
276
277   uptr ComputeRegionBeg(uptr mem) {
278     return mem & ~(kRegionSize - 1);
279   }
280
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));
285     if (UNLIKELY(!res))
286       return 0;
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));
291     return res;
292   }
293
294   SizeClassInfo *GetSizeClassInfo(uptr class_id) {
295     DCHECK_LT(class_id, kNumClasses);
296     return &size_class_info_array[class_id];
297   }
298
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++) {
308       if (!b) {
309         b = c->CreateBatch(class_id, this, (TransferBatch*)pointers_array[i]);
310         if (UNLIKELY(!b))
311           return false;
312         b->Clear();
313       }
314       b->Add((void*)pointers_array[i]);
315       if (b->Count() == max_count) {
316         sci->free_list.push_back(b);
317         b = nullptr;
318       }
319     }
320     *current_batch = b;
321     return true;
322   }
323
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))
328       return false;
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];
340     uptr count = 0;
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)))
346           return false;
347         count = 0;
348       }
349     }
350     if (count) {
351       if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count,
352                                     shuffle_array, count)))
353         return false;
354     }
355     if (b) {
356       CHECK_GT(b->Count(), 0);
357       sci->free_list.push_back(b);
358     }
359     return true;
360   }
361
362   ByteMap possible_regions;
363   SizeClassInfo size_class_info_array[kNumClasses];
364 };