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 '1073741820', which is unrepresentable in the unsigned version of the return type '__sanitizer::uptr'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple i386-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 -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu i686 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D clang_rt_scudo_dynamic_i386_EXPORTS -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/projects/compiler-rt/lib/scudo -I /build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn358860/include -I /build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/.. -U NDEBUG -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/32 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/i386-pc-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/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/projects/compiler-rt/lib/scudo -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn358860=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -fno-rtti -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-04-22-050718-5320-1 -x c++ /build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/scudo_allocator.cpp -faddrsig

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

/build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h

1//===-- sanitizer_allocator_primary32.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 SizeClassAllocator32LocalCache;
17
18// SizeClassAllocator32 -- allocator for 32-bit address space.
19// This allocator can theoretically be used on 64-bit arch, but there it is less
20// efficient than SizeClassAllocator64.
21//
22// [kSpaceBeg, kSpaceBeg + kSpaceSize) is the range of addresses which can
23// be returned by MmapOrDie().
24//
25// Region:
26// a result of a single call to MmapAlignedOrDieOnFatalError(kRegionSize,
27// kRegionSize).
28// Since the regions are aligned by kRegionSize, there are exactly
29// kNumPossibleRegions possible regions in the address space and so we keep
30// a ByteMap possible_regions to store the size classes of each Region.
31// 0 size class means the region is not used by the allocator.
32//
33// One Region is used to allocate chunks of a single size class.
34// A Region looks like this:
35// UserChunk1 .. UserChunkN <gap> MetaChunkN .. MetaChunk1
36//
37// In order to avoid false sharing the objects of this class should be
38// chache-line aligned.
39
40struct SizeClassAllocator32FlagMasks { // Bit masks.
41 enum {
42 kRandomShuffleChunks = 1,
43 kUseSeparateSizeClassForBatch = 2,
44 };
45};
46
47template <class Params>
48class SizeClassAllocator32 {
49 public:
50 using AddressSpaceView = typename Params::AddressSpaceView;
51 static const uptr kSpaceBeg = Params::kSpaceBeg;
52 static const u64 kSpaceSize = Params::kSpaceSize;
53 static const uptr kMetadataSize = Params::kMetadataSize;
54 typedef typename Params::SizeClassMap SizeClassMap;
55 static const uptr kRegionSizeLog = Params::kRegionSizeLog;
56 typedef typename Params::ByteMap ByteMap;
57 typedef typename Params::MapUnmapCallback MapUnmapCallback;
58
59 static_assert(
60 is_same<typename ByteMap::AddressSpaceView, AddressSpaceView>::value,
61 "AddressSpaceView type mismatch");
62
63 COMPILER_CHECK(!SANITIZER_SIGN_EXTENDED_ADDRESSES ||typedef char assertion_failed__64[2*(int)(!0 || (kSpaceSize &
(kSpaceSize - 1)) == 0)-1]
64 (kSpaceSize & (kSpaceSize - 1)) == 0)typedef char assertion_failed__64[2*(int)(!0 || (kSpaceSize &
(kSpaceSize - 1)) == 0)-1]
;
65
66 static const bool kRandomShuffleChunks = Params::kFlags &
67 SizeClassAllocator32FlagMasks::kRandomShuffleChunks;
68 static const bool kUseSeparateSizeClassForBatch = Params::kFlags &
69 SizeClassAllocator32FlagMasks::kUseSeparateSizeClassForBatch;
70
71 struct TransferBatch {
72 static const uptr kMaxNumCached = SizeClassMap::kMaxNumCachedHint - 2;
73 void SetFromArray(void *batch[], uptr count) {
74 DCHECK_LE(count, kMaxNumCached);
75 count_ = count;
76 for (uptr i = 0; i < count; i++)
77 batch_[i] = batch[i];
78 }
79 uptr Count() const { return count_; }
80 void Clear() { count_ = 0; }
81 void Add(void *ptr) {
82 batch_[count_++] = ptr;
83 DCHECK_LE(count_, kMaxNumCached);
84 }
85 void CopyToArray(void *to_batch[]) const {
86 for (uptr i = 0, n = Count(); i < n; i++)
87 to_batch[i] = batch_[i];
88 }
89
90 // How much memory do we need for a batch containing n elements.
91 static uptr AllocationSizeRequiredForNElements(uptr n) {
92 return sizeof(uptr) * 2 + sizeof(void *) * n;
93 }
94 static uptr MaxCached(uptr size) {
95 return Min(kMaxNumCached, SizeClassMap::MaxCachedHint(size));
96 }
97
98 TransferBatch *next;
99
100 private:
101 uptr count_;
102 void *batch_[kMaxNumCached];
103 };
104
105 static const uptr kBatchSize = sizeof(TransferBatch);
106 COMPILER_CHECK((kBatchSize & (kBatchSize - 1)) == 0)typedef char assertion_failed__106[2*(int)((kBatchSize & (
kBatchSize - 1)) == 0)-1]
;
107 COMPILER_CHECK(kBatchSize == SizeClassMap::kMaxNumCachedHint * sizeof(uptr))typedef char assertion_failed__107[2*(int)(kBatchSize == SizeClassMap
::kMaxNumCachedHint * sizeof(uptr))-1]
;
108
109 static uptr ClassIdToSize(uptr class_id) {
110 return (class_id == SizeClassMap::kBatchClassID) ?
24
Assuming 'class_id' is not equal to 'kBatchClassID'
25
'?' condition is false
111 kBatchSize : SizeClassMap::Size(class_id);
26
Calling 'SizeClassMap::Size'
112 }
113
114 typedef SizeClassAllocator32<Params> ThisT;
115 typedef SizeClassAllocator32LocalCache<ThisT> AllocatorCache;
116
117 void Init(s32 release_to_os_interval_ms) {
118 possible_regions.Init();
119 internal_memset(size_class_info_array, 0, sizeof(size_class_info_array));
120 }
121
122 s32 ReleaseToOSIntervalMs() const {
123 return kReleaseToOSIntervalNever;
124 }
125
126 void SetReleaseToOSIntervalMs(s32 release_to_os_interval_ms) {
127 // This is empty here. Currently only implemented in 64-bit allocator.
128 }
129
130 void ForceReleaseToOS() {
131 // Currently implemented in 64-bit allocator only.
132 }
133
134 void *MapWithCallback(uptr size) {
135 void *res = MmapOrDie(size, PrimaryAllocatorName);
136 MapUnmapCallback().OnMap((uptr)res, size);
137 return res;
138 }
139
140 void UnmapWithCallback(uptr beg, uptr size) {
141 MapUnmapCallback().OnUnmap(beg, size);
142 UnmapOrDie(reinterpret_cast<void *>(beg), size);
143 }
144
145 static bool CanAllocate(uptr size, uptr alignment) {
146 return size <= SizeClassMap::kMaxSize &&
147 alignment <= SizeClassMap::kMaxSize;
148 }
149
150 void *GetMetaData(const void *p) {
151 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-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 151, "(" "(PointerIsMine(p))" ") " "!=" " (" "0" ")", v1, v2
); } while (false)
;
152 uptr mem = reinterpret_cast<uptr>(p);
153 uptr beg = ComputeRegionBeg(mem);
154 uptr size = ClassIdToSize(GetSizeClass(p));
155 u32 offset = mem - beg;
156 uptr n = offset / (u32)size; // 32-bit division
157 uptr meta = (beg + kRegionSize) - (n + 1) * kMetadataSize;
158 return reinterpret_cast<void*>(meta);
159 }
160
161 NOINLINE__attribute__((noinline)) TransferBatch *AllocateBatch(AllocatorStats *stat, AllocatorCache *c,
162 uptr class_id) {
163 DCHECK_LT(class_id, kNumClasses);
164 SizeClassInfo *sci = GetSizeClassInfo(class_id);
165 SpinMutexLock l(&sci->mutex);
166 if (sci->free_list.empty()) {
167 if (UNLIKELY(!PopulateFreeList(stat, c, sci, class_id))__builtin_expect(!!(!PopulateFreeList(stat, c, sci, class_id)
), 0)
)
168 return nullptr;
169 DCHECK(!sci->free_list.empty());
170 }
171 TransferBatch *b = sci->free_list.front();
172 sci->free_list.pop_front();
173 return b;
174 }
175
176 NOINLINE__attribute__((noinline)) void DeallocateBatch(AllocatorStats *stat, uptr class_id,
177 TransferBatch *b) {
178 DCHECK_LT(class_id, kNumClasses);
179 CHECK_GT(b->Count(), 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((b->Count())
); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 179, "(" "(b->Count())" ") " ">" " (" "(0)" ")", v1, v2
); } while (false)
;
180 SizeClassInfo *sci = GetSizeClassInfo(class_id);
181 SpinMutexLock l(&sci->mutex);
182 sci->free_list.push_front(b);
183 }
184
185 bool PointerIsMine(const void *p) {
186 uptr mem = reinterpret_cast<uptr>(p);
187 if (SANITIZER_SIGN_EXTENDED_ADDRESSES0)
188 mem &= (kSpaceSize - 1);
189 if (mem < kSpaceBeg || mem >= kSpaceBeg + kSpaceSize)
190 return false;
191 return GetSizeClass(p) != 0;
192 }
193
194 uptr GetSizeClass(const void *p) {
195 return possible_regions[ComputeRegionId(reinterpret_cast<uptr>(p))];
196 }
197
198 void *GetBlockBegin(const 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-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 199, "(" "(PointerIsMine(p))" ") " "!=" " (" "0" ")", v1, v2
); } while (false)
;
200 uptr mem = reinterpret_cast<uptr>(p);
201 uptr beg = ComputeRegionBeg(mem);
202 uptr size = ClassIdToSize(GetSizeClass(p));
203 u32 offset = mem - beg;
204 u32 n = offset / (u32)size; // 32-bit division
205 uptr res = beg + (n * (u32)size);
206 return reinterpret_cast<void*>(res);
207 }
208
209 uptr GetActuallyAllocatedSize(void *p) {
210 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-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 210, "(" "(PointerIsMine(p))" ") " "!=" " (" "0" ")", v1, v2
); } while (false)
;
211 return ClassIdToSize(GetSizeClass(p));
212 }
213
214 uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); }
215
216 uptr TotalMemoryUsed() {
217 // No need to lock here.
218 uptr res = 0;
219 for (uptr i = 0; i < kNumPossibleRegions; i++)
220 if (possible_regions[i])
221 res += kRegionSize;
222 return res;
223 }
224
225 void TestOnlyUnmap() {
226 for (uptr i = 0; i < kNumPossibleRegions; i++)
227 if (possible_regions[i])
228 UnmapWithCallback((i * kRegionSize), kRegionSize);
229 }
230
231 // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
232 // introspection API.
233 void ForceLock() {
234 for (uptr i = 0; i < kNumClasses; i++) {
235 GetSizeClassInfo(i)->mutex.Lock();
236 }
237 }
238
239 void ForceUnlock() {
240 for (int i = kNumClasses - 1; i >= 0; i--) {
241 GetSizeClassInfo(i)->mutex.Unlock();
242 }
243 }
244
245 // Iterate over all existing chunks.
246 // The allocator must be locked when calling this function.
247 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
248 for (uptr region = 0; region < kNumPossibleRegions; region++)
249 if (possible_regions[region]) {
250 uptr chunk_size = ClassIdToSize(possible_regions[region]);
251 uptr max_chunks_in_region = kRegionSize / (chunk_size + kMetadataSize);
252 uptr region_beg = region * kRegionSize;
253 for (uptr chunk = region_beg;
254 chunk < region_beg + max_chunks_in_region * chunk_size;
255 chunk += chunk_size) {
256 // Too slow: CHECK_EQ((void *)chunk, GetBlockBegin((void *)chunk));
257 callback(chunk, arg);
258 }
259 }
260 }
261
262 void PrintStats() {}
263
264 static uptr AdditionalSize() { return 0; }
265
266 typedef SizeClassMap SizeClassMapT;
267 static const uptr kNumClasses = SizeClassMap::kNumClasses;
268
269 private:
270 static const uptr kRegionSize = 1 << kRegionSizeLog;
271 static const uptr kNumPossibleRegions = kSpaceSize / kRegionSize;
272
273 struct ALIGNED(SANITIZER_CACHE_LINE_SIZE)__attribute__((aligned(64))) SizeClassInfo {
274 StaticSpinMutex mutex;
275 IntrusiveList<TransferBatch> free_list;
276 u32 rand_state;
277 };
278 COMPILER_CHECK(sizeof(SizeClassInfo) % kCacheLineSize == 0)typedef char assertion_failed__278[2*(int)(sizeof(SizeClassInfo
) % kCacheLineSize == 0)-1]
;
279
280 uptr ComputeRegionId(uptr mem) {
281 if (SANITIZER_SIGN_EXTENDED_ADDRESSES0)
282 mem &= (kSpaceSize - 1);
283 const uptr res = mem >> kRegionSizeLog;
284 CHECK_LT(res, kNumPossibleRegions)do { __sanitizer::u64 v1 = (__sanitizer::u64)((res)); __sanitizer
::u64 v2 = (__sanitizer::u64)((kNumPossibleRegions)); if (__builtin_expect
(!!(!(v1 < v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 284, "(" "(res)" ") " "<" " (" "(kNumPossibleRegions)" ")"
, v1, v2); } while (false)
;
285 return res;
286 }
287
288 uptr ComputeRegionBeg(uptr mem) {
289 return mem & ~(kRegionSize - 1);
290 }
291
292 uptr AllocateRegion(AllocatorStats *stat, uptr class_id) {
293 DCHECK_LT(class_id, kNumClasses);
294 const uptr res = reinterpret_cast<uptr>(MmapAlignedOrDieOnFatalError(
295 kRegionSize, kRegionSize, PrimaryAllocatorName));
296 if (UNLIKELY(!res)__builtin_expect(!!(!res), 0))
297 return 0;
298 MapUnmapCallback().OnMap(res, kRegionSize);
299 stat->Add(AllocatorStatMapped, kRegionSize);
300 CHECK(IsAligned(res, kRegionSize))do { __sanitizer::u64 v1 = (__sanitizer::u64)((IsAligned(res,
kRegionSize))); __sanitizer::u64 v2 = (__sanitizer::u64)(0);
if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 300, "(" "(IsAligned(res, kRegionSize))" ") " "!=" " (" "0"
")", v1, v2); } while (false)
;
301 possible_regions.set(ComputeRegionId(res), static_cast<u8>(class_id));
302 return res;
303 }
304
305 SizeClassInfo *GetSizeClassInfo(uptr class_id) {
306 DCHECK_LT(class_id, kNumClasses);
307 return &size_class_info_array[class_id];
308 }
309
310 bool PopulateBatches(AllocatorCache *c, SizeClassInfo *sci, uptr class_id,
311 TransferBatch **current_batch, uptr max_count,
312 uptr *pointers_array, uptr count) {
313 // If using a separate class for batches, we do not need to shuffle it.
314 if (kRandomShuffleChunks && (!kUseSeparateSizeClassForBatch ||
315 class_id != SizeClassMap::kBatchClassID))
316 RandomShuffle(pointers_array, count, &sci->rand_state);
317 TransferBatch *b = *current_batch;
318 for (uptr i = 0; i < count; i++) {
319 if (!b) {
320 b = c->CreateBatch(class_id, this, (TransferBatch*)pointers_array[i]);
321 if (UNLIKELY(!b)__builtin_expect(!!(!b), 0))
322 return false;
323 b->Clear();
324 }
325 b->Add((void*)pointers_array[i]);
326 if (b->Count() == max_count) {
327 sci->free_list.push_back(b);
328 b = nullptr;
329 }
330 }
331 *current_batch = b;
332 return true;
333 }
334
335 bool PopulateFreeList(AllocatorStats *stat, AllocatorCache *c,
336 SizeClassInfo *sci, uptr class_id) {
337 const uptr region = AllocateRegion(stat, class_id);
338 if (UNLIKELY(!region)__builtin_expect(!!(!region), 0))
339 return false;
340 if (kRandomShuffleChunks)
341 if (UNLIKELY(sci->rand_state == 0)__builtin_expect(!!(sci->rand_state == 0), 0))
342 // The random state is initialized from ASLR (PIE) and time.
343 sci->rand_state = reinterpret_cast<uptr>(sci) ^ NanoTime();
344 const uptr size = ClassIdToSize(class_id);
345 const uptr n_chunks = kRegionSize / (size + kMetadataSize);
346 const uptr max_count = TransferBatch::MaxCached(size);
347 DCHECK_GT(max_count, 0);
348 TransferBatch *b = nullptr;
349 constexpr uptr kShuffleArraySize = 48;
350 uptr shuffle_array[kShuffleArraySize];
351 uptr count = 0;
352 for (uptr i = region; i < region + n_chunks * size; i += size) {
353 shuffle_array[count++] = i;
354 if (count == kShuffleArraySize) {
355 if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count,__builtin_expect(!!(!PopulateBatches(c, sci, class_id, &b
, max_count, shuffle_array, count)), 0)
356 shuffle_array, count))__builtin_expect(!!(!PopulateBatches(c, sci, class_id, &b
, max_count, shuffle_array, count)), 0)
)
357 return false;
358 count = 0;
359 }
360 }
361 if (count) {
362 if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count,__builtin_expect(!!(!PopulateBatches(c, sci, class_id, &b
, max_count, shuffle_array, count)), 0)
363 shuffle_array, count))__builtin_expect(!!(!PopulateBatches(c, sci, class_id, &b
, max_count, shuffle_array, count)), 0)
)
364 return false;
365 }
366 if (b) {
367 CHECK_GT(b->Count(), 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((b->Count())
); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-9~svn358860/projects/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_allocator_primary32.h"
, 367, "(" "(b->Count())" ") " ">" " (" "(0)" ")", v1, v2
); } while (false)
;
368 sci->free_list.push_back(b);
369 }
370 return true;
371 }
372
373 ByteMap possible_regions;
374 SizeClassInfo size_class_info_array[kNumClasses];
375};

/build/llvm-toolchain-snapshot-9~svn358860/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))
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 '1073741820', 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-9~svn358860/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-9~svn358860/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-9~svn358860/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-9~svn358860/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-9~svn358860/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-9~svn358860/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-9~svn358860/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-9~svn358860/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-9~svn358860/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;