Bug Summary

File:projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h
Warning:line 154, column 23
The result of the left shift is undefined due to shifting '256' by '4611686018427387900', which is unrepresentable in the unsigned version of the return type '__sanitizer::uptr'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name scudo_allocator.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=all -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D clang_rt_scudo_dynamic_x86_64_EXPORTS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/projects/compiler-rt/lib/scudo -I /build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -I /build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/.. -U NDEBUG -D GWP_ASAN_HOOKS -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -Wno-unused-parameter -Wno-variadic-macros -Wno-non-virtual-dtor -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/projects/compiler-rt/lib/scudo -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -fno-rtti -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/scudo_allocator.cpp

/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/scudo_allocator.cpp

1//===-- scudo_allocator.cpp -------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// Scudo Hardened Allocator implementation.
10/// It uses the sanitizer_common allocator as a base and aims at mitigating
11/// heap corruption vulnerabilities. It provides a checksum-guarded chunk
12/// header, a delayed free list, and additional sanity checks.
13///
14//===----------------------------------------------------------------------===//
15
16#include "scudo_allocator.h"
17#include "scudo_crc32.h"
18#include "scudo_errors.h"
19#include "scudo_flags.h"
20#include "scudo_interface_internal.h"
21#include "scudo_tsd.h"
22#include "scudo_utils.h"
23
24#include "sanitizer_common/sanitizer_allocator_checks.h"
25#include "sanitizer_common/sanitizer_allocator_interface.h"
26#include "sanitizer_common/sanitizer_quarantine.h"
27
28#ifdef GWP_ASAN_HOOKS1
29# include "gwp_asan/guarded_pool_allocator.h"
30# include "gwp_asan/optional/backtrace.h"
31# include "gwp_asan/optional/options_parser.h"
32#endif // GWP_ASAN_HOOKS
33
34#include <errno(*__errno_location ()).h>
35#include <string.h>
36
37namespace __scudo {
38
39// Global static cookie, initialized at start-up.
40static u32 Cookie;
41
42// We default to software CRC32 if the alternatives are not supported, either
43// at compilation or at runtime.
44static atomic_uint8_t HashAlgorithm = { CRC32Software };
45
46INLINEinline u32 computeCRC32(u32 Crc, uptr Value, uptr *Array, uptr ArraySize) {
47 // If the hardware CRC32 feature is defined here, it was enabled everywhere,
48 // as opposed to only for scudo_crc32.cpp. This means that other hardware
49 // specific instructions were likely emitted at other places, and as a
50 // result there is no reason to not use it here.
51#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
52 Crc = CRC32_INTRINSIC(Crc, Value);
53 for (uptr i = 0; i < ArraySize; i++)
54 Crc = CRC32_INTRINSIC(Crc, Array[i]);
55 return Crc;
56#else
57 if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) {
58 Crc = computeHardwareCRC32(Crc, Value);
59 for (uptr i = 0; i < ArraySize; i++)
60 Crc = computeHardwareCRC32(Crc, Array[i]);
61 return Crc;
62 }
63 Crc = computeSoftwareCRC32(Crc, Value);
64 for (uptr i = 0; i < ArraySize; i++)
65 Crc = computeSoftwareCRC32(Crc, Array[i]);
66 return Crc;
67#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
68}
69
70static BackendT &getBackend();
71
72namespace Chunk {
73 static INLINEinline AtomicPackedHeader *getAtomicHeader(void *Ptr) {
74 return reinterpret_cast<AtomicPackedHeader *>(reinterpret_cast<uptr>(Ptr) -
75 getHeaderSize());
76 }
77 static INLINEinline
78 const AtomicPackedHeader *getConstAtomicHeader(const void *Ptr) {
79 return reinterpret_cast<const AtomicPackedHeader *>(
80 reinterpret_cast<uptr>(Ptr) - getHeaderSize());
81 }
82
83 static INLINEinline bool isAligned(const void *Ptr) {
84 return IsAligned(reinterpret_cast<uptr>(Ptr), MinAlignment);
85 }
86
87 // We can't use the offset member of the chunk itself, as we would double
88 // fetch it without any warranty that it wouldn't have been tampered. To
89 // prevent this, we work with a local copy of the header.
90 static INLINEinline void *getBackendPtr(const void *Ptr, UnpackedHeader *Header) {
91 return reinterpret_cast<void *>(reinterpret_cast<uptr>(Ptr) -
92 getHeaderSize() - (Header->Offset << MinAlignmentLog));
93 }
94
95 // Returns the usable size for a chunk, meaning the amount of bytes from the
96 // beginning of the user data to the end of the backend allocated chunk.
97 static INLINEinline uptr getUsableSize(const void *Ptr, UnpackedHeader *Header) {
98 const uptr ClassId = Header->ClassId;
99 if (ClassId)
100 return PrimaryT::ClassIdToSize(ClassId) - getHeaderSize() -
101 (Header->Offset << MinAlignmentLog);
102 return SecondaryT::GetActuallyAllocatedSize(
103 getBackendPtr(Ptr, Header)) - getHeaderSize();
104 }
105
106 // Returns the size the user requested when allocating the chunk.
107 static INLINEinline uptr getSize(const void *Ptr, UnpackedHeader *Header) {
108 const uptr SizeOrUnusedBytes = Header->SizeOrUnusedBytes;
109 if (Header->ClassId)
110 return SizeOrUnusedBytes;
111 return SecondaryT::GetActuallyAllocatedSize(
112 getBackendPtr(Ptr, Header)) - getHeaderSize() - SizeOrUnusedBytes;
113 }
114
115 // Compute the checksum of the chunk pointer and its header.
116 static INLINEinline u16 computeChecksum(const void *Ptr, UnpackedHeader *Header) {
117 UnpackedHeader ZeroChecksumHeader = *Header;
118 ZeroChecksumHeader.Checksum = 0;
119 uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)];
120 memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder));
121 const u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(Ptr),
122 HeaderHolder, ARRAY_SIZE(HeaderHolder)(sizeof(HeaderHolder)/sizeof((HeaderHolder)[0])));
123 return static_cast<u16>(Crc);
124 }
125
126 // Checks the validity of a chunk by verifying its checksum. It doesn't
127 // incur termination in the event of an invalid chunk.
128 static INLINEinline bool isValid(const void *Ptr) {
129 PackedHeader NewPackedHeader =
130 atomic_load_relaxed(getConstAtomicHeader(Ptr));
131 UnpackedHeader NewUnpackedHeader =
132 bit_cast<UnpackedHeader>(NewPackedHeader);
133 return (NewUnpackedHeader.Checksum ==
134 computeChecksum(Ptr, &NewUnpackedHeader));
135 }
136
137 // Ensure that ChunkAvailable is 0, so that if a 0 checksum is ever valid
138 // for a fully nulled out header, its state will be available anyway.
139 COMPILER_CHECK(ChunkAvailable == 0)typedef char assertion_failed__139[2*(int)(ChunkAvailable == 0
)-1]
;
140
141 // Loads and unpacks the header, verifying the checksum in the process.
142 static INLINEinline
143 void loadHeader(const void *Ptr, UnpackedHeader *NewUnpackedHeader) {
144 PackedHeader NewPackedHeader =
145 atomic_load_relaxed(getConstAtomicHeader(Ptr));
146 *NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
147 if (UNLIKELY(NewUnpackedHeader->Checksum !=__builtin_expect(!!(NewUnpackedHeader->Checksum != computeChecksum
(Ptr, NewUnpackedHeader)), 0)
148 computeChecksum(Ptr, NewUnpackedHeader))__builtin_expect(!!(NewUnpackedHeader->Checksum != computeChecksum
(Ptr, NewUnpackedHeader)), 0)
)
149 dieWithMessage("corrupted chunk header at address %p\n", Ptr);
150 }
151
152 // Packs and stores the header, computing the checksum in the process.
153 static INLINEinline void storeHeader(void *Ptr, UnpackedHeader *NewUnpackedHeader) {
154 NewUnpackedHeader->Checksum = computeChecksum(Ptr, NewUnpackedHeader);
155 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
156 atomic_store_relaxed(getAtomicHeader(Ptr), NewPackedHeader);
157 }
158
159 // Packs and stores the header, computing the checksum in the process. We
160 // compare the current header with the expected provided one to ensure that
161 // we are not being raced by a corruption occurring in another thread.
162 static INLINEinline void compareExchangeHeader(void *Ptr,
163 UnpackedHeader *NewUnpackedHeader,
164 UnpackedHeader *OldUnpackedHeader) {
165 NewUnpackedHeader->Checksum = computeChecksum(Ptr, NewUnpackedHeader);
166 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
167 PackedHeader OldPackedHeader = bit_cast<PackedHeader>(*OldUnpackedHeader);
168 if (UNLIKELY(!atomic_compare_exchange_strong(__builtin_expect(!!(!atomic_compare_exchange_strong( getAtomicHeader
(Ptr), &OldPackedHeader, NewPackedHeader, memory_order_relaxed
)), 0)
169 getAtomicHeader(Ptr), &OldPackedHeader, NewPackedHeader,__builtin_expect(!!(!atomic_compare_exchange_strong( getAtomicHeader
(Ptr), &OldPackedHeader, NewPackedHeader, memory_order_relaxed
)), 0)
170 memory_order_relaxed))__builtin_expect(!!(!atomic_compare_exchange_strong( getAtomicHeader
(Ptr), &OldPackedHeader, NewPackedHeader, memory_order_relaxed
)), 0)
)
171 dieWithMessage("race on chunk header at address %p\n", Ptr);
172 }
173} // namespace Chunk
174
175struct QuarantineCallback {
176 explicit QuarantineCallback(AllocatorCacheT *Cache)
177 : Cache_(Cache) {}
178
179 // Chunk recycling function, returns a quarantined chunk to the backend,
180 // first making sure it hasn't been tampered with.
181 void Recycle(void *Ptr) {
182 UnpackedHeader Header;
183 Chunk::loadHeader(Ptr, &Header);
184 if (UNLIKELY(Header.State != ChunkQuarantine)__builtin_expect(!!(Header.State != ChunkQuarantine), 0))
185 dieWithMessage("invalid chunk state when recycling address %p\n", Ptr);
186 UnpackedHeader NewHeader = Header;
187 NewHeader.State = ChunkAvailable;
188 Chunk::compareExchangeHeader(Ptr, &NewHeader, &Header);
189 void *BackendPtr = Chunk::getBackendPtr(Ptr, &Header);
190 if (Header.ClassId)
191 getBackend().deallocatePrimary(Cache_, BackendPtr, Header.ClassId);
192 else
193 getBackend().deallocateSecondary(BackendPtr);
194 }
195
196 // Internal quarantine allocation and deallocation functions. We first check
197 // that the batches are indeed serviced by the Primary.
198 // TODO(kostyak): figure out the best way to protect the batches.
199 void *Allocate(uptr Size) {
200 const uptr BatchClassId = SizeClassMap::ClassID(sizeof(QuarantineBatch));
201 return getBackend().allocatePrimary(Cache_, BatchClassId);
202 }
203
204 void Deallocate(void *Ptr) {
205 const uptr BatchClassId = SizeClassMap::ClassID(sizeof(QuarantineBatch));
206 getBackend().deallocatePrimary(Cache_, Ptr, BatchClassId);
207 }
208
209 AllocatorCacheT *Cache_;
210 COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize)typedef char assertion_failed__210[2*(int)(sizeof(QuarantineBatch
) < SizeClassMap::kMaxSize)-1]
;
211};
212
213typedef Quarantine<QuarantineCallback, void> QuarantineT;
214typedef QuarantineT::Cache QuarantineCacheT;
215COMPILER_CHECK(sizeof(QuarantineCacheT) <=typedef char assertion_failed__216[2*(int)(sizeof(QuarantineCacheT
) <= sizeof(ScudoTSD::QuarantineCachePlaceHolder))-1]
216 sizeof(ScudoTSD::QuarantineCachePlaceHolder))typedef char assertion_failed__216[2*(int)(sizeof(QuarantineCacheT
) <= sizeof(ScudoTSD::QuarantineCachePlaceHolder))-1]
;
217
218QuarantineCacheT *getQuarantineCache(ScudoTSD *TSD) {
219 return reinterpret_cast<QuarantineCacheT *>(TSD->QuarantineCachePlaceHolder);
220}
221
222#ifdef GWP_ASAN_HOOKS1
223static gwp_asan::GuardedPoolAllocator GuardedAlloc;
224#endif // GWP_ASAN_HOOKS
225
226struct Allocator {
227 static const uptr MaxAllowedMallocSize =
228 FIRST_32_SECOND_64(2UL << 30, 1ULL << 40)(1ULL << 40);
229
230 BackendT Backend;
231 QuarantineT Quarantine;
232
233 u32 QuarantineChunksUpToSize;
234
235 bool DeallocationTypeMismatch;
236 bool ZeroContents;
237 bool DeleteSizeMismatch;
238
239 bool CheckRssLimit;
240 uptr HardRssLimitMb;
241 uptr SoftRssLimitMb;
242 atomic_uint8_t RssLimitExceeded;
243 atomic_uint64_t RssLastCheckedAtNS;
244
245 explicit Allocator(LinkerInitialized)
246 : Quarantine(LINKER_INITIALIZED) {}
247
248 NOINLINE__attribute__((noinline)) void performSanityChecks();
249
250 void init() {
251 SanitizerToolName = "Scudo";
252 PrimaryAllocatorName = "ScudoPrimary";
253 SecondaryAllocatorName = "ScudoSecondary";
254
255 initFlags();
256
257 performSanityChecks();
258
259 // Check if hardware CRC32 is supported in the binary and by the platform,
260 // if so, opt for the CRC32 hardware version of the checksum.
261 if (&computeHardwareCRC32 && hasHardwareCRC32())
262 atomic_store_relaxed(&HashAlgorithm, CRC32Hardware);
263
264 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
265 Backend.init(common_flags()->allocator_release_to_os_interval_ms);
266 HardRssLimitMb = common_flags()->hard_rss_limit_mb;
267 SoftRssLimitMb = common_flags()->soft_rss_limit_mb;
268 Quarantine.Init(
269 static_cast<uptr>(getFlags()->QuarantineSizeKb) << 10,
270 static_cast<uptr>(getFlags()->ThreadLocalQuarantineSizeKb) << 10);
271 QuarantineChunksUpToSize = (Quarantine.GetCacheSize() == 0) ? 0 :
272 getFlags()->QuarantineChunksUpToSize;
273 DeallocationTypeMismatch = getFlags()->DeallocationTypeMismatch;
274 DeleteSizeMismatch = getFlags()->DeleteSizeMismatch;
275 ZeroContents = getFlags()->ZeroContents;
276
277 if (UNLIKELY(!GetRandom(reinterpret_cast<void *>(&Cookie), sizeof(Cookie),__builtin_expect(!!(!GetRandom(reinterpret_cast<void *>
(&Cookie), sizeof(Cookie), false)), 0)
278 /*blocking=*/false))__builtin_expect(!!(!GetRandom(reinterpret_cast<void *>
(&Cookie), sizeof(Cookie), false)), 0)
) {
279 Cookie = static_cast<u32>((NanoTime() >> 12) ^
280 (reinterpret_cast<uptr>(this) >> 4));
281 }
282
283 CheckRssLimit = HardRssLimitMb || SoftRssLimitMb;
284 if (CheckRssLimit)
285 atomic_store_relaxed(&RssLastCheckedAtNS, MonotonicNanoTime());
286 }
287
288 // Helper function that checks for a valid Scudo chunk. nullptr isn't.
289 bool isValidPointer(const void *Ptr) {
290 initThreadMaybe();
291 if (UNLIKELY(!Ptr)__builtin_expect(!!(!Ptr), 0))
292 return false;
293 if (!Chunk::isAligned(Ptr))
294 return false;
295 return Chunk::isValid(Ptr);
296 }
297
298 NOINLINE__attribute__((noinline)) bool isRssLimitExceeded();
299
300 // Allocates a chunk.
301 void *allocate(uptr Size, uptr Alignment, AllocType Type,
302 bool ForceZeroContents = false) {
303 initThreadMaybe();
304
305#ifdef GWP_ASAN_HOOKS1
306 if (UNLIKELY(GuardedAlloc.shouldSample())__builtin_expect(!!(GuardedAlloc.shouldSample()), 0)) {
6
Taking false branch
307 if (void *Ptr = GuardedAlloc.allocate(Size))
308 return Ptr;
309 }
310#endif // GWP_ASAN_HOOKS
311
312 if (UNLIKELY(Alignment > MaxAlignment)__builtin_expect(!!(Alignment > MaxAlignment), 0)) {
7
Assuming 'Alignment' is <= 'MaxAlignment'
8
Taking false branch
313 if (AllocatorMayReturnNull())
314 return nullptr;
315 reportAllocationAlignmentTooBig(Alignment, MaxAlignment);
316 }
317 if (UNLIKELY(Alignment < MinAlignment)__builtin_expect(!!(Alignment < MinAlignment), 0))
9
Assuming 'Alignment' is >= 'MinAlignment'
10
Taking false branch
318 Alignment = MinAlignment;
319
320 const uptr NeededSize = RoundUpTo(Size
10.1
'Size' is not equal to 0
10.1
'Size' is not equal to 0
10.1
'Size' is not equal to 0
? Size : 1, MinAlignment) +
11
'?' condition is true
321 Chunk::getHeaderSize();
322 const uptr AlignedSize = (Alignment > MinAlignment) ?
12
Assuming 'Alignment' is <= 'MinAlignment'
13
'?' condition is false
323 NeededSize + (Alignment - Chunk::getHeaderSize()) : NeededSize;
324 if (UNLIKELY(Size >= MaxAllowedMallocSize)__builtin_expect(!!(Size >= MaxAllowedMallocSize), 0) ||
15
Taking false branch
325 UNLIKELY(AlignedSize >= MaxAllowedMallocSize)__builtin_expect(!!(AlignedSize >= MaxAllowedMallocSize), 0
)
) {
14
Assuming 'AlignedSize' is < 'MaxAllowedMallocSize'
326 if (AllocatorMayReturnNull())
327 return nullptr;
328 reportAllocationSizeTooBig(Size, AlignedSize, MaxAllowedMallocSize);
329 }
330
331 if (CheckRssLimit && UNLIKELY(isRssLimitExceeded())__builtin_expect(!!(isRssLimitExceeded()), 0)) {
16
Assuming field 'CheckRssLimit' is false
332 if (AllocatorMayReturnNull())
333 return nullptr;
334 reportRssLimitExceeded();
335 }
336
337 // Primary and Secondary backed allocations have a different treatment. We
338 // deal with alignment requirements of Primary serviced allocations here,
339 // but the Secondary will take care of its own alignment needs.
340 void *BackendPtr;
341 uptr BackendSize;
342 u8 ClassId;
343 if (PrimaryT::CanAllocate(AlignedSize, MinAlignment)) {
17
Taking true branch
344 BackendSize = AlignedSize;
345 ClassId = SizeClassMap::ClassID(BackendSize);
346 bool UnlockRequired;
347 ScudoTSD *TSD = getTSDAndLock(&UnlockRequired);
348 BackendPtr = Backend.allocatePrimary(&TSD->Cache, ClassId);
349 if (UnlockRequired
17.1
'UnlockRequired' is false
17.1
'UnlockRequired' is false
17.1
'UnlockRequired' is false
)
18
Taking false branch
350 TSD->unlock();
351 } else {
352 BackendSize = NeededSize;
353 ClassId = 0;
354 BackendPtr = Backend.allocateSecondary(BackendSize, Alignment);
355 }
356 if (UNLIKELY(!BackendPtr)__builtin_expect(!!(!BackendPtr), 0)) {
19
Assuming 'BackendPtr' is non-null
20
Taking false branch
357 SetAllocatorOutOfMemory();
358 if (AllocatorMayReturnNull())
359 return nullptr;
360 reportOutOfMemory(Size);
361 }
362
363 // If requested, we will zero out the entire contents of the returned chunk.
364 if ((ForceZeroContents
20.1
'ForceZeroContents' is false
20.1
'ForceZeroContents' is false
20.1
'ForceZeroContents' is false
|| ZeroContents) && ClassId)
21
Assuming field 'ZeroContents' is true
22
Assuming 'ClassId' is not equal to 0
23
Taking true branch
365 memset(BackendPtr, 0, PrimaryT::ClassIdToSize(ClassId));
24
Calling 'SizeClassAllocator64::ClassIdToSize'
366
367 UnpackedHeader Header = {};
368 uptr UserPtr = reinterpret_cast<uptr>(BackendPtr) + Chunk::getHeaderSize();
369 if (UNLIKELY(!IsAligned(UserPtr, Alignment))__builtin_expect(!!(!IsAligned(UserPtr, Alignment)), 0)) {
370 // Since the Secondary takes care of alignment, a non-aligned pointer
371 // means it is from the Primary. It is also the only case where the offset
372 // field of the header would be non-zero.
373 DCHECK(ClassId);
374 const uptr AlignedUserPtr = RoundUpTo(UserPtr, Alignment);
375 Header.Offset = (AlignedUserPtr - UserPtr) >> MinAlignmentLog;
376 UserPtr = AlignedUserPtr;
377 }
378 DCHECK_LE(UserPtr + Size, reinterpret_cast<uptr>(BackendPtr) + BackendSize);
379 Header.State = ChunkAllocated;
380 Header.AllocType = Type;
381 if (ClassId) {
382 Header.ClassId = ClassId;
383 Header.SizeOrUnusedBytes = Size;
384 } else {
385 // The secondary fits the allocations to a page, so the amount of unused
386 // bytes is the difference between the end of the user allocation and the
387 // next page boundary.
388 const uptr PageSize = GetPageSizeCached();
389 const uptr TrailingBytes = (UserPtr + Size) & (PageSize - 1);
390 if (TrailingBytes)
391 Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
392 }
393 void *Ptr = reinterpret_cast<void *>(UserPtr);
394 Chunk::storeHeader(Ptr, &Header);
395 if (SCUDO_CAN_USE_HOOKS0 && &__sanitizer_malloc_hook)
396 __sanitizer_malloc_hook(Ptr, Size);
397 return Ptr;
398 }
399
400 // Place a chunk in the quarantine or directly deallocate it in the event of
401 // a zero-sized quarantine, or if the size of the chunk is greater than the
402 // quarantine chunk size threshold.
403 void quarantineOrDeallocateChunk(void *Ptr, UnpackedHeader *Header,
404 uptr Size) {
405 const bool BypassQuarantine = !Size || (Size > QuarantineChunksUpToSize);
406 if (BypassQuarantine) {
407 UnpackedHeader NewHeader = *Header;
408 NewHeader.State = ChunkAvailable;
409 Chunk::compareExchangeHeader(Ptr, &NewHeader, Header);
410 void *BackendPtr = Chunk::getBackendPtr(Ptr, Header);
411 if (Header->ClassId) {
412 bool UnlockRequired;
413 ScudoTSD *TSD = getTSDAndLock(&UnlockRequired);
414 getBackend().deallocatePrimary(&TSD->Cache, BackendPtr,
415 Header->ClassId);
416 if (UnlockRequired)
417 TSD->unlock();
418 } else {
419 getBackend().deallocateSecondary(BackendPtr);
420 }
421 } else {
422 // If a small memory amount was allocated with a larger alignment, we want
423 // to take that into account. Otherwise the Quarantine would be filled
424 // with tiny chunks, taking a lot of VA memory. This is an approximation
425 // of the usable size, that allows us to not call
426 // GetActuallyAllocatedSize.
427 const uptr EstimatedSize = Size + (Header->Offset << MinAlignmentLog);
428 UnpackedHeader NewHeader = *Header;
429 NewHeader.State = ChunkQuarantine;
430 Chunk::compareExchangeHeader(Ptr, &NewHeader, Header);
431 bool UnlockRequired;
432 ScudoTSD *TSD = getTSDAndLock(&UnlockRequired);
433 Quarantine.Put(getQuarantineCache(TSD), QuarantineCallback(&TSD->Cache),
434 Ptr, EstimatedSize);
435 if (UnlockRequired)
436 TSD->unlock();
437 }
438 }
439
440 // Deallocates a Chunk, which means either adding it to the quarantine or
441 // directly returning it to the backend if criteria are met.
442 void deallocate(void *Ptr, uptr DeleteSize, uptr DeleteAlignment,
443 AllocType Type) {
444 // For a deallocation, we only ensure minimal initialization, meaning thread
445 // local data will be left uninitialized for now (when using ELF TLS). The
446 // fallback cache will be used instead. This is a workaround for a situation
447 // where the only heap operation performed in a thread would be a free past
448 // the TLS destructors, ending up in initialized thread specific data never
449 // being destroyed properly. Any other heap operation will do a full init.
450 initThreadMaybe(/*MinimalInit=*/true);
451 if (SCUDO_CAN_USE_HOOKS0 && &__sanitizer_free_hook)
452 __sanitizer_free_hook(Ptr);
453 if (UNLIKELY(!Ptr)__builtin_expect(!!(!Ptr), 0))
454 return;
455
456#ifdef GWP_ASAN_HOOKS1
457 if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))__builtin_expect(!!(GuardedAlloc.pointerIsMine(Ptr)), 0)) {
458 GuardedAlloc.deallocate(Ptr);
459 return;
460 }
461#endif // GWP_ASAN_HOOKS
462
463 if (UNLIKELY(!Chunk::isAligned(Ptr))__builtin_expect(!!(!Chunk::isAligned(Ptr)), 0))
464 dieWithMessage("misaligned pointer when deallocating address %p\n", Ptr);
465 UnpackedHeader Header;
466 Chunk::loadHeader(Ptr, &Header);
467 if (UNLIKELY(Header.State != ChunkAllocated)__builtin_expect(!!(Header.State != ChunkAllocated), 0))
468 dieWithMessage("invalid chunk state when deallocating address %p\n", Ptr);
469 if (DeallocationTypeMismatch) {
470 // The deallocation type has to match the allocation one.
471 if (Header.AllocType != Type) {
472 // With the exception of memalign'd Chunks, that can be still be free'd.
473 if (Header.AllocType != FromMemalign || Type != FromMalloc)
474 dieWithMessage("allocation type mismatch when deallocating address "
475 "%p\n", Ptr);
476 }
477 }
478 const uptr Size = Chunk::getSize(Ptr, &Header);
479 if (DeleteSizeMismatch) {
480 if (DeleteSize && DeleteSize != Size)
481 dieWithMessage("invalid sized delete when deallocating address %p\n",
482 Ptr);
483 }
484 (void)DeleteAlignment; // TODO(kostyak): verify that the alignment matches.
485 quarantineOrDeallocateChunk(Ptr, &Header, Size);
486 }
487
488 // Reallocates a chunk. We can save on a new allocation if the new requested
489 // size still fits in the chunk.
490 void *reallocate(void *OldPtr, uptr NewSize) {
491 initThreadMaybe();
492
493#ifdef GWP_ASAN_HOOKS1
494 if (UNLIKELY(GuardedAlloc.pointerIsMine(OldPtr))__builtin_expect(!!(GuardedAlloc.pointerIsMine(OldPtr)), 0)) {
495 size_t OldSize = GuardedAlloc.getSize(OldPtr);
496 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
497 if (NewPtr)
498 memcpy(NewPtr, OldPtr, (NewSize < OldSize) ? NewSize : OldSize);
499 GuardedAlloc.deallocate(OldPtr);
500 return NewPtr;
501 }
502#endif // GWP_ASAN_HOOKS
503
504 if (UNLIKELY(!Chunk::isAligned(OldPtr))__builtin_expect(!!(!Chunk::isAligned(OldPtr)), 0))
505 dieWithMessage("misaligned address when reallocating address %p\n",
506 OldPtr);
507 UnpackedHeader OldHeader;
508 Chunk::loadHeader(OldPtr, &OldHeader);
509 if (UNLIKELY(OldHeader.State != ChunkAllocated)__builtin_expect(!!(OldHeader.State != ChunkAllocated), 0))
510 dieWithMessage("invalid chunk state when reallocating address %p\n",
511 OldPtr);
512 if (DeallocationTypeMismatch) {
513 if (UNLIKELY(OldHeader.AllocType != FromMalloc)__builtin_expect(!!(OldHeader.AllocType != FromMalloc), 0))
514 dieWithMessage("allocation type mismatch when reallocating address "
515 "%p\n", OldPtr);
516 }
517 const uptr UsableSize = Chunk::getUsableSize(OldPtr, &OldHeader);
518 // The new size still fits in the current chunk, and the size difference
519 // is reasonable.
520 if (NewSize <= UsableSize &&
521 (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
522 UnpackedHeader NewHeader = OldHeader;
523 NewHeader.SizeOrUnusedBytes =
524 OldHeader.ClassId ? NewSize : UsableSize - NewSize;
525 Chunk::compareExchangeHeader(OldPtr, &NewHeader, &OldHeader);
526 return OldPtr;
527 }
528 // Otherwise, we have to allocate a new chunk and copy the contents of the
529 // old one.
530 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
531 if (NewPtr) {
532 const uptr OldSize = OldHeader.ClassId ? OldHeader.SizeOrUnusedBytes :
533 UsableSize - OldHeader.SizeOrUnusedBytes;
534 memcpy(NewPtr, OldPtr, Min(NewSize, UsableSize));
535 quarantineOrDeallocateChunk(OldPtr, &OldHeader, OldSize);
536 }
537 return NewPtr;
538 }
539
540 // Helper function that returns the actual usable size of a chunk.
541 uptr getUsableSize(const void *Ptr) {
542 initThreadMaybe();
543 if (UNLIKELY(!Ptr)__builtin_expect(!!(!Ptr), 0))
544 return 0;
545
546#ifdef GWP_ASAN_HOOKS1
547 if (UNLIKELY(GuardedAlloc.pointerIsMine(Ptr))__builtin_expect(!!(GuardedAlloc.pointerIsMine(Ptr)), 0))
548 return GuardedAlloc.getSize(Ptr);
549#endif // GWP_ASAN_HOOKS
550
551 UnpackedHeader Header;
552 Chunk::loadHeader(Ptr, &Header);
553 // Getting the usable size of a chunk only makes sense if it's allocated.
554 if (UNLIKELY(Header.State != ChunkAllocated)__builtin_expect(!!(Header.State != ChunkAllocated), 0))
555 dieWithMessage("invalid chunk state when sizing address %p\n", Ptr);
556 return Chunk::getUsableSize(Ptr, &Header);
557 }
558
559 void *calloc(uptr NMemB, uptr Size) {
560 initThreadMaybe();
561 if (UNLIKELY(CheckForCallocOverflow(NMemB, Size))__builtin_expect(!!(CheckForCallocOverflow(NMemB, Size)), 0)) {
562 if (AllocatorMayReturnNull())
563 return nullptr;
564 reportCallocOverflow(NMemB, Size);
565 }
566 return allocate(NMemB * Size, MinAlignment, FromMalloc, true);
567 }
568
569 void commitBack(ScudoTSD *TSD) {
570 Quarantine.Drain(getQuarantineCache(TSD), QuarantineCallback(&TSD->Cache));
571 Backend.destroyCache(&TSD->Cache);
572 }
573
574 uptr getStats(AllocatorStat StatType) {
575 initThreadMaybe();
576 uptr stats[AllocatorStatCount];
577 Backend.getStats(stats);
578 return stats[StatType];
579 }
580
581 bool canReturnNull() {
582 initThreadMaybe();
583 return AllocatorMayReturnNull();
584 }
585
586 void setRssLimit(uptr LimitMb, bool HardLimit) {
587 if (HardLimit)
588 HardRssLimitMb = LimitMb;
589 else
590 SoftRssLimitMb = LimitMb;
591 CheckRssLimit = HardRssLimitMb || SoftRssLimitMb;
592 }
593
594 void printStats() {
595 initThreadMaybe();
596 Backend.printStats();
597 }
598};
599
600NOINLINE__attribute__((noinline)) void Allocator::performSanityChecks() {
601 // Verify that the header offset field can hold the maximum offset. In the
602 // case of the Secondary allocator, it takes care of alignment and the
603 // offset will always be 0. In the case of the Primary, the worst case
604 // scenario happens in the last size class, when the backend allocation
605 // would already be aligned on the requested alignment, which would happen
606 // to be the maximum alignment that would fit in that size class. As a
607 // result, the maximum offset will be at most the maximum alignment for the
608 // last size class minus the header size, in multiples of MinAlignment.
609 UnpackedHeader Header = {};
610 const uptr MaxPrimaryAlignment =
611 1 << MostSignificantSetBitIndex(SizeClassMap::kMaxSize - MinAlignment);
612 const uptr MaxOffset =
613 (MaxPrimaryAlignment - Chunk::getHeaderSize()) >> MinAlignmentLog;
614 Header.Offset = MaxOffset;
615 if (Header.Offset != MaxOffset)
616 dieWithMessage("maximum possible offset doesn't fit in header\n");
617 // Verify that we can fit the maximum size or amount of unused bytes in the
618 // header. Given that the Secondary fits the allocation to a page, the worst
619 // case scenario happens in the Primary. It will depend on the second to
620 // last and last class sizes, as well as the dynamic base for the Primary.
621 // The following is an over-approximation that works for our needs.
622 const uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
623 Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
624 if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes)
625 dieWithMessage("maximum possible unused bytes doesn't fit in header\n");
626
627 const uptr LargestClassId = SizeClassMap::kLargestClassID;
628 Header.ClassId = LargestClassId;
629 if (Header.ClassId != LargestClassId)
630 dieWithMessage("largest class ID doesn't fit in header\n");
631}
632
633// Opportunistic RSS limit check. This will update the RSS limit status, if
634// it can, every 250ms, otherwise it will just return the current one.
635NOINLINE__attribute__((noinline)) bool Allocator::isRssLimitExceeded() {
636 u64 LastCheck = atomic_load_relaxed(&RssLastCheckedAtNS);
637 const u64 CurrentCheck = MonotonicNanoTime();
638 if (LIKELY(CurrentCheck < LastCheck + (250ULL * 1000000ULL))__builtin_expect(!!(CurrentCheck < LastCheck + (250ULL * 1000000ULL
)), 1)
)
639 return atomic_load_relaxed(&RssLimitExceeded);
640 if (!atomic_compare_exchange_weak(&RssLastCheckedAtNS, &LastCheck,
641 CurrentCheck, memory_order_relaxed))
642 return atomic_load_relaxed(&RssLimitExceeded);
643 // TODO(kostyak): We currently use sanitizer_common's GetRSS which reads the
644 // RSS from /proc/self/statm by default. We might want to
645 // call getrusage directly, even if it's less accurate.
646 const uptr CurrentRssMb = GetRSS() >> 20;
647 if (HardRssLimitMb && UNLIKELY(HardRssLimitMb < CurrentRssMb)__builtin_expect(!!(HardRssLimitMb < CurrentRssMb), 0))
648 dieWithMessage("hard RSS limit exhausted (%zdMb vs %zdMb)\n",
649 HardRssLimitMb, CurrentRssMb);
650 if (SoftRssLimitMb) {
651 if (atomic_load_relaxed(&RssLimitExceeded)) {
652 if (CurrentRssMb <= SoftRssLimitMb)
653 atomic_store_relaxed(&RssLimitExceeded, false);
654 } else {
655 if (CurrentRssMb > SoftRssLimitMb) {
656 atomic_store_relaxed(&RssLimitExceeded, true);
657 Printf("Scudo INFO: soft RSS limit exhausted (%zdMb vs %zdMb)\n",
658 SoftRssLimitMb, CurrentRssMb);
659 }
660 }
661 }
662 return atomic_load_relaxed(&RssLimitExceeded);
663}
664
665static Allocator Instance(LINKER_INITIALIZED);
666
667static BackendT &getBackend() {
668 return Instance.Backend;
669}
670
671void initScudo() {
672 Instance.init();
673#ifdef GWP_ASAN_HOOKS1
674 gwp_asan::options::initOptions();
675 gwp_asan::options::Options &Opts = gwp_asan::options::getOptions();
676 Opts.Backtrace = gwp_asan::options::getBacktraceFunction();
677 Opts.PrintBacktrace = gwp_asan::options::getPrintBacktraceFunction();
678 GuardedAlloc.init(Opts);
679#endif // GWP_ASAN_HOOKS
680}
681
682void ScudoTSD::init() {
683 getBackend().initCache(&Cache);
684 memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
685}
686
687void ScudoTSD::commitBack() {
688 Instance.commitBack(this);
689}
690
691void *scudoAllocate(uptr Size, uptr Alignment, AllocType Type) {
692 if (Alignment && UNLIKELY(!IsPowerOfTwo(Alignment))__builtin_expect(!!(!IsPowerOfTwo(Alignment)), 0)) {
693 errno(*__errno_location ()) = EINVAL22;
694 if (Instance.canReturnNull())
695 return nullptr;
696 reportAllocationAlignmentNotPowerOfTwo(Alignment);
697 }
698 return SetErrnoOnNull(Instance.allocate(Size, Alignment, Type));
699}
700
701void scudoDeallocate(void *Ptr, uptr Size, uptr Alignment, AllocType Type) {
702 Instance.deallocate(Ptr, Size, Alignment, Type);
703}
704
705void *scudoRealloc(void *Ptr, uptr Size) {
706 if (!Ptr)
707 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, FromMalloc));
708 if (Size == 0) {
709 Instance.deallocate(Ptr, 0, 0, FromMalloc);
710 return nullptr;
711 }
712 return SetErrnoOnNull(Instance.reallocate(Ptr, Size));
713}
714
715void *scudoCalloc(uptr NMemB, uptr Size) {
716 return SetErrnoOnNull(Instance.calloc(NMemB, Size));
717}
718
719void *scudoValloc(uptr Size) {
720 return SetErrnoOnNull(
721 Instance.allocate(Size, GetPageSizeCached(), FromMemalign));
722}
723
724void *scudoPvalloc(uptr Size) {
725 const uptr PageSize = GetPageSizeCached();
726 if (UNLIKELY(CheckForPvallocOverflow(Size, PageSize))__builtin_expect(!!(CheckForPvallocOverflow(Size, PageSize)),
0)
) {
1
Assuming the condition is false
2
Taking false branch
727 errno(*__errno_location ()) = ENOMEM12;
728 if (Instance.canReturnNull())
729 return nullptr;
730 reportPvallocOverflow(Size);
731 }
732 // pvalloc(0) should allocate one page.
733 Size = Size ? RoundUpTo(Size, PageSize) : PageSize;
3
Assuming 'Size' is 0
4
'?' condition is false
734 return SetErrnoOnNull(Instance.allocate(Size, PageSize, FromMemalign));
5
Calling 'Allocator::allocate'
735}
736
737int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
738 if (UNLIKELY(!CheckPosixMemalignAlignment(Alignment))__builtin_expect(!!(!CheckPosixMemalignAlignment(Alignment)),
0)
) {
739 if (!Instance.canReturnNull())
740 reportInvalidPosixMemalignAlignment(Alignment);
741 return EINVAL22;
742 }
743 void *Ptr = Instance.allocate(Size, Alignment, FromMemalign);
744 if (UNLIKELY(!Ptr)__builtin_expect(!!(!Ptr), 0))
745 return ENOMEM12;
746 *MemPtr = Ptr;
747 return 0;
748}
749
750void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
751 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(Alignment, Size))__builtin_expect(!!(!CheckAlignedAllocAlignmentAndSize(Alignment
, Size)), 0)
) {
752 errno(*__errno_location ()) = EINVAL22;
753 if (Instance.canReturnNull())
754 return nullptr;
755 reportInvalidAlignedAllocAlignment(Size, Alignment);
756 }
757 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMalloc));
758}
759
760uptr scudoMallocUsableSize(void *Ptr) {
761 return Instance.getUsableSize(Ptr);
762}
763
764} // namespace __scudo
765
766using namespace __scudo;
767
768// MallocExtension helper functions
769
770uptr __sanitizer_get_current_allocated_bytes() {
771 return Instance.getStats(AllocatorStatAllocated);
772}
773
774uptr __sanitizer_get_heap_size() {
775 return Instance.getStats(AllocatorStatMapped);
776}
777
778uptr __sanitizer_get_free_bytes() {
779 return 1;
780}
781
782uptr __sanitizer_get_unmapped_bytes() {
783 return 1;
784}
785
786uptr __sanitizer_get_estimated_allocated_size(uptr Size) {
787 return Size;
788}
789
790int __sanitizer_get_ownership(const void *Ptr) {
791 return Instance.isValidPointer(Ptr);
792}
793
794uptr __sanitizer_get_allocated_size(const void *Ptr) {
795 return Instance.getUsableSize(Ptr);
796}
797
798#if !SANITIZER_SUPPORTS_WEAK_HOOKS1
799SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook,extern "C" __attribute__((visibility("default"))) __attribute__
((weak)) void __sanitizer_malloc_hook(void *Ptr, uptr Size)
800 void *Ptr, uptr Size)extern "C" __attribute__((visibility("default"))) __attribute__
((weak)) void __sanitizer_malloc_hook(void *Ptr, uptr Size)
{
801 (void)Ptr;
802 (void)Size;
803}
804
805SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *Ptr)extern "C" __attribute__((visibility("default"))) __attribute__
((weak)) void __sanitizer_free_hook(void *Ptr)
{
806 (void)Ptr;
807}
808#endif
809
810// Interface functions
811
812void __scudo_set_rss_limit(uptr LimitMb, s32 HardLimit) {
813 if (!SCUDO_CAN_USE_PUBLIC_INTERFACE1)
814 return;
815 Instance.setRssLimit(LimitMb, !!HardLimit);
816}
817
818void __scudo_print_stats() {
819 Instance.printStats();
820}

/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h

1//===-- sanitizer_allocator_primary64.h -------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Part of the Sanitizer Allocator.
10//
11//===----------------------------------------------------------------------===//
12#ifndef SANITIZER_ALLOCATOR_H
13#error This file must be included inside sanitizer_allocator.h
14#endif
15
16template<class SizeClassAllocator> struct SizeClassAllocator64LocalCache;
17
18// SizeClassAllocator64 -- allocator for 64-bit address space.
19// The template parameter Params is a class containing the actual parameters.
20//
21// Space: a portion of address space of kSpaceSize bytes starting at SpaceBeg.
22// If kSpaceBeg is ~0 then SpaceBeg is chosen dynamically my mmap.
23// Otherwise SpaceBeg=kSpaceBeg (fixed address).
24// kSpaceSize is a power of two.
25// At the beginning the entire space is mprotect-ed, then small parts of it
26// are mapped on demand.
27//
28// Region: a part of Space dedicated to a single size class.
29// There are kNumClasses Regions of equal size.
30//
31// UserChunk: a piece of memory returned to user.
32// MetaChunk: kMetadataSize bytes of metadata associated with a UserChunk.
33
34// FreeArray is an array free-d chunks (stored as 4-byte offsets)
35//
36// A Region looks like this:
37// UserChunk1 ... UserChunkN <gap> MetaChunkN ... MetaChunk1 FreeArray
38
39struct SizeClassAllocator64FlagMasks { // Bit masks.
40 enum {
41 kRandomShuffleChunks = 1,
42 };
43};
44
45template <class Params>
46class SizeClassAllocator64 {
47 public:
48 using AddressSpaceView = typename Params::AddressSpaceView;
49 static const uptr kSpaceBeg = Params::kSpaceBeg;
50 static const uptr kSpaceSize = Params::kSpaceSize;
51 static const uptr kMetadataSize = Params::kMetadataSize;
52 typedef typename Params::SizeClassMap SizeClassMap;
53 typedef typename Params::MapUnmapCallback MapUnmapCallback;
54
55 static const bool kRandomShuffleChunks =
56 Params::kFlags & SizeClassAllocator64FlagMasks::kRandomShuffleChunks;
57
58 typedef SizeClassAllocator64<Params> ThisT;
59 typedef SizeClassAllocator64LocalCache<ThisT> AllocatorCache;
60
61 // When we know the size class (the region base) we can represent a pointer
62 // as a 4-byte integer (offset from the region start shifted right by 4).
63 typedef u32 CompactPtrT;
64 static const uptr kCompactPtrScale = 4;
65 CompactPtrT PointerToCompactPtr(uptr base, uptr ptr) const {
66 return static_cast<CompactPtrT>((ptr - base) >> kCompactPtrScale);
67 }
68 uptr CompactPtrToPointer(uptr base, CompactPtrT ptr32) const {
69 return base + (static_cast<uptr>(ptr32) << kCompactPtrScale);
70 }
71
72 void Init(s32 release_to_os_interval_ms) {
73 uptr TotalSpaceSize = kSpaceSize + AdditionalSize();
74 if (kUsingConstantSpaceBeg) {
75 CHECK_EQ(kSpaceBeg, address_range.Init(TotalSpaceSize,do { __sanitizer::u64 v1 = (__sanitizer::u64)((kSpaceBeg)); __sanitizer
::u64 v2 = (__sanitizer::u64)((address_range.Init(TotalSpaceSize
, PrimaryAllocatorName, kSpaceBeg))); if (__builtin_expect(!!
(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 76, "(" "(kSpaceBeg)" ") " "==" " (" "(address_range.Init(TotalSpaceSize, PrimaryAllocatorName, kSpaceBeg))"
")", v1, v2); } while (false)
76 PrimaryAllocatorName, kSpaceBeg))do { __sanitizer::u64 v1 = (__sanitizer::u64)((kSpaceBeg)); __sanitizer
::u64 v2 = (__sanitizer::u64)((address_range.Init(TotalSpaceSize
, PrimaryAllocatorName, kSpaceBeg))); if (__builtin_expect(!!
(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 76, "(" "(kSpaceBeg)" ") " "==" " (" "(address_range.Init(TotalSpaceSize, PrimaryAllocatorName, kSpaceBeg))"
")", v1, v2); } while (false)
;
77 } else {
78 NonConstSpaceBeg = address_range.Init(TotalSpaceSize,
79 PrimaryAllocatorName);
80 CHECK_NE(NonConstSpaceBeg, ~(uptr)0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((NonConstSpaceBeg
)); __sanitizer::u64 v2 = (__sanitizer::u64)((~(uptr)0)); if (
__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 80, "(" "(NonConstSpaceBeg)" ") " "!=" " (" "(~(uptr)0)" ")"
, v1, v2); } while (false)
;
81 }
82 SetReleaseToOSIntervalMs(release_to_os_interval_ms);
83 MapWithCallbackOrDie(SpaceEnd(), AdditionalSize(),
84 "SizeClassAllocator: region info");
85 // Check that the RegionInfo array is aligned on the CacheLine size.
86 DCHECK_EQ(SpaceEnd() % kCacheLineSize, 0);
87 }
88
89 s32 ReleaseToOSIntervalMs() const {
90 return atomic_load(&release_to_os_interval_ms_, memory_order_relaxed);
91 }
92
93 void SetReleaseToOSIntervalMs(s32 release_to_os_interval_ms) {
94 atomic_store(&release_to_os_interval_ms_, release_to_os_interval_ms,
95 memory_order_relaxed);
96 }
97
98 void ForceReleaseToOS() {
99 for (uptr class_id = 1; class_id < kNumClasses; class_id++) {
100 BlockingMutexLock l(&GetRegionInfo(class_id)->mutex);
101 MaybeReleaseToOS(class_id, true /*force*/);
102 }
103 }
104
105 static bool CanAllocate(uptr size, uptr alignment) {
106 return size <= SizeClassMap::kMaxSize &&
107 alignment <= SizeClassMap::kMaxSize;
108 }
109
110 NOINLINE__attribute__((noinline)) void ReturnToAllocator(AllocatorStats *stat, uptr class_id,
111 const CompactPtrT *chunks, uptr n_chunks) {
112 RegionInfo *region = GetRegionInfo(class_id);
113 uptr region_beg = GetRegionBeginBySizeClass(class_id);
114 CompactPtrT *free_array = GetFreeArray(region_beg);
115
116 BlockingMutexLock l(&region->mutex);
117 uptr old_num_chunks = region->num_freed_chunks;
118 uptr new_num_freed_chunks = old_num_chunks + n_chunks;
119 // Failure to allocate free array space while releasing memory is non
120 // recoverable.
121 if (UNLIKELY(!EnsureFreeArraySpace(region, region_beg,__builtin_expect(!!(!EnsureFreeArraySpace(region, region_beg,
new_num_freed_chunks)), 0)
122 new_num_freed_chunks))__builtin_expect(!!(!EnsureFreeArraySpace(region, region_beg,
new_num_freed_chunks)), 0)
) {
123 Report("FATAL: Internal error: %s's allocator exhausted the free list "
124 "space for size class %zd (%zd bytes).\n", SanitizerToolName,
125 class_id, ClassIdToSize(class_id));
126 Die();
127 }
128 for (uptr i = 0; i < n_chunks; i++)
129 free_array[old_num_chunks + i] = chunks[i];
130 region->num_freed_chunks = new_num_freed_chunks;
131 region->stats.n_freed += n_chunks;
132
133 MaybeReleaseToOS(class_id, false /*force*/);
134 }
135
136 NOINLINE__attribute__((noinline)) bool GetFromAllocator(AllocatorStats *stat, uptr class_id,
137 CompactPtrT *chunks, uptr n_chunks) {
138 RegionInfo *region = GetRegionInfo(class_id);
139 uptr region_beg = GetRegionBeginBySizeClass(class_id);
140 CompactPtrT *free_array = GetFreeArray(region_beg);
141
142 BlockingMutexLock l(&region->mutex);
143 if (UNLIKELY(region->num_freed_chunks < n_chunks)__builtin_expect(!!(region->num_freed_chunks < n_chunks
), 0)
) {
144 if (UNLIKELY(!PopulateFreeArray(stat, class_id, region,__builtin_expect(!!(!PopulateFreeArray(stat, class_id, region
, n_chunks - region->num_freed_chunks)), 0)
145 n_chunks - region->num_freed_chunks))__builtin_expect(!!(!PopulateFreeArray(stat, class_id, region
, n_chunks - region->num_freed_chunks)), 0)
)
146 return false;
147 CHECK_GE(region->num_freed_chunks, n_chunks)do { __sanitizer::u64 v1 = (__sanitizer::u64)((region->num_freed_chunks
)); __sanitizer::u64 v2 = (__sanitizer::u64)((n_chunks)); if (
__builtin_expect(!!(!(v1 >= v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 147, "(" "(region->num_freed_chunks)" ") " ">=" " (" "(n_chunks)"
")", v1, v2); } while (false)
;
148 }
149 region->num_freed_chunks -= n_chunks;
150 uptr base_idx = region->num_freed_chunks;
151 for (uptr i = 0; i < n_chunks; i++)
152 chunks[i] = free_array[base_idx + i];
153 region->stats.n_allocated += n_chunks;
154 return true;
155 }
156
157 bool PointerIsMine(const void *p) const {
158 uptr P = reinterpret_cast<uptr>(p);
159 if (kUsingConstantSpaceBeg && (kSpaceBeg % kSpaceSize) == 0)
160 return P / kSpaceSize == kSpaceBeg / kSpaceSize;
161 return P >= SpaceBeg() && P < SpaceEnd();
162 }
163
164 uptr GetRegionBegin(const void *p) {
165 if (kUsingConstantSpaceBeg)
166 return reinterpret_cast<uptr>(p) & ~(kRegionSize - 1);
167 uptr space_beg = SpaceBeg();
168 return ((reinterpret_cast<uptr>(p) - space_beg) & ~(kRegionSize - 1)) +
169 space_beg;
170 }
171
172 uptr GetRegionBeginBySizeClass(uptr class_id) const {
173 return SpaceBeg() + kRegionSize * class_id;
174 }
175
176 uptr GetSizeClass(const void *p) {
177 if (kUsingConstantSpaceBeg && (kSpaceBeg % kSpaceSize) == 0)
178 return ((reinterpret_cast<uptr>(p)) / kRegionSize) % kNumClassesRounded;
179 return ((reinterpret_cast<uptr>(p) - SpaceBeg()) / kRegionSize) %
180 kNumClassesRounded;
181 }
182
183 void *GetBlockBegin(const void *p) {
184 uptr class_id = GetSizeClass(p);
185 uptr size = ClassIdToSize(class_id);
186 if (!size) return nullptr;
187 uptr chunk_idx = GetChunkIdx((uptr)p, size);
188 uptr reg_beg = GetRegionBegin(p);
189 uptr beg = chunk_idx * size;
190 uptr next_beg = beg + size;
191 if (class_id >= kNumClasses) return nullptr;
192 const RegionInfo *region = AddressSpaceView::Load(GetRegionInfo(class_id));
193 if (region->mapped_user >= next_beg)
194 return reinterpret_cast<void*>(reg_beg + beg);
195 return nullptr;
196 }
197
198 uptr GetActuallyAllocatedSize(void *p) {
199 CHECK(PointerIsMine(p))do { __sanitizer::u64 v1 = (__sanitizer::u64)((PointerIsMine(
p))); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 199, "(" "(PointerIsMine(p))" ") " "!=" " (" "0" ")", v1, v2
); } while (false)
;
200 return ClassIdToSize(GetSizeClass(p));
201 }
202
203 static uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); }
204
205 void *GetMetaData(const void *p) {
206 uptr class_id = GetSizeClass(p);
207 uptr size = ClassIdToSize(class_id);
208 uptr chunk_idx = GetChunkIdx(reinterpret_cast<uptr>(p), size);
209 uptr region_beg = GetRegionBeginBySizeClass(class_id);
210 return reinterpret_cast<void *>(GetMetadataEnd(region_beg) -
211 (1 + chunk_idx) * kMetadataSize);
212 }
213
214 uptr TotalMemoryUsed() {
215 uptr res = 0;
216 for (uptr i = 0; i < kNumClasses; i++)
217 res += GetRegionInfo(i)->allocated_user;
218 return res;
219 }
220
221 // Test-only.
222 void TestOnlyUnmap() {
223 UnmapWithCallbackOrDie(SpaceBeg(), kSpaceSize + AdditionalSize());
224 }
225
226 static void FillMemoryProfile(uptr start, uptr rss, bool file, uptr *stats,
227 uptr stats_size) {
228 for (uptr class_id = 0; class_id < stats_size; class_id++)
229 if (stats[class_id] == start)
230 stats[class_id] = rss;
231 }
232
233 void PrintStats(uptr class_id, uptr rss) {
234 RegionInfo *region = GetRegionInfo(class_id);
235 if (region->mapped_user == 0) return;
236 uptr in_use = region->stats.n_allocated - region->stats.n_freed;
237 uptr avail_chunks = region->allocated_user / ClassIdToSize(class_id);
238 Printf(
239 "%s %02zd (%6zd): mapped: %6zdK allocs: %7zd frees: %7zd inuse: %6zd "
240 "num_freed_chunks %7zd avail: %6zd rss: %6zdK releases: %6zd "
241 "last released: %6zdK region: 0x%zx\n",
242 region->exhausted ? "F" : " ", class_id, ClassIdToSize(class_id),
243 region->mapped_user >> 10, region->stats.n_allocated,
244 region->stats.n_freed, in_use, region->num_freed_chunks, avail_chunks,
245 rss >> 10, region->rtoi.num_releases,
246 region->rtoi.last_released_bytes >> 10,
247 SpaceBeg() + kRegionSize * class_id);
248 }
249
250 void PrintStats() {
251 uptr rss_stats[kNumClasses];
252 for (uptr class_id = 0; class_id < kNumClasses; class_id++)
253 rss_stats[class_id] = SpaceBeg() + kRegionSize * class_id;
254 GetMemoryProfile(FillMemoryProfile, rss_stats, kNumClasses);
255
256 uptr total_mapped = 0;
257 uptr total_rss = 0;
258 uptr n_allocated = 0;
259 uptr n_freed = 0;
260 for (uptr class_id = 1; class_id < kNumClasses; class_id++) {
261 RegionInfo *region = GetRegionInfo(class_id);
262 if (region->mapped_user != 0) {
263 total_mapped += region->mapped_user;
264 total_rss += rss_stats[class_id];
265 }
266 n_allocated += region->stats.n_allocated;
267 n_freed += region->stats.n_freed;
268 }
269
270 Printf("Stats: SizeClassAllocator64: %zdM mapped (%zdM rss) in "
271 "%zd allocations; remains %zd\n", total_mapped >> 20,
272 total_rss >> 20, n_allocated, n_allocated - n_freed);
273 for (uptr class_id = 1; class_id < kNumClasses; class_id++)
274 PrintStats(class_id, rss_stats[class_id]);
275 }
276
277 // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
278 // introspection API.
279 void ForceLock() {
280 for (uptr i = 0; i < kNumClasses; i++) {
281 GetRegionInfo(i)->mutex.Lock();
282 }
283 }
284
285 void ForceUnlock() {
286 for (int i = (int)kNumClasses - 1; i >= 0; i--) {
287 GetRegionInfo(i)->mutex.Unlock();
288 }
289 }
290
291 // Iterate over all existing chunks.
292 // The allocator must be locked when calling this function.
293 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
294 for (uptr class_id = 1; class_id < kNumClasses; class_id++) {
295 RegionInfo *region = GetRegionInfo(class_id);
296 uptr chunk_size = ClassIdToSize(class_id);
297 uptr region_beg = SpaceBeg() + class_id * kRegionSize;
298 uptr region_allocated_user_size =
299 AddressSpaceView::Load(region)->allocated_user;
300 for (uptr chunk = region_beg;
301 chunk < region_beg + region_allocated_user_size;
302 chunk += chunk_size) {
303 // Too slow: CHECK_EQ((void *)chunk, GetBlockBegin((void *)chunk));
304 callback(chunk, arg);
305 }
306 }
307 }
308
309 static uptr ClassIdToSize(uptr class_id) {
310 return SizeClassMap::Size(class_id);
25
Calling 'SizeClassMap::Size'
311 }
312
313 static uptr AdditionalSize() {
314 return RoundUpTo(sizeof(RegionInfo) * kNumClassesRounded,
315 GetPageSizeCached());
316 }
317
318 typedef SizeClassMap SizeClassMapT;
319 static const uptr kNumClasses = SizeClassMap::kNumClasses;
320 static const uptr kNumClassesRounded = SizeClassMap::kNumClassesRounded;
321
322 // A packed array of counters. Each counter occupies 2^n bits, enough to store
323 // counter's max_value. Ctor will try to allocate the required buffer via
324 // mapper->MapPackedCounterArrayBuffer and the caller is expected to check
325 // whether the initialization was successful by checking IsAllocated() result.
326 // For the performance sake, none of the accessors check the validity of the
327 // arguments, it is assumed that index is always in [0, n) range and the value
328 // is not incremented past max_value.
329 template<class MemoryMapperT>
330 class PackedCounterArray {
331 public:
332 PackedCounterArray(u64 num_counters, u64 max_value, MemoryMapperT *mapper)
333 : n(num_counters), memory_mapper(mapper) {
334 CHECK_GT(num_counters, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((num_counters))
; __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 334, "(" "(num_counters)" ") " ">" " (" "(0)" ")", v1, v2
); } while (false)
;
335 CHECK_GT(max_value, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((max_value)); __sanitizer
::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect(!!(!
(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 335, "(" "(max_value)" ") " ">" " (" "(0)" ")", v1, v2);
} while (false)
;
336 constexpr u64 kMaxCounterBits = sizeof(*buffer) * 8ULL;
337 // Rounding counter storage size up to the power of two allows for using
338 // bit shifts calculating particular counter's index and offset.
339 uptr counter_size_bits =
340 RoundUpToPowerOfTwo(MostSignificantSetBitIndex(max_value) + 1);
341 CHECK_LE(counter_size_bits, kMaxCounterBits)do { __sanitizer::u64 v1 = (__sanitizer::u64)((counter_size_bits
)); __sanitizer::u64 v2 = (__sanitizer::u64)((kMaxCounterBits
)); if (__builtin_expect(!!(!(v1 <= v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 341, "(" "(counter_size_bits)" ") " "<=" " (" "(kMaxCounterBits)"
")", v1, v2); } while (false)
;
342 counter_size_bits_log = Log2(counter_size_bits);
343 counter_mask = ~0ULL >> (kMaxCounterBits - counter_size_bits);
344
345 uptr packing_ratio = kMaxCounterBits >> counter_size_bits_log;
346 CHECK_GT(packing_ratio, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((packing_ratio)
); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 346, "(" "(packing_ratio)" ") " ">" " (" "(0)" ")", v1, v2
); } while (false)
;
347 packing_ratio_log = Log2(packing_ratio);
348 bit_offset_mask = packing_ratio - 1;
349
350 buffer_size =
351 (RoundUpTo(n, 1ULL << packing_ratio_log) >> packing_ratio_log) *
352 sizeof(*buffer);
353 buffer = reinterpret_cast<u64*>(
354 memory_mapper->MapPackedCounterArrayBuffer(buffer_size));
355 }
356 ~PackedCounterArray() {
357 if (buffer) {
358 memory_mapper->UnmapPackedCounterArrayBuffer(
359 reinterpret_cast<uptr>(buffer), buffer_size);
360 }
361 }
362
363 bool IsAllocated() const {
364 return !!buffer;
365 }
366
367 u64 GetCount() const {
368 return n;
369 }
370
371 uptr Get(uptr i) const {
372 DCHECK_LT(i, n);
373 uptr index = i >> packing_ratio_log;
374 uptr bit_offset = (i & bit_offset_mask) << counter_size_bits_log;
375 return (buffer[index] >> bit_offset) & counter_mask;
376 }
377
378 void Inc(uptr i) const {
379 DCHECK_LT(Get(i), counter_mask);
380 uptr index = i >> packing_ratio_log;
381 uptr bit_offset = (i & bit_offset_mask) << counter_size_bits_log;
382 buffer[index] += 1ULL << bit_offset;
383 }
384
385 void IncRange(uptr from, uptr to) const {
386 DCHECK_LE(from, to);
387 for (uptr i = from; i <= to; i++)
388 Inc(i);
389 }
390
391 private:
392 const u64 n;
393 u64 counter_size_bits_log;
394 u64 counter_mask;
395 u64 packing_ratio_log;
396 u64 bit_offset_mask;
397
398 MemoryMapperT* const memory_mapper;
399 u64 buffer_size;
400 u64* buffer;
401 };
402
403 template<class MemoryMapperT>
404 class FreePagesRangeTracker {
405 public:
406 explicit FreePagesRangeTracker(MemoryMapperT* mapper)
407 : memory_mapper(mapper),
408 page_size_scaled_log(Log2(GetPageSizeCached() >> kCompactPtrScale)),
409 in_the_range(false), current_page(0), current_range_start_page(0) {}
410
411 void NextPage(bool freed) {
412 if (freed) {
413 if (!in_the_range) {
414 current_range_start_page = current_page;
415 in_the_range = true;
416 }
417 } else {
418 CloseOpenedRange();
419 }
420 current_page++;
421 }
422
423 void Done() {
424 CloseOpenedRange();
425 }
426
427 private:
428 void CloseOpenedRange() {
429 if (in_the_range) {
430 memory_mapper->ReleasePageRangeToOS(
431 current_range_start_page << page_size_scaled_log,
432 current_page << page_size_scaled_log);
433 in_the_range = false;
434 }
435 }
436
437 MemoryMapperT* const memory_mapper;
438 const uptr page_size_scaled_log;
439 bool in_the_range;
440 uptr current_page;
441 uptr current_range_start_page;
442 };
443
444 // Iterates over the free_array to identify memory pages containing freed
445 // chunks only and returns these pages back to OS.
446 // allocated_pages_count is the total number of pages allocated for the
447 // current bucket.
448 template<class MemoryMapperT>
449 static void ReleaseFreeMemoryToOS(CompactPtrT *free_array,
450 uptr free_array_count, uptr chunk_size,
451 uptr allocated_pages_count,
452 MemoryMapperT *memory_mapper) {
453 const uptr page_size = GetPageSizeCached();
454
455 // Figure out the number of chunks per page and whether we can take a fast
456 // path (the number of chunks per page is the same for all pages).
457 uptr full_pages_chunk_count_max;
458 bool same_chunk_count_per_page;
459 if (chunk_size <= page_size && page_size % chunk_size == 0) {
460 // Same number of chunks per page, no cross overs.
461 full_pages_chunk_count_max = page_size / chunk_size;
462 same_chunk_count_per_page = true;
463 } else if (chunk_size <= page_size && page_size % chunk_size != 0 &&
464 chunk_size % (page_size % chunk_size) == 0) {
465 // Some chunks are crossing page boundaries, which means that the page
466 // contains one or two partial chunks, but all pages contain the same
467 // number of chunks.
468 full_pages_chunk_count_max = page_size / chunk_size + 1;
469 same_chunk_count_per_page = true;
470 } else if (chunk_size <= page_size) {
471 // Some chunks are crossing page boundaries, which means that the page
472 // contains one or two partial chunks.
473 full_pages_chunk_count_max = page_size / chunk_size + 2;
474 same_chunk_count_per_page = false;
475 } else if (chunk_size > page_size && chunk_size % page_size == 0) {
476 // One chunk covers multiple pages, no cross overs.
477 full_pages_chunk_count_max = 1;
478 same_chunk_count_per_page = true;
479 } else if (chunk_size > page_size) {
480 // One chunk covers multiple pages, Some chunks are crossing page
481 // boundaries. Some pages contain one chunk, some contain two.
482 full_pages_chunk_count_max = 2;
483 same_chunk_count_per_page = false;
484 } else {
485 UNREACHABLE("All chunk_size/page_size ratios must be handled.")do { do { __sanitizer::u64 v1 = (__sanitizer::u64)((0 &&
"All chunk_size/page_size ratios must be handled.")); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 485, "(" "(0 && \"All chunk_size/page_size ratios must be handled.\")"
") " "!=" " (" "0" ")", v1, v2); } while (false); Die(); } while
(0)
;
486 }
487
488 PackedCounterArray<MemoryMapperT> counters(allocated_pages_count,
489 full_pages_chunk_count_max,
490 memory_mapper);
491 if (!counters.IsAllocated())
492 return;
493
494 const uptr chunk_size_scaled = chunk_size >> kCompactPtrScale;
495 const uptr page_size_scaled = page_size >> kCompactPtrScale;
496 const uptr page_size_scaled_log = Log2(page_size_scaled);
497
498 // Iterate over free chunks and count how many free chunks affect each
499 // allocated page.
500 if (chunk_size <= page_size && page_size % chunk_size == 0) {
501 // Each chunk affects one page only.
502 for (uptr i = 0; i < free_array_count; i++)
503 counters.Inc(free_array[i] >> page_size_scaled_log);
504 } else {
505 // In all other cases chunks might affect more than one page.
506 for (uptr i = 0; i < free_array_count; i++) {
507 counters.IncRange(
508 free_array[i] >> page_size_scaled_log,
509 (free_array[i] + chunk_size_scaled - 1) >> page_size_scaled_log);
510 }
511 }
512
513 // Iterate over pages detecting ranges of pages with chunk counters equal
514 // to the expected number of chunks for the particular page.
515 FreePagesRangeTracker<MemoryMapperT> range_tracker(memory_mapper);
516 if (same_chunk_count_per_page) {
517 // Fast path, every page has the same number of chunks affecting it.
518 for (uptr i = 0; i < counters.GetCount(); i++)
519 range_tracker.NextPage(counters.Get(i) == full_pages_chunk_count_max);
520 } else {
521 // Show path, go through the pages keeping count how many chunks affect
522 // each page.
523 const uptr pn =
524 chunk_size < page_size ? page_size_scaled / chunk_size_scaled : 1;
525 const uptr pnc = pn * chunk_size_scaled;
526 // The idea is to increment the current page pointer by the first chunk
527 // size, middle portion size (the portion of the page covered by chunks
528 // except the first and the last one) and then the last chunk size, adding
529 // up the number of chunks on the current page and checking on every step
530 // whether the page boundary was crossed.
531 uptr prev_page_boundary = 0;
532 uptr current_boundary = 0;
533 for (uptr i = 0; i < counters.GetCount(); i++) {
534 uptr page_boundary = prev_page_boundary + page_size_scaled;
535 uptr chunks_per_page = pn;
536 if (current_boundary < page_boundary) {
537 if (current_boundary > prev_page_boundary)
538 chunks_per_page++;
539 current_boundary += pnc;
540 if (current_boundary < page_boundary) {
541 chunks_per_page++;
542 current_boundary += chunk_size_scaled;
543 }
544 }
545 prev_page_boundary = page_boundary;
546
547 range_tracker.NextPage(counters.Get(i) == chunks_per_page);
548 }
549 }
550 range_tracker.Done();
551 }
552
553 private:
554 friend class MemoryMapper;
555
556 ReservedAddressRange address_range;
557
558 static const uptr kRegionSize = kSpaceSize / kNumClassesRounded;
559 // FreeArray is the array of free-d chunks (stored as 4-byte offsets).
560 // In the worst case it may reguire kRegionSize/SizeClassMap::kMinSize
561 // elements, but in reality this will not happen. For simplicity we
562 // dedicate 1/8 of the region's virtual space to FreeArray.
563 static const uptr kFreeArraySize = kRegionSize / 8;
564
565 static const bool kUsingConstantSpaceBeg = kSpaceBeg != ~(uptr)0;
566 uptr NonConstSpaceBeg;
567 uptr SpaceBeg() const {
568 return kUsingConstantSpaceBeg ? kSpaceBeg : NonConstSpaceBeg;
569 }
570 uptr SpaceEnd() const { return SpaceBeg() + kSpaceSize; }
571 // kRegionSize must be >= 2^32.
572 COMPILER_CHECK((kRegionSize) >= (1ULL << (SANITIZER_WORDSIZE / 2)))typedef char assertion_failed__572[2*(int)((kRegionSize) >=
(1ULL << (64 / 2)))-1]
;
573 // kRegionSize must be <= 2^36, see CompactPtrT.
574 COMPILER_CHECK((kRegionSize) <= (1ULL << (SANITIZER_WORDSIZE / 2 + 4)))typedef char assertion_failed__574[2*(int)((kRegionSize) <=
(1ULL << (64 / 2 + 4)))-1]
;
575 // Call mmap for user memory with at least this size.
576 static const uptr kUserMapSize = 1 << 16;
577 // Call mmap for metadata memory with at least this size.
578 static const uptr kMetaMapSize = 1 << 16;
579 // Call mmap for free array memory with at least this size.
580 static const uptr kFreeArrayMapSize = 1 << 16;
581
582 atomic_sint32_t release_to_os_interval_ms_;
583
584 struct Stats {
585 uptr n_allocated;
586 uptr n_freed;
587 };
588
589 struct ReleaseToOsInfo {
590 uptr n_freed_at_last_release;
591 uptr num_releases;
592 u64 last_release_at_ns;
593 u64 last_released_bytes;
594 };
595
596 struct ALIGNED(SANITIZER_CACHE_LINE_SIZE)__attribute__((aligned(64))) RegionInfo {
597 BlockingMutex mutex;
598 uptr num_freed_chunks; // Number of elements in the freearray.
599 uptr mapped_free_array; // Bytes mapped for freearray.
600 uptr allocated_user; // Bytes allocated for user memory.
601 uptr allocated_meta; // Bytes allocated for metadata.
602 uptr mapped_user; // Bytes mapped for user memory.
603 uptr mapped_meta; // Bytes mapped for metadata.
604 u32 rand_state; // Seed for random shuffle, used if kRandomShuffleChunks.
605 bool exhausted; // Whether region is out of space for new chunks.
606 Stats stats;
607 ReleaseToOsInfo rtoi;
608 };
609 COMPILER_CHECK(sizeof(RegionInfo) % kCacheLineSize == 0)typedef char assertion_failed__609[2*(int)(sizeof(RegionInfo)
% kCacheLineSize == 0)-1]
;
610
611 RegionInfo *GetRegionInfo(uptr class_id) const {
612 DCHECK_LT(class_id, kNumClasses);
613 RegionInfo *regions = reinterpret_cast<RegionInfo *>(SpaceEnd());
614 return &regions[class_id];
615 }
616
617 uptr GetMetadataEnd(uptr region_beg) const {
618 return region_beg + kRegionSize - kFreeArraySize;
619 }
620
621 uptr GetChunkIdx(uptr chunk, uptr size) const {
622 if (!kUsingConstantSpaceBeg)
623 chunk -= SpaceBeg();
624
625 uptr offset = chunk % kRegionSize;
626 // Here we divide by a non-constant. This is costly.
627 // size always fits into 32-bits. If the offset fits too, use 32-bit div.
628 if (offset >> (SANITIZER_WORDSIZE64 / 2))
629 return offset / size;
630 return (u32)offset / (u32)size;
631 }
632
633 CompactPtrT *GetFreeArray(uptr region_beg) const {
634 return reinterpret_cast<CompactPtrT *>(GetMetadataEnd(region_beg));
635 }
636
637 bool MapWithCallback(uptr beg, uptr size, const char *name) {
638 uptr mapped = address_range.Map(beg, size, name);
639 if (UNLIKELY(!mapped)__builtin_expect(!!(!mapped), 0))
640 return false;
641 CHECK_EQ(beg, mapped)do { __sanitizer::u64 v1 = (__sanitizer::u64)((beg)); __sanitizer
::u64 v2 = (__sanitizer::u64)((mapped)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 641, "(" "(beg)" ") " "==" " (" "(mapped)" ")", v1, v2); } while
(false)
;
642 MapUnmapCallback().OnMap(beg, size);
643 return true;
644 }
645
646 void MapWithCallbackOrDie(uptr beg, uptr size, const char *name) {
647 CHECK_EQ(beg, address_range.MapOrDie(beg, size, name))do { __sanitizer::u64 v1 = (__sanitizer::u64)((beg)); __sanitizer
::u64 v2 = (__sanitizer::u64)((address_range.MapOrDie(beg, size
, name))); if (__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer
::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 647, "(" "(beg)" ") " "==" " (" "(address_range.MapOrDie(beg, size, name))"
")", v1, v2); } while (false)
;
648 MapUnmapCallback().OnMap(beg, size);
649 }
650
651 void UnmapWithCallbackOrDie(uptr beg, uptr size) {
652 MapUnmapCallback().OnUnmap(beg, size);
653 address_range.Unmap(beg, size);
654 }
655
656 bool EnsureFreeArraySpace(RegionInfo *region, uptr region_beg,
657 uptr num_freed_chunks) {
658 uptr needed_space = num_freed_chunks * sizeof(CompactPtrT);
659 if (region->mapped_free_array < needed_space) {
660 uptr new_mapped_free_array = RoundUpTo(needed_space, kFreeArrayMapSize);
661 CHECK_LE(new_mapped_free_array, kFreeArraySize)do { __sanitizer::u64 v1 = (__sanitizer::u64)((new_mapped_free_array
)); __sanitizer::u64 v2 = (__sanitizer::u64)((kFreeArraySize)
); if (__builtin_expect(!!(!(v1 <= v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 661, "(" "(new_mapped_free_array)" ") " "<=" " (" "(kFreeArraySize)"
")", v1, v2); } while (false)
;
662 uptr current_map_end = reinterpret_cast<uptr>(GetFreeArray(region_beg)) +
663 region->mapped_free_array;
664 uptr new_map_size = new_mapped_free_array - region->mapped_free_array;
665 if (UNLIKELY(!MapWithCallback(current_map_end, new_map_size,__builtin_expect(!!(!MapWithCallback(current_map_end, new_map_size
, "SizeClassAllocator: freearray")), 0)
666 "SizeClassAllocator: freearray"))__builtin_expect(!!(!MapWithCallback(current_map_end, new_map_size
, "SizeClassAllocator: freearray")), 0)
)
667 return false;
668 region->mapped_free_array = new_mapped_free_array;
669 }
670 return true;
671 }
672
673 // Check whether this size class is exhausted.
674 bool IsRegionExhausted(RegionInfo *region, uptr class_id,
675 uptr additional_map_size) {
676 if (LIKELY(region->mapped_user + region->mapped_meta +__builtin_expect(!!(region->mapped_user + region->mapped_meta
+ additional_map_size <= kRegionSize - kFreeArraySize), 1
)
677 additional_map_size <= kRegionSize - kFreeArraySize)__builtin_expect(!!(region->mapped_user + region->mapped_meta
+ additional_map_size <= kRegionSize - kFreeArraySize), 1
)
)
678 return false;
679 if (!region->exhausted) {
680 region->exhausted = true;
681 Printf("%s: Out of memory. ", SanitizerToolName);
682 Printf("The process has exhausted %zuMB for size class %zu.\n",
683 kRegionSize >> 20, ClassIdToSize(class_id));
684 }
685 return true;
686 }
687
688 NOINLINE__attribute__((noinline)) bool PopulateFreeArray(AllocatorStats *stat, uptr class_id,
689 RegionInfo *region, uptr requested_count) {
690 // region->mutex is held.
691 const uptr region_beg = GetRegionBeginBySizeClass(class_id);
692 const uptr size = ClassIdToSize(class_id);
693
694 const uptr total_user_bytes =
695 region->allocated_user + requested_count * size;
696 // Map more space for chunks, if necessary.
697 if (LIKELY(total_user_bytes > region->mapped_user)__builtin_expect(!!(total_user_bytes > region->mapped_user
), 1)
) {
698 if (UNLIKELY(region->mapped_user == 0)__builtin_expect(!!(region->mapped_user == 0), 0)) {
699 if (!kUsingConstantSpaceBeg && kRandomShuffleChunks)
700 // The random state is initialized from ASLR.
701 region->rand_state = static_cast<u32>(region_beg >> 12);
702 // Postpone the first release to OS attempt for ReleaseToOSIntervalMs,
703 // preventing just allocated memory from being released sooner than
704 // necessary and also preventing extraneous ReleaseMemoryPagesToOS calls
705 // for short lived processes.
706 // Do it only when the feature is turned on, to avoid a potentially
707 // extraneous syscall.
708 if (ReleaseToOSIntervalMs() >= 0)
709 region->rtoi.last_release_at_ns = MonotonicNanoTime();
710 }
711 // Do the mmap for the user memory.
712 const uptr user_map_size =
713 RoundUpTo(total_user_bytes - region->mapped_user, kUserMapSize);
714 if (UNLIKELY(IsRegionExhausted(region, class_id, user_map_size))__builtin_expect(!!(IsRegionExhausted(region, class_id, user_map_size
)), 0)
)
715 return false;
716 if (UNLIKELY(!MapWithCallback(region_beg + region->mapped_user,__builtin_expect(!!(!MapWithCallback(region_beg + region->
mapped_user, user_map_size, "SizeClassAllocator: region data"
)), 0)
717 user_map_size,__builtin_expect(!!(!MapWithCallback(region_beg + region->
mapped_user, user_map_size, "SizeClassAllocator: region data"
)), 0)
718 "SizeClassAllocator: region data"))__builtin_expect(!!(!MapWithCallback(region_beg + region->
mapped_user, user_map_size, "SizeClassAllocator: region data"
)), 0)
)
719 return false;
720 stat->Add(AllocatorStatMapped, user_map_size);
721 region->mapped_user += user_map_size;
722 }
723 const uptr new_chunks_count =
724 (region->mapped_user - region->allocated_user) / size;
725
726 if (kMetadataSize) {
727 // Calculate the required space for metadata.
728 const uptr total_meta_bytes =
729 region->allocated_meta + new_chunks_count * kMetadataSize;
730 const uptr meta_map_size = (total_meta_bytes > region->mapped_meta) ?
731 RoundUpTo(total_meta_bytes - region->mapped_meta, kMetaMapSize) : 0;
732 // Map more space for metadata, if necessary.
733 if (meta_map_size) {
734 if (UNLIKELY(IsRegionExhausted(region, class_id, meta_map_size))__builtin_expect(!!(IsRegionExhausted(region, class_id, meta_map_size
)), 0)
)
735 return false;
736 if (UNLIKELY(!MapWithCallback(__builtin_expect(!!(!MapWithCallback( GetMetadataEnd(region_beg
) - region->mapped_meta - meta_map_size, meta_map_size, "SizeClassAllocator: region metadata"
)), 0)
737 GetMetadataEnd(region_beg) - region->mapped_meta - meta_map_size,__builtin_expect(!!(!MapWithCallback( GetMetadataEnd(region_beg
) - region->mapped_meta - meta_map_size, meta_map_size, "SizeClassAllocator: region metadata"
)), 0)
738 meta_map_size, "SizeClassAllocator: region metadata"))__builtin_expect(!!(!MapWithCallback( GetMetadataEnd(region_beg
) - region->mapped_meta - meta_map_size, meta_map_size, "SizeClassAllocator: region metadata"
)), 0)
)
739 return false;
740 region->mapped_meta += meta_map_size;
741 }
742 }
743
744 // If necessary, allocate more space for the free array and populate it with
745 // newly allocated chunks.
746 const uptr total_freed_chunks = region->num_freed_chunks + new_chunks_count;
747 if (UNLIKELY(!EnsureFreeArraySpace(region, region_beg, total_freed_chunks))__builtin_expect(!!(!EnsureFreeArraySpace(region, region_beg,
total_freed_chunks)), 0)
)
748 return false;
749 CompactPtrT *free_array = GetFreeArray(region_beg);
750 for (uptr i = 0, chunk = region->allocated_user; i < new_chunks_count;
751 i++, chunk += size)
752 free_array[total_freed_chunks - 1 - i] = PointerToCompactPtr(0, chunk);
753 if (kRandomShuffleChunks)
754 RandomShuffle(&free_array[region->num_freed_chunks], new_chunks_count,
755 &region->rand_state);
756
757 // All necessary memory is mapped and now it is safe to advance all
758 // 'allocated_*' counters.
759 region->num_freed_chunks += new_chunks_count;
760 region->allocated_user += new_chunks_count * size;
761 CHECK_LE(region->allocated_user, region->mapped_user)do { __sanitizer::u64 v1 = (__sanitizer::u64)((region->allocated_user
)); __sanitizer::u64 v2 = (__sanitizer::u64)((region->mapped_user
)); if (__builtin_expect(!!(!(v1 <= v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 761, "(" "(region->allocated_user)" ") " "<=" " (" "(region->mapped_user)"
")", v1, v2); } while (false)
;
762 region->allocated_meta += new_chunks_count * kMetadataSize;
763 CHECK_LE(region->allocated_meta, region->mapped_meta)do { __sanitizer::u64 v1 = (__sanitizer::u64)((region->allocated_meta
)); __sanitizer::u64 v2 = (__sanitizer::u64)((region->mapped_meta
)); if (__builtin_expect(!!(!(v1 <= v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h"
, 763, "(" "(region->allocated_meta)" ") " "<=" " (" "(region->mapped_meta)"
")", v1, v2); } while (false)
;
764 region->exhausted = false;
765
766 // TODO(alekseyshl): Consider bumping last_release_at_ns here to prevent
767 // MaybeReleaseToOS from releasing just allocated pages or protect these
768 // not yet used chunks some other way.
769
770 return true;
771 }
772
773 class MemoryMapper {
774 public:
775 MemoryMapper(const ThisT& base_allocator, uptr class_id)
776 : allocator(base_allocator),
777 region_base(base_allocator.GetRegionBeginBySizeClass(class_id)),
778 released_ranges_count(0),
779 released_bytes(0) {
780 }
781
782 uptr GetReleasedRangesCount() const {
783 return released_ranges_count;
784 }
785
786 uptr GetReleasedBytes() const {
787 return released_bytes;
788 }
789
790 uptr MapPackedCounterArrayBuffer(uptr buffer_size) {
791 // TODO(alekseyshl): The idea to explore is to check if we have enough
792 // space between num_freed_chunks*sizeof(CompactPtrT) and
793 // mapped_free_array to fit buffer_size bytes and use that space instead
794 // of mapping a temporary one.
795 return reinterpret_cast<uptr>(
796 MmapOrDieOnFatalError(buffer_size, "ReleaseToOSPageCounters"));
797 }
798
799 void UnmapPackedCounterArrayBuffer(uptr buffer, uptr buffer_size) {
800 UnmapOrDie(reinterpret_cast<void *>(buffer), buffer_size);
801 }
802
803 // Releases [from, to) range of pages back to OS.
804 void ReleasePageRangeToOS(CompactPtrT from, CompactPtrT to) {
805 const uptr from_page = allocator.CompactPtrToPointer(region_base, from);
806 const uptr to_page = allocator.CompactPtrToPointer(region_base, to);
807 ReleaseMemoryPagesToOS(from_page, to_page);
808 released_ranges_count++;
809 released_bytes += to_page - from_page;
810 }
811
812 private:
813 const ThisT& allocator;
814 const uptr region_base;
815 uptr released_ranges_count;
816 uptr released_bytes;
817 };
818
819 // Attempts to release RAM occupied by freed chunks back to OS. The region is
820 // expected to be locked.
821 void MaybeReleaseToOS(uptr class_id, bool force) {
822 RegionInfo *region = GetRegionInfo(class_id);
823 const uptr chunk_size = ClassIdToSize(class_id);
824 const uptr page_size = GetPageSizeCached();
825
826 uptr n = region->num_freed_chunks;
827 if (n * chunk_size < page_size)
828 return; // No chance to release anything.
829 if ((region->stats.n_freed -
830 region->rtoi.n_freed_at_last_release) * chunk_size < page_size) {
831 return; // Nothing new to release.
832 }
833
834 if (!force) {
835 s32 interval_ms = ReleaseToOSIntervalMs();
836 if (interval_ms < 0)
837 return;
838
839 if (region->rtoi.last_release_at_ns + interval_ms * 1000000ULL >
840 MonotonicNanoTime()) {
841 return; // Memory was returned recently.
842 }
843 }
844
845 MemoryMapper memory_mapper(*this, class_id);
846
847 ReleaseFreeMemoryToOS<MemoryMapper>(
848 GetFreeArray(GetRegionBeginBySizeClass(class_id)), n, chunk_size,
849 RoundUpTo(region->allocated_user, page_size) / page_size,
850 &memory_mapper);
851
852 if (memory_mapper.GetReleasedRangesCount() > 0) {
853 region->rtoi.n_freed_at_last_release = region->stats.n_freed;
854 region->rtoi.num_releases += memory_mapper.GetReleasedRangesCount();
855 region->rtoi.last_released_bytes = memory_mapper.GetReleasedBytes();
856 }
857 region->rtoi.last_release_at_ns = MonotonicNanoTime();
858 }
859};

/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h

1//===-- sanitizer_allocator_size_class_map.h --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Part of the Sanitizer Allocator.
10//
11//===----------------------------------------------------------------------===//
12#ifndef SANITIZER_ALLOCATOR_H
13#error This file must be included inside sanitizer_allocator.h
14#endif
15
16// SizeClassMap maps allocation sizes into size classes and back.
17// Class 0 always corresponds to size 0.
18// The other sizes are controlled by the template parameters:
19// kMinSizeLog: defines the class 1 as 2^kMinSizeLog.
20// kMaxSizeLog: defines the last class as 2^kMaxSizeLog.
21// kMidSizeLog: the classes starting from 1 increase with step
22// 2^kMinSizeLog until 2^kMidSizeLog.
23// kNumBits: the number of non-zero bits in sizes after 2^kMidSizeLog.
24// E.g. with kNumBits==3 all size classes after 2^kMidSizeLog
25// look like 0b1xx0..0, where x is either 0 or 1.
26//
27// Example: kNumBits=3, kMidSizeLog=4, kMidSizeLog=8, kMaxSizeLog=17:
28//
29// Classes 1 - 16 correspond to sizes 16 to 256 (size = class_id * 16).
30// Next 4 classes: 256 + i * 64 (i = 1 to 4).
31// Next 4 classes: 512 + i * 128 (i = 1 to 4).
32// ...
33// Next 4 classes: 2^k + i * 2^(k-2) (i = 1 to 4).
34// Last class corresponds to kMaxSize = 1 << kMaxSizeLog.
35//
36// This structure of the size class map gives us:
37// - Efficient table-free class-to-size and size-to-class functions.
38// - Difference between two consequent size classes is between 14% and 25%
39//
40// This class also gives a hint to a thread-caching allocator about the amount
41// of chunks that need to be cached per-thread:
42// - kMaxNumCachedHint is a hint for maximal number of chunks per size class.
43// The actual number is computed in TransferBatch.
44// - (1 << kMaxBytesCachedLog) is the maximal number of bytes per size class.
45//
46// Part of output of SizeClassMap::Print():
47// c00 => s: 0 diff: +0 00% l 0 cached: 0 0; id 0
48// c01 => s: 16 diff: +16 00% l 4 cached: 256 4096; id 1
49// c02 => s: 32 diff: +16 100% l 5 cached: 256 8192; id 2
50// c03 => s: 48 diff: +16 50% l 5 cached: 256 12288; id 3
51// c04 => s: 64 diff: +16 33% l 6 cached: 256 16384; id 4
52// c05 => s: 80 diff: +16 25% l 6 cached: 256 20480; id 5
53// c06 => s: 96 diff: +16 20% l 6 cached: 256 24576; id 6
54// c07 => s: 112 diff: +16 16% l 6 cached: 256 28672; id 7
55//
56// c08 => s: 128 diff: +16 14% l 7 cached: 256 32768; id 8
57// c09 => s: 144 diff: +16 12% l 7 cached: 256 36864; id 9
58// c10 => s: 160 diff: +16 11% l 7 cached: 256 40960; id 10
59// c11 => s: 176 diff: +16 10% l 7 cached: 256 45056; id 11
60// c12 => s: 192 diff: +16 09% l 7 cached: 256 49152; id 12
61// c13 => s: 208 diff: +16 08% l 7 cached: 256 53248; id 13
62// c14 => s: 224 diff: +16 07% l 7 cached: 256 57344; id 14
63// c15 => s: 240 diff: +16 07% l 7 cached: 256 61440; id 15
64//
65// c16 => s: 256 diff: +16 06% l 8 cached: 256 65536; id 16
66// c17 => s: 320 diff: +64 25% l 8 cached: 204 65280; id 17
67// c18 => s: 384 diff: +64 20% l 8 cached: 170 65280; id 18
68// c19 => s: 448 diff: +64 16% l 8 cached: 146 65408; id 19
69//
70// c20 => s: 512 diff: +64 14% l 9 cached: 128 65536; id 20
71// c21 => s: 640 diff: +128 25% l 9 cached: 102 65280; id 21
72// c22 => s: 768 diff: +128 20% l 9 cached: 85 65280; id 22
73// c23 => s: 896 diff: +128 16% l 9 cached: 73 65408; id 23
74//
75// c24 => s: 1024 diff: +128 14% l 10 cached: 64 65536; id 24
76// c25 => s: 1280 diff: +256 25% l 10 cached: 51 65280; id 25
77// c26 => s: 1536 diff: +256 20% l 10 cached: 42 64512; id 26
78// c27 => s: 1792 diff: +256 16% l 10 cached: 36 64512; id 27
79//
80// ...
81//
82// c48 => s: 65536 diff: +8192 14% l 16 cached: 1 65536; id 48
83// c49 => s: 81920 diff: +16384 25% l 16 cached: 1 81920; id 49
84// c50 => s: 98304 diff: +16384 20% l 16 cached: 1 98304; id 50
85// c51 => s: 114688 diff: +16384 16% l 16 cached: 1 114688; id 51
86//
87// c52 => s: 131072 diff: +16384 14% l 17 cached: 1 131072; id 52
88//
89//
90// Another example (kNumBits=2):
91// c00 => s: 0 diff: +0 00% l 0 cached: 0 0; id 0
92// c01 => s: 32 diff: +32 00% l 5 cached: 64 2048; id 1
93// c02 => s: 64 diff: +32 100% l 6 cached: 64 4096; id 2
94// c03 => s: 96 diff: +32 50% l 6 cached: 64 6144; id 3
95// c04 => s: 128 diff: +32 33% l 7 cached: 64 8192; id 4
96// c05 => s: 160 diff: +32 25% l 7 cached: 64 10240; id 5
97// c06 => s: 192 diff: +32 20% l 7 cached: 64 12288; id 6
98// c07 => s: 224 diff: +32 16% l 7 cached: 64 14336; id 7
99// c08 => s: 256 diff: +32 14% l 8 cached: 64 16384; id 8
100// c09 => s: 384 diff: +128 50% l 8 cached: 42 16128; id 9
101// c10 => s: 512 diff: +128 33% l 9 cached: 32 16384; id 10
102// c11 => s: 768 diff: +256 50% l 9 cached: 21 16128; id 11
103// c12 => s: 1024 diff: +256 33% l 10 cached: 16 16384; id 12
104// c13 => s: 1536 diff: +512 50% l 10 cached: 10 15360; id 13
105// c14 => s: 2048 diff: +512 33% l 11 cached: 8 16384; id 14
106// c15 => s: 3072 diff: +1024 50% l 11 cached: 5 15360; id 15
107// c16 => s: 4096 diff: +1024 33% l 12 cached: 4 16384; id 16
108// c17 => s: 6144 diff: +2048 50% l 12 cached: 2 12288; id 17
109// c18 => s: 8192 diff: +2048 33% l 13 cached: 2 16384; id 18
110// c19 => s: 12288 diff: +4096 50% l 13 cached: 1 12288; id 19
111// c20 => s: 16384 diff: +4096 33% l 14 cached: 1 16384; id 20
112// c21 => s: 24576 diff: +8192 50% l 14 cached: 1 24576; id 21
113// c22 => s: 32768 diff: +8192 33% l 15 cached: 1 32768; id 22
114// c23 => s: 49152 diff: +16384 50% l 15 cached: 1 49152; id 23
115// c24 => s: 65536 diff: +16384 33% l 16 cached: 1 65536; id 24
116// c25 => s: 98304 diff: +32768 50% l 16 cached: 1 98304; id 25
117// c26 => s: 131072 diff: +32768 33% l 17 cached: 1 131072; id 26
118
119template <uptr kNumBits, uptr kMinSizeLog, uptr kMidSizeLog, uptr kMaxSizeLog,
120 uptr kMaxNumCachedHintT, uptr kMaxBytesCachedLog>
121class SizeClassMap {
122 static const uptr kMinSize = 1 << kMinSizeLog;
123 static const uptr kMidSize = 1 << kMidSizeLog;
124 static const uptr kMidClass = kMidSize / kMinSize;
125 static const uptr S = kNumBits - 1;
126 static const uptr M = (1 << S) - 1;
127
128 public:
129 // kMaxNumCachedHintT is a power of two. It serves as a hint
130 // for the size of TransferBatch, the actual size could be a bit smaller.
131 static const uptr kMaxNumCachedHint = kMaxNumCachedHintT;
132 COMPILER_CHECK((kMaxNumCachedHint & (kMaxNumCachedHint - 1)) == 0)typedef char assertion_failed__132[2*(int)((kMaxNumCachedHint
& (kMaxNumCachedHint - 1)) == 0)-1]
;
133
134 static const uptr kMaxSize = 1UL << kMaxSizeLog;
135 static const uptr kNumClasses =
136 kMidClass + ((kMaxSizeLog - kMidSizeLog) << S) + 1 + 1;
137 static const uptr kLargestClassID = kNumClasses - 2;
138 static const uptr kBatchClassID = kNumClasses - 1;
139 COMPILER_CHECK(kNumClasses >= 16 && kNumClasses <= 256)typedef char assertion_failed__139[2*(int)(kNumClasses >= 16
&& kNumClasses <= 256)-1]
;
140 static const uptr kNumClassesRounded =
141 kNumClasses <= 32 ? 32 :
142 kNumClasses <= 64 ? 64 :
143 kNumClasses <= 128 ? 128 : 256;
144
145 static uptr Size(uptr class_id) {
146 // Estimate the result for kBatchClassID because this class does not know
147 // the exact size of TransferBatch. It's OK since we are using the actual
148 // sizeof(TransferBatch) where it matters.
149 if (UNLIKELY(class_id == kBatchClassID)__builtin_expect(!!(class_id == kBatchClassID), 0))
26
Assuming 'class_id' is not equal to 'kBatchClassID'
27
Taking false branch
150 return kMaxNumCachedHint * sizeof(uptr);
151 if (class_id <= kMidClass)
28
Assuming 'class_id' is > 'kMidClass'
29
Taking false branch
152 return kMinSize * class_id;
153 class_id -= kMidClass;
154 uptr t = kMidSize << (class_id >> S);
30
The result of the left shift is undefined due to shifting '256' by '4611686018427387900', which is unrepresentable in the unsigned version of the return type '__sanitizer::uptr'
155 return t + (t >> S) * (class_id & M);
156 }
157
158 static uptr ClassID(uptr size) {
159 if (UNLIKELY(size > kMaxSize)__builtin_expect(!!(size > kMaxSize), 0))
160 return 0;
161 if (size <= kMidSize)
162 return (size + kMinSize - 1) >> kMinSizeLog;
163 const uptr l = MostSignificantSetBitIndex(size);
164 const uptr hbits = (size >> (l - S)) & M;
165 const uptr lbits = size & ((1U << (l - S)) - 1);
166 const uptr l1 = l - kMidSizeLog;
167 return kMidClass + (l1 << S) + hbits + (lbits > 0);
168 }
169
170 static uptr MaxCachedHint(uptr size) {
171 DCHECK_LE(size, kMaxSize);
172 if (UNLIKELY(size == 0)__builtin_expect(!!(size == 0), 0))
173 return 0;
174 uptr n;
175 // Force a 32-bit division if the template parameters allow for it.
176 if (kMaxBytesCachedLog > 31 || kMaxSizeLog > 31)
177 n = (1UL << kMaxBytesCachedLog) / size;
178 else
179 n = (1U << kMaxBytesCachedLog) / static_cast<u32>(size);
180 return Max<uptr>(1U, Min(kMaxNumCachedHint, n));
181 }
182
183 static void Print() {
184 uptr prev_s = 0;
185 uptr total_cached = 0;
186 for (uptr i = 0; i < kNumClasses; i++) {
187 uptr s = Size(i);
188 if (s >= kMidSize / 2 && (s & (s - 1)) == 0)
189 Printf("\n");
190 uptr d = s - prev_s;
191 uptr p = prev_s ? (d * 100 / prev_s) : 0;
192 uptr l = s ? MostSignificantSetBitIndex(s) : 0;
193 uptr cached = MaxCachedHint(s) * s;
194 if (i == kBatchClassID)
195 d = p = l = 0;
196 Printf("c%02zd => s: %zd diff: +%zd %02zd%% l %zd "
197 "cached: %zd %zd; id %zd\n",
198 i, Size(i), d, p, l, MaxCachedHint(s), cached, ClassID(s));
199 total_cached += cached;
200 prev_s = s;
201 }
202 Printf("Total cached: %zd\n", total_cached);
203 }
204
205 static void Validate() {
206 for (uptr c = 1; c < kNumClasses; c++) {
207 // Printf("Validate: c%zd\n", c);
208 uptr s = Size(c);
209 CHECK_NE(s, 0U)do { __sanitizer::u64 v1 = (__sanitizer::u64)((s)); __sanitizer
::u64 v2 = (__sanitizer::u64)((0U)); if (__builtin_expect(!!(
!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 209, "(" "(s)" ") " "!=" " (" "(0U)" ")", v1, v2); } while (
false)
;
210 if (c == kBatchClassID)
211 continue;
212 CHECK_EQ(ClassID(s), c)do { __sanitizer::u64 v1 = (__sanitizer::u64)((ClassID(s))); __sanitizer
::u64 v2 = (__sanitizer::u64)((c)); if (__builtin_expect(!!(!
(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 212, "(" "(ClassID(s))" ") " "==" " (" "(c)" ")", v1, v2); }
while (false)
;
213 if (c < kLargestClassID)
214 CHECK_EQ(ClassID(s + 1), c + 1)do { __sanitizer::u64 v1 = (__sanitizer::u64)((ClassID(s + 1)
)); __sanitizer::u64 v2 = (__sanitizer::u64)((c + 1)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 214, "(" "(ClassID(s + 1))" ") " "==" " (" "(c + 1)" ")", v1
, v2); } while (false)
;
215 CHECK_EQ(ClassID(s - 1), c)do { __sanitizer::u64 v1 = (__sanitizer::u64)((ClassID(s - 1)
)); __sanitizer::u64 v2 = (__sanitizer::u64)((c)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 215, "(" "(ClassID(s - 1))" ") " "==" " (" "(c)" ")", v1, v2
); } while (false)
;
216 CHECK_GT(Size(c), Size(c - 1))do { __sanitizer::u64 v1 = (__sanitizer::u64)((Size(c))); __sanitizer
::u64 v2 = (__sanitizer::u64)((Size(c - 1))); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 216, "(" "(Size(c))" ") " ">" " (" "(Size(c - 1))" ")", v1
, v2); } while (false)
;
217 }
218 CHECK_EQ(ClassID(kMaxSize + 1), 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((ClassID(kMaxSize
+ 1))); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 218, "(" "(ClassID(kMaxSize + 1))" ") " "==" " (" "(0)" ")"
, v1, v2); } while (false)
;
219
220 for (uptr s = 1; s <= kMaxSize; s++) {
221 uptr c = ClassID(s);
222 // Printf("s%zd => c%zd\n", s, c);
223 CHECK_LT(c, kNumClasses)do { __sanitizer::u64 v1 = (__sanitizer::u64)((c)); __sanitizer
::u64 v2 = (__sanitizer::u64)((kNumClasses)); if (__builtin_expect
(!!(!(v1 < v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 223, "(" "(c)" ") " "<" " (" "(kNumClasses)" ")", v1, v2
); } while (false)
;
224 CHECK_GE(Size(c), s)do { __sanitizer::u64 v1 = (__sanitizer::u64)((Size(c))); __sanitizer
::u64 v2 = (__sanitizer::u64)((s)); if (__builtin_expect(!!(!
(v1 >= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 224, "(" "(Size(c))" ") " ">=" " (" "(s)" ")", v1, v2); }
while (false)
;
225 if (c > 0)
226 CHECK_LT(Size(c - 1), s)do { __sanitizer::u64 v1 = (__sanitizer::u64)((Size(c - 1)));
__sanitizer::u64 v2 = (__sanitizer::u64)((s)); if (__builtin_expect
(!!(!(v1 < v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-10~svn374877/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_size_class_map.h"
, 226, "(" "(Size(c - 1))" ") " "<" " (" "(s)" ")", v1, v2
); } while (false)
;
227 }
228 }
229};
230
231typedef SizeClassMap<3, 4, 8, 17, 128, 16> DefaultSizeClassMap;
232typedef SizeClassMap<3, 4, 8, 17, 64, 14> CompactSizeClassMap;
233typedef SizeClassMap<2, 5, 9, 16, 64, 14> VeryCompactSizeClassMap;
234
235// The following SizeClassMap only holds a way small number of cached entries,
236// allowing for denser per-class arrays, smaller memory footprint and usually
237// better performances in threaded environments.
238typedef SizeClassMap<3, 4, 8, 17, 8, 10> DenseSizeClassMap;
239// Similar to VeryCompact map above, this one has a small number of different
240// size classes, and also reduced thread-local caches.
241typedef SizeClassMap<2, 5, 9, 16, 8, 10> VeryDenseSizeClassMap;