blob: 2b7f099dfef4982801dc7e1904de03f7adef66a3 [file] [log] [blame]
Kostya Serebryany712fc982016-06-07 01:20:26 +00001//===-- scudo_allocator.cpp -------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// Scudo Hardened Allocator implementation.
11/// It uses the sanitizer_common allocator as a base and aims at mitigating
12/// heap corruption vulnerabilities. It provides a checksum-guarded chunk
13/// header, a delayed free list, and additional sanity checks.
14///
15//===----------------------------------------------------------------------===//
16
17#include "scudo_allocator.h"
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000018#include "scudo_crc32.h"
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000019#include "scudo_tls.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000020#include "scudo_utils.h"
21
22#include "sanitizer_common/sanitizer_allocator_interface.h"
23#include "sanitizer_common/sanitizer_quarantine.h"
24
25#include <limits.h>
26#include <pthread.h>
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000027#include <string.h>
Kostya Serebryany712fc982016-06-07 01:20:26 +000028
29namespace __scudo {
30
Kostya Serebryany712fc982016-06-07 01:20:26 +000031// Global static cookie, initialized at start-up.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000032static uptr Cookie;
33
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000034// We default to software CRC32 if the alternatives are not supported, either
35// at compilation or at runtime.
36static atomic_uint8_t HashAlgorithm = { CRC32Software };
37
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000038INLINE u32 computeCRC32(uptr Crc, uptr Value, uptr *Array, uptr ArraySize) {
39 // If the hardware CRC32 feature is defined here, it was enabled everywhere,
40 // as opposed to only for scudo_crc32.cpp. This means that other hardware
41 // specific instructions were likely emitted at other places, and as a
42 // result there is no reason to not use it here.
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000043#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000044 Crc = CRC32_INTRINSIC(Crc, Value);
45 for (uptr i = 0; i < ArraySize; i++)
46 Crc = CRC32_INTRINSIC(Crc, Array[i]);
47 return Crc;
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000048#else
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000049 if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) {
50 Crc = computeHardwareCRC32(Crc, Value);
51 for (uptr i = 0; i < ArraySize; i++)
52 Crc = computeHardwareCRC32(Crc, Array[i]);
53 return Crc;
54 }
55 Crc = computeSoftwareCRC32(Crc, Value);
56 for (uptr i = 0; i < ArraySize; i++)
57 Crc = computeSoftwareCRC32(Crc, Array[i]);
58 return Crc;
59#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000060}
Kostya Serebryany712fc982016-06-07 01:20:26 +000061
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000062static ScudoBackendAllocator &getBackendAllocator();
63
Kostya Serebryany712fc982016-06-07 01:20:26 +000064struct ScudoChunk : UnpackedHeader {
65 // We can't use the offset member of the chunk itself, as we would double
66 // fetch it without any warranty that it wouldn't have been tampered. To
67 // prevent this, we work with a local copy of the header.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000068 void *getAllocBeg(UnpackedHeader *Header) {
Kostya Serebryany712fc982016-06-07 01:20:26 +000069 return reinterpret_cast<void *>(
70 reinterpret_cast<uptr>(this) - (Header->Offset << MinAlignmentLog));
71 }
72
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000073 // Returns the usable size for a chunk, meaning the amount of bytes from the
74 // beginning of the user data to the end of the backend allocated chunk.
75 uptr getUsableSize(UnpackedHeader *Header) {
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000076 uptr Size = getBackendAllocator().GetActuallyAllocatedSize(
77 getAllocBeg(Header));
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000078 if (Size == 0)
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000079 return 0;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000080 return Size - AlignedChunkHeaderSize - (Header->Offset << MinAlignmentLog);
81 }
82
83 // Compute the checksum of the Chunk pointer and its ChunkHeader.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000084 u16 computeChecksum(UnpackedHeader *Header) const {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000085 UnpackedHeader ZeroChecksumHeader = *Header;
86 ZeroChecksumHeader.Checksum = 0;
87 uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)];
88 memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder));
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000089 u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(this), HeaderHolder,
90 ARRAY_SIZE(HeaderHolder));
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000091 return static_cast<u16>(Crc);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000092 }
93
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000094 // Checks the validity of a chunk by verifying its checksum. It doesn't
95 // incur termination in the event of an invalid chunk.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000096 bool isValid() {
97 UnpackedHeader NewUnpackedHeader;
98 const AtomicPackedHeader *AtomicHeader =
99 reinterpret_cast<const AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000100 PackedHeader NewPackedHeader = atomic_load_relaxed(AtomicHeader);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000101 NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
102 return (NewUnpackedHeader.Checksum == computeChecksum(&NewUnpackedHeader));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000103 }
104
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000105 // Nulls out a chunk header. When returning the chunk to the backend, there
106 // is no need to store a valid ChunkAvailable header, as this would be
107 // computationally expensive. Zeroing out serves the same purpose by making
108 // the header invalid. In the extremely rare event where 0 would be a valid
109 // checksum for the chunk, the state of the chunk is ChunkAvailable anyway.
110 COMPILER_CHECK(ChunkAvailable == 0);
111 void eraseHeader() {
112 PackedHeader NullPackedHeader = 0;
113 AtomicPackedHeader *AtomicHeader =
114 reinterpret_cast<AtomicPackedHeader *>(this);
115 atomic_store_relaxed(AtomicHeader, NullPackedHeader);
116 }
117
Kostya Serebryany712fc982016-06-07 01:20:26 +0000118 // Loads and unpacks the header, verifying the checksum in the process.
119 void loadHeader(UnpackedHeader *NewUnpackedHeader) const {
120 const AtomicPackedHeader *AtomicHeader =
121 reinterpret_cast<const AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000122 PackedHeader NewPackedHeader = atomic_load_relaxed(AtomicHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000123 *NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000124 if (UNLIKELY(NewUnpackedHeader->Checksum !=
125 computeChecksum(NewUnpackedHeader))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000126 dieWithMessage("ERROR: corrupted chunk header at address %p\n", this);
127 }
128 }
129
130 // Packs and stores the header, computing the checksum in the process.
131 void storeHeader(UnpackedHeader *NewUnpackedHeader) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000132 NewUnpackedHeader->Checksum = computeChecksum(NewUnpackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000133 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
134 AtomicPackedHeader *AtomicHeader =
135 reinterpret_cast<AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000136 atomic_store_relaxed(AtomicHeader, NewPackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000137 }
138
139 // Packs and stores the header, computing the checksum in the process. We
140 // compare the current header with the expected provided one to ensure that
141 // we are not being raced by a corruption occurring in another thread.
142 void compareExchangeHeader(UnpackedHeader *NewUnpackedHeader,
143 UnpackedHeader *OldUnpackedHeader) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000144 NewUnpackedHeader->Checksum = computeChecksum(NewUnpackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000145 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
146 PackedHeader OldPackedHeader = bit_cast<PackedHeader>(*OldUnpackedHeader);
147 AtomicPackedHeader *AtomicHeader =
148 reinterpret_cast<AtomicPackedHeader *>(this);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000149 if (UNLIKELY(!atomic_compare_exchange_strong(AtomicHeader,
150 &OldPackedHeader,
151 NewPackedHeader,
152 memory_order_relaxed))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000153 dieWithMessage("ERROR: race on chunk header at address %p\n", this);
154 }
155 }
156};
157
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000158ScudoChunk *getScudoChunk(uptr UserBeg) {
159 return reinterpret_cast<ScudoChunk *>(UserBeg - AlignedChunkHeaderSize);
160}
161
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000162struct AllocatorOptions {
163 u32 QuarantineSizeMb;
164 u32 ThreadLocalQuarantineSizeKb;
165 bool MayReturnNull;
166 s32 ReleaseToOSIntervalMs;
167 bool DeallocationTypeMismatch;
168 bool DeleteSizeMismatch;
169 bool ZeroContents;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000170
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000171 void setFrom(const Flags *f, const CommonFlags *cf);
172 void copyTo(Flags *f, CommonFlags *cf) const;
173};
Kostya Serebryany712fc982016-06-07 01:20:26 +0000174
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000175void AllocatorOptions::setFrom(const Flags *f, const CommonFlags *cf) {
176 MayReturnNull = cf->allocator_may_return_null;
177 ReleaseToOSIntervalMs = cf->allocator_release_to_os_interval_ms;
178 QuarantineSizeMb = f->QuarantineSizeMb;
179 ThreadLocalQuarantineSizeKb = f->ThreadLocalQuarantineSizeKb;
180 DeallocationTypeMismatch = f->DeallocationTypeMismatch;
181 DeleteSizeMismatch = f->DeleteSizeMismatch;
182 ZeroContents = f->ZeroContents;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000183}
184
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000185void AllocatorOptions::copyTo(Flags *f, CommonFlags *cf) const {
186 cf->allocator_may_return_null = MayReturnNull;
187 cf->allocator_release_to_os_interval_ms = ReleaseToOSIntervalMs;
188 f->QuarantineSizeMb = QuarantineSizeMb;
189 f->ThreadLocalQuarantineSizeKb = ThreadLocalQuarantineSizeKb;
190 f->DeallocationTypeMismatch = DeallocationTypeMismatch;
191 f->DeleteSizeMismatch = DeleteSizeMismatch;
192 f->ZeroContents = ZeroContents;
193}
194
195static void initScudoInternal(const AllocatorOptions &Options);
196
197static bool ScudoInitIsRunning = false;
198
199void initScudo() {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000200 SanitizerToolName = "Scudo";
201 CHECK(!ScudoInitIsRunning && "Scudo init calls itself!");
202 ScudoInitIsRunning = true;
203
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +0000204 // Check if hardware CRC32 is supported in the binary and by the platform, if
205 // so, opt for the CRC32 hardware version of the checksum.
206 if (computeHardwareCRC32 && testCPUFeature(CRC32CPUFeature))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000207 atomic_store_relaxed(&HashAlgorithm, CRC32Hardware);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000208
Kostya Serebryany712fc982016-06-07 01:20:26 +0000209 initFlags();
210
211 AllocatorOptions Options;
212 Options.setFrom(getFlags(), common_flags());
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000213 initScudoInternal(Options);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000214
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000215 // TODO(kostyak): determine if MaybeStartBackgroudThread could be of some use.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000216
Kostya Serebryany712fc982016-06-07 01:20:26 +0000217 ScudoInitIsRunning = false;
218}
219
Kostya Serebryany712fc982016-06-07 01:20:26 +0000220struct QuarantineCallback {
221 explicit QuarantineCallback(AllocatorCache *Cache)
222 : Cache_(Cache) {}
223
224 // Chunk recycling function, returns a quarantined chunk to the backend.
225 void Recycle(ScudoChunk *Chunk) {
226 UnpackedHeader Header;
227 Chunk->loadHeader(&Header);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000228 if (UNLIKELY(Header.State != ChunkQuarantine)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000229 dieWithMessage("ERROR: invalid chunk state when recycling address %p\n",
230 Chunk);
231 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000232 Chunk->eraseHeader();
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000233 void *Ptr = Chunk->getAllocBeg(&Header);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000234 getBackendAllocator().Deallocate(Cache_, Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000235 }
236
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +0000237 // Internal quarantine allocation and deallocation functions.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000238 void *Allocate(uptr Size) {
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000239 // TODO(kostyak): figure out the best way to protect the batches.
240 return getBackendAllocator().Allocate(Cache_, Size, MinAlignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000241 }
242
243 void Deallocate(void *Ptr) {
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000244 getBackendAllocator().Deallocate(Cache_, Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000245 }
246
247 AllocatorCache *Cache_;
248};
249
250typedef Quarantine<QuarantineCallback, ScudoChunk> ScudoQuarantine;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000251typedef ScudoQuarantine::Cache ScudoQuarantineCache;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000252COMPILER_CHECK(sizeof(ScudoQuarantineCache) <=
253 sizeof(ScudoThreadContext::QuarantineCachePlaceHolder));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000254
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000255AllocatorCache *getAllocatorCache(ScudoThreadContext *ThreadContext) {
256 return &ThreadContext->Cache;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000257}
258
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000259ScudoQuarantineCache *getQuarantineCache(ScudoThreadContext *ThreadContext) {
260 return reinterpret_cast<
261 ScudoQuarantineCache *>(ThreadContext->QuarantineCachePlaceHolder);
262}
263
264Xorshift128Plus *getPrng(ScudoThreadContext *ThreadContext) {
265 return &ThreadContext->Prng;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000266}
267
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000268struct ScudoAllocator {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000269 static const uptr MaxAllowedMallocSize =
270 FIRST_32_SECOND_64(2UL << 30, 1ULL << 40);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000271
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000272 ScudoBackendAllocator BackendAllocator;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000273 ScudoQuarantine AllocatorQuarantine;
274
275 // The fallback caches are used when the thread local caches have been
276 // 'detroyed' on thread tear-down. They are protected by a Mutex as they can
277 // be accessed by different threads.
278 StaticSpinMutex FallbackMutex;
279 AllocatorCache FallbackAllocatorCache;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000280 ScudoQuarantineCache FallbackQuarantineCache;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000281 Xorshift128Plus FallbackPrng;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000282
283 bool DeallocationTypeMismatch;
284 bool ZeroContents;
285 bool DeleteSizeMismatch;
286
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000287 explicit ScudoAllocator(LinkerInitialized)
Kostya Serebryany712fc982016-06-07 01:20:26 +0000288 : AllocatorQuarantine(LINKER_INITIALIZED),
289 FallbackQuarantineCache(LINKER_INITIALIZED) {}
290
291 void init(const AllocatorOptions &Options) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000292 // Verify that the header offset field can hold the maximum offset. In the
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000293 // case of the Secondary allocator, it takes care of alignment and the
294 // offset will always be 0. In the case of the Primary, the worst case
295 // scenario happens in the last size class, when the backend allocation
296 // would already be aligned on the requested alignment, which would happen
297 // to be the maximum alignment that would fit in that size class. As a
298 // result, the maximum offset will be at most the maximum alignment for the
299 // last size class minus the header size, in multiples of MinAlignment.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000300 UnpackedHeader Header = {};
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000301 uptr MaxPrimaryAlignment = 1 << MostSignificantSetBitIndex(
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000302 SizeClassMap::kMaxSize - MinAlignment);
303 uptr MaxOffset = (MaxPrimaryAlignment - AlignedChunkHeaderSize) >>
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000304 MinAlignmentLog;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000305 Header.Offset = MaxOffset;
306 if (Header.Offset != MaxOffset) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000307 dieWithMessage("ERROR: the maximum possible offset doesn't fit in the "
308 "header\n");
309 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000310 // Verify that we can fit the maximum size or amount of unused bytes in the
311 // header. Given that the Secondary fits the allocation to a page, the worst
312 // case scenario happens in the Primary. It will depend on the second to
313 // last and last class sizes, as well as the dynamic base for the Primary.
314 // The following is an over-approximation that works for our needs.
315 uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
316 Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
317 if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000318 dieWithMessage("ERROR: the maximum possible unused bytes doesn't fit in "
319 "the header\n");
320 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000321
322 DeallocationTypeMismatch = Options.DeallocationTypeMismatch;
323 DeleteSizeMismatch = Options.DeleteSizeMismatch;
324 ZeroContents = Options.ZeroContents;
Evgeniy Stepanovd3305af2016-11-29 00:22:50 +0000325 BackendAllocator.Init(Options.MayReturnNull, Options.ReleaseToOSIntervalMs);
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000326 AllocatorQuarantine.Init(
327 static_cast<uptr>(Options.QuarantineSizeMb) << 20,
328 static_cast<uptr>(Options.ThreadLocalQuarantineSizeKb) << 10);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000329 BackendAllocator.InitCache(&FallbackAllocatorCache);
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000330 FallbackPrng.initFromURandom();
331 Cookie = FallbackPrng.getNext();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000332 }
333
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000334 // Helper function that checks for a valid Scudo chunk. nullptr isn't.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000335 bool isValidPointer(const void *UserPtr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000336 initThreadMaybe();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000337 if (!UserPtr)
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000338 return false;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000339 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
340 if (!IsAligned(UserBeg, MinAlignment))
341 return false;
342 return getScudoChunk(UserBeg)->isValid();
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000343 }
344
Kostya Serebryany712fc982016-06-07 01:20:26 +0000345 // Allocates a chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000346 void *allocate(uptr Size, uptr Alignment, AllocType Type,
347 bool ForceZeroContents = false) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000348 initThreadMaybe();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000349 if (UNLIKELY(!IsPowerOfTwo(Alignment))) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000350 dieWithMessage("ERROR: alignment is not a power of 2\n");
Kostya Serebryany712fc982016-06-07 01:20:26 +0000351 }
352 if (Alignment > MaxAlignment)
Vitaly Buka0ec5a282016-09-29 23:00:54 +0000353 return BackendAllocator.ReturnNullOrDieOnBadRequest();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000354 if (Alignment < MinAlignment)
355 Alignment = MinAlignment;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000356 if (Size >= MaxAllowedMallocSize)
Vitaly Buka0ec5a282016-09-29 23:00:54 +0000357 return BackendAllocator.ReturnNullOrDieOnBadRequest();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000358 if (Size == 0)
359 Size = 1;
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000360
361 uptr NeededSize = RoundUpTo(Size, MinAlignment) + AlignedChunkHeaderSize;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000362 if (Alignment > MinAlignment)
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000363 NeededSize += Alignment;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000364 if (NeededSize >= MaxAllowedMallocSize)
Vitaly Buka0ec5a282016-09-29 23:00:54 +0000365 return BackendAllocator.ReturnNullOrDieOnBadRequest();
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000366
367 // Primary backed and Secondary backed allocations have a different
368 // treatment. We deal with alignment requirements of Primary serviced
369 // allocations here, but the Secondary will take care of its own alignment
370 // needs, which means we also have to work around some limitations of the
371 // combined allocator to accommodate the situation.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000372 bool FromPrimary = PrimaryAllocator::CanAllocate(NeededSize, MinAlignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000373
374 void *Ptr;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000375 uptr Salt;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000376 uptr AllocationAlignment = FromPrimary ? MinAlignment : Alignment;
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000377 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000378 if (LIKELY(ThreadContext)) {
379 Salt = getPrng(ThreadContext)->getNext();
380 Ptr = BackendAllocator.Allocate(getAllocatorCache(ThreadContext),
381 NeededSize, AllocationAlignment);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000382 ThreadContext->unlock();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000383 } else {
384 SpinMutexLock l(&FallbackMutex);
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000385 Salt = FallbackPrng.getNext();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000386 Ptr = BackendAllocator.Allocate(&FallbackAllocatorCache, NeededSize,
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000387 AllocationAlignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000388 }
389 if (!Ptr)
Vitaly Buka0ec5a282016-09-29 23:00:54 +0000390 return BackendAllocator.ReturnNullOrDieOnOOM();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000391
Kostya Serebryany712fc982016-06-07 01:20:26 +0000392 uptr AllocBeg = reinterpret_cast<uptr>(Ptr);
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000393 // If the allocation was serviced by the secondary, the returned pointer
394 // accounts for ChunkHeaderSize to pass the alignment check of the combined
395 // allocator. Adjust it here.
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000396 if (!FromPrimary) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000397 AllocBeg -= AlignedChunkHeaderSize;
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000398 if (Alignment > MinAlignment)
399 NeededSize -= Alignment;
400 }
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000401
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000402 // If requested, we will zero out the entire contents of the returned chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000403 if ((ForceZeroContents || ZeroContents) && FromPrimary)
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000404 memset(Ptr, 0, BackendAllocator.GetActuallyAllocatedSize(Ptr));
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000405
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000406 uptr UserBeg = AllocBeg + AlignedChunkHeaderSize;
407 if (!IsAligned(UserBeg, Alignment))
408 UserBeg = RoundUpTo(UserBeg, Alignment);
409 CHECK_LE(UserBeg + Size, AllocBeg + NeededSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000410 UnpackedHeader Header = {};
411 Header.State = ChunkAllocated;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000412 uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000413 Header.Offset = Offset >> MinAlignmentLog;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000414 Header.AllocType = Type;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000415 if (FromPrimary) {
416 Header.FromPrimary = FromPrimary;
417 Header.SizeOrUnusedBytes = Size;
418 } else {
419 // The secondary fits the allocations to a page, so the amount of unused
420 // bytes is the difference between the end of the user allocation and the
421 // next page boundary.
422 uptr PageSize = GetPageSizeCached();
423 uptr TrailingBytes = (UserBeg + Size) & (PageSize - 1);
424 if (TrailingBytes)
425 Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
426 }
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000427 Header.Salt = static_cast<u8>(Salt);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000428 getScudoChunk(UserBeg)->storeHeader(&Header);
429 void *UserPtr = reinterpret_cast<void *>(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000430 // if (&__sanitizer_malloc_hook) __sanitizer_malloc_hook(UserPtr, Size);
431 return UserPtr;
432 }
433
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000434 // Place a chunk in the quarantine. In the event of a zero-sized quarantine,
435 // we directly deallocate the chunk, otherwise the flow would lead to the
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000436 // chunk being loaded (and checked) twice, and stored (and checksummed) once,
437 // with no additional security value.
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000438 void quarantineOrDeallocateChunk(ScudoChunk *Chunk, UnpackedHeader *Header,
439 uptr Size) {
440 bool BypassQuarantine = (AllocatorQuarantine.GetCacheSize() == 0);
441 if (BypassQuarantine) {
442 Chunk->eraseHeader();
443 void *Ptr = Chunk->getAllocBeg(Header);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000444 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000445 if (LIKELY(ThreadContext)) {
446 getBackendAllocator().Deallocate(getAllocatorCache(ThreadContext), Ptr);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000447 ThreadContext->unlock();
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000448 } else {
449 SpinMutexLock Lock(&FallbackMutex);
450 getBackendAllocator().Deallocate(&FallbackAllocatorCache, Ptr);
451 }
452 } else {
453 UnpackedHeader NewHeader = *Header;
454 NewHeader.State = ChunkQuarantine;
455 Chunk->compareExchangeHeader(&NewHeader, Header);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000456 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000457 if (LIKELY(ThreadContext)) {
458 AllocatorQuarantine.Put(getQuarantineCache(ThreadContext),
459 QuarantineCallback(
460 getAllocatorCache(ThreadContext)),
461 Chunk, Size);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000462 ThreadContext->unlock();
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000463 } else {
464 SpinMutexLock l(&FallbackMutex);
465 AllocatorQuarantine.Put(&FallbackQuarantineCache,
466 QuarantineCallback(&FallbackAllocatorCache),
467 Chunk, Size);
468 }
469 }
470 }
471
Kostya Serebryany712fc982016-06-07 01:20:26 +0000472 // Deallocates a Chunk, which means adding it to the delayed free list (or
473 // Quarantine).
474 void deallocate(void *UserPtr, uptr DeleteSize, AllocType Type) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000475 initThreadMaybe();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000476 // if (&__sanitizer_free_hook) __sanitizer_free_hook(UserPtr);
477 if (!UserPtr)
478 return;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000479 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
480 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000481 dieWithMessage("ERROR: attempted to deallocate a chunk not properly "
482 "aligned at address %p\n", UserPtr);
483 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000484 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000485 UnpackedHeader OldHeader;
486 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000487 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000488 dieWithMessage("ERROR: invalid chunk state when deallocating address "
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000489 "%p\n", UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000490 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000491 if (DeallocationTypeMismatch) {
492 // The deallocation type has to match the allocation one.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000493 if (OldHeader.AllocType != Type) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000494 // With the exception of memalign'd Chunks, that can be still be free'd.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000495 if (OldHeader.AllocType != FromMemalign || Type != FromMalloc) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000496 dieWithMessage("ERROR: allocation type mismatch on address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000497 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000498 }
499 }
500 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000501 uptr Size = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
502 Chunk->getUsableSize(&OldHeader) - OldHeader.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000503 if (DeleteSizeMismatch) {
504 if (DeleteSize && DeleteSize != Size) {
505 dieWithMessage("ERROR: invalid sized delete on chunk at address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000506 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000507 }
508 }
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000509
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000510 // If a small memory amount was allocated with a larger alignment, we want
511 // to take that into account. Otherwise the Quarantine would be filled with
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000512 // tiny chunks, taking a lot of VA memory. This is an approximation of the
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000513 // usable size, that allows us to not call GetActuallyAllocatedSize.
514 uptr LiableSize = Size + (OldHeader.Offset << MinAlignment);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000515 quarantineOrDeallocateChunk(Chunk, &OldHeader, LiableSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000516 }
517
Kostya Serebryany712fc982016-06-07 01:20:26 +0000518 // Reallocates a chunk. We can save on a new allocation if the new requested
519 // size still fits in the chunk.
520 void *reallocate(void *OldPtr, uptr NewSize) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000521 initThreadMaybe();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000522 uptr UserBeg = reinterpret_cast<uptr>(OldPtr);
523 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
524 dieWithMessage("ERROR: attempted to reallocate a chunk not properly "
525 "aligned at address %p\n", OldPtr);
526 }
527 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000528 UnpackedHeader OldHeader;
529 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000530 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000531 dieWithMessage("ERROR: invalid chunk state when reallocating address "
532 "%p\n", OldPtr);
533 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000534 if (UNLIKELY(OldHeader.AllocType != FromMalloc)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000535 dieWithMessage("ERROR: invalid chunk type when reallocating address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000536 OldPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000537 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000538 uptr UsableSize = Chunk->getUsableSize(&OldHeader);
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000539 // The new size still fits in the current chunk, and the size difference
540 // is reasonable.
541 if (NewSize <= UsableSize &&
542 (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000543 UnpackedHeader NewHeader = OldHeader;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000544 NewHeader.SizeOrUnusedBytes =
545 OldHeader.FromPrimary ? NewSize : UsableSize - NewSize;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000546 Chunk->compareExchangeHeader(&NewHeader, &OldHeader);
547 return OldPtr;
548 }
549 // Otherwise, we have to allocate a new chunk and copy the contents of the
550 // old one.
551 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
552 if (NewPtr) {
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000553 uptr OldSize = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
554 UsableSize - OldHeader.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000555 memcpy(NewPtr, OldPtr, Min(NewSize, OldSize));
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000556 quarantineOrDeallocateChunk(Chunk, &OldHeader, UsableSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000557 }
558 return NewPtr;
559 }
560
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000561 // Helper function that returns the actual usable size of a chunk.
562 uptr getUsableSize(const void *Ptr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000563 initThreadMaybe();
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000564 if (!Ptr)
565 return 0;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000566 uptr UserBeg = reinterpret_cast<uptr>(Ptr);
567 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000568 UnpackedHeader Header;
569 Chunk->loadHeader(&Header);
570 // Getting the usable size of a chunk only makes sense if it's allocated.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000571 if (UNLIKELY(Header.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000572 dieWithMessage("ERROR: invalid chunk state when sizing address %p\n",
573 Ptr);
574 }
575 return Chunk->getUsableSize(&Header);
576 }
577
Kostya Serebryany712fc982016-06-07 01:20:26 +0000578 void *calloc(uptr NMemB, uptr Size) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000579 initThreadMaybe();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000580 uptr Total = NMemB * Size;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000581 if (Size != 0 && Total / Size != NMemB) // Overflow check
Vitaly Buka0ec5a282016-09-29 23:00:54 +0000582 return BackendAllocator.ReturnNullOrDieOnBadRequest();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000583 return allocate(Total, MinAlignment, FromMalloc, true);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000584 }
585
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000586 void commitBack(ScudoThreadContext *ThreadContext) {
587 AllocatorCache *Cache = getAllocatorCache(ThreadContext);
588 AllocatorQuarantine.Drain(getQuarantineCache(ThreadContext),
589 QuarantineCallback(Cache));
590 BackendAllocator.DestroyCache(Cache);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000591 }
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000592
593 uptr getStats(AllocatorStat StatType) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000594 initThreadMaybe();
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000595 uptr stats[AllocatorStatCount];
596 BackendAllocator.GetStats(stats);
597 return stats[StatType];
598 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000599};
600
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000601static ScudoAllocator Instance(LINKER_INITIALIZED);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000602
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000603static ScudoBackendAllocator &getBackendAllocator() {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000604 return Instance.BackendAllocator;
605}
606
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000607static void initScudoInternal(const AllocatorOptions &Options) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000608 Instance.init(Options);
609}
610
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000611void ScudoThreadContext::init() {
612 getBackendAllocator().InitCache(&Cache);
613 Prng.initFromURandom();
614 memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
615}
616
617void ScudoThreadContext::commitBack() {
618 Instance.commitBack(this);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000619}
620
621void *scudoMalloc(uptr Size, AllocType Type) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000622 return Instance.allocate(Size, MinAlignment, Type);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000623}
624
625void scudoFree(void *Ptr, AllocType Type) {
626 Instance.deallocate(Ptr, 0, Type);
627}
628
629void scudoSizedFree(void *Ptr, uptr Size, AllocType Type) {
630 Instance.deallocate(Ptr, Size, Type);
631}
632
633void *scudoRealloc(void *Ptr, uptr Size) {
634 if (!Ptr)
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000635 return Instance.allocate(Size, MinAlignment, FromMalloc);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000636 if (Size == 0) {
637 Instance.deallocate(Ptr, 0, FromMalloc);
638 return nullptr;
639 }
640 return Instance.reallocate(Ptr, Size);
641}
642
643void *scudoCalloc(uptr NMemB, uptr Size) {
644 return Instance.calloc(NMemB, Size);
645}
646
647void *scudoValloc(uptr Size) {
648 return Instance.allocate(Size, GetPageSizeCached(), FromMemalign);
649}
650
651void *scudoMemalign(uptr Alignment, uptr Size) {
652 return Instance.allocate(Size, Alignment, FromMemalign);
653}
654
655void *scudoPvalloc(uptr Size) {
656 uptr PageSize = GetPageSizeCached();
657 Size = RoundUpTo(Size, PageSize);
658 if (Size == 0) {
659 // pvalloc(0) should allocate one page.
660 Size = PageSize;
661 }
662 return Instance.allocate(Size, PageSize, FromMemalign);
663}
664
665int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
666 *MemPtr = Instance.allocate(Size, Alignment, FromMemalign);
667 return 0;
668}
669
670void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
671 // size must be a multiple of the alignment. To avoid a division, we first
672 // make sure that alignment is a power of 2.
673 CHECK(IsPowerOfTwo(Alignment));
674 CHECK_EQ((Size & (Alignment - 1)), 0);
675 return Instance.allocate(Size, Alignment, FromMalloc);
676}
677
678uptr scudoMallocUsableSize(void *Ptr) {
679 return Instance.getUsableSize(Ptr);
680}
681
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000682} // namespace __scudo
Kostya Serebryany712fc982016-06-07 01:20:26 +0000683
684using namespace __scudo;
685
686// MallocExtension helper functions
687
688uptr __sanitizer_get_current_allocated_bytes() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000689 return Instance.getStats(AllocatorStatAllocated);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000690}
691
692uptr __sanitizer_get_heap_size() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000693 return Instance.getStats(AllocatorStatMapped);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000694}
695
696uptr __sanitizer_get_free_bytes() {
697 return 1;
698}
699
700uptr __sanitizer_get_unmapped_bytes() {
701 return 1;
702}
703
704uptr __sanitizer_get_estimated_allocated_size(uptr size) {
705 return size;
706}
707
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000708int __sanitizer_get_ownership(const void *Ptr) {
709 return Instance.isValidPointer(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000710}
711
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000712uptr __sanitizer_get_allocated_size(const void *Ptr) {
713 return Instance.getUsableSize(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000714}