blob: 102d1d0df8f0c937fcffd72fe03adf2882d161e6 [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"
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +000023#include "sanitizer_common/sanitizer_errno.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000024#include "sanitizer_common/sanitizer_quarantine.h"
25
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000026#include <string.h>
Kostya Serebryany712fc982016-06-07 01:20:26 +000027
28namespace __scudo {
29
Kostya Serebryany712fc982016-06-07 01:20:26 +000030// Global static cookie, initialized at start-up.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000031static uptr Cookie;
32
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000033// We default to software CRC32 if the alternatives are not supported, either
34// at compilation or at runtime.
35static atomic_uint8_t HashAlgorithm = { CRC32Software };
36
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000037INLINE u32 computeCRC32(uptr Crc, uptr Value, uptr *Array, uptr ArraySize) {
38 // If the hardware CRC32 feature is defined here, it was enabled everywhere,
39 // as opposed to only for scudo_crc32.cpp. This means that other hardware
40 // specific instructions were likely emitted at other places, and as a
41 // result there is no reason to not use it here.
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000042#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000043 Crc = CRC32_INTRINSIC(Crc, Value);
44 for (uptr i = 0; i < ArraySize; i++)
45 Crc = CRC32_INTRINSIC(Crc, Array[i]);
46 return Crc;
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000047#else
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000048 if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) {
49 Crc = computeHardwareCRC32(Crc, Value);
50 for (uptr i = 0; i < ArraySize; i++)
51 Crc = computeHardwareCRC32(Crc, Array[i]);
52 return Crc;
53 }
54 Crc = computeSoftwareCRC32(Crc, Value);
55 for (uptr i = 0; i < ArraySize; i++)
56 Crc = computeSoftwareCRC32(Crc, Array[i]);
57 return Crc;
58#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000059}
Kostya Serebryany712fc982016-06-07 01:20:26 +000060
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000061static ScudoBackendAllocator &getBackendAllocator();
62
Kostya Serebryany712fc982016-06-07 01:20:26 +000063struct ScudoChunk : UnpackedHeader {
64 // We can't use the offset member of the chunk itself, as we would double
65 // fetch it without any warranty that it wouldn't have been tampered. To
66 // prevent this, we work with a local copy of the header.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000067 void *getAllocBeg(UnpackedHeader *Header) {
Kostya Serebryany712fc982016-06-07 01:20:26 +000068 return reinterpret_cast<void *>(
69 reinterpret_cast<uptr>(this) - (Header->Offset << MinAlignmentLog));
70 }
71
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000072 // Returns the usable size for a chunk, meaning the amount of bytes from the
73 // beginning of the user data to the end of the backend allocated chunk.
74 uptr getUsableSize(UnpackedHeader *Header) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +000075 uptr Size =
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +000076 getBackendAllocator().getActuallyAllocatedSize(getAllocBeg(Header),
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +000077 Header->FromPrimary);
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
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000224 // Chunk recycling function, returns a quarantined chunk to the backend,
225 // first making sure it hasn't been tampered with.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000226 void Recycle(ScudoChunk *Chunk) {
227 UnpackedHeader Header;
228 Chunk->loadHeader(&Header);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000229 if (UNLIKELY(Header.State != ChunkQuarantine)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000230 dieWithMessage("ERROR: invalid chunk state when recycling address %p\n",
231 Chunk);
232 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000233 Chunk->eraseHeader();
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000234 void *Ptr = Chunk->getAllocBeg(&Header);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000235 if (Header.FromPrimary)
236 getBackendAllocator().deallocatePrimary(Cache_, Ptr);
237 else
238 getBackendAllocator().deallocateSecondary(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000239 }
240
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000241 // Internal quarantine allocation and deallocation functions. We first check
242 // that the batches are indeed serviced by the Primary.
243 // TODO(kostyak): figure out the best way to protect the batches.
244 COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000245 void *Allocate(uptr Size) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000246 return getBackendAllocator().allocatePrimary(Cache_, Size);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000247 }
248
249 void Deallocate(void *Ptr) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000250 getBackendAllocator().deallocatePrimary(Cache_, Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000251 }
252
253 AllocatorCache *Cache_;
254};
255
256typedef Quarantine<QuarantineCallback, ScudoChunk> ScudoQuarantine;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000257typedef ScudoQuarantine::Cache ScudoQuarantineCache;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000258COMPILER_CHECK(sizeof(ScudoQuarantineCache) <=
259 sizeof(ScudoThreadContext::QuarantineCachePlaceHolder));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000260
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000261AllocatorCache *getAllocatorCache(ScudoThreadContext *ThreadContext) {
262 return &ThreadContext->Cache;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000263}
264
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000265ScudoQuarantineCache *getQuarantineCache(ScudoThreadContext *ThreadContext) {
266 return reinterpret_cast<
267 ScudoQuarantineCache *>(ThreadContext->QuarantineCachePlaceHolder);
268}
269
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000270ScudoPrng *getPrng(ScudoThreadContext *ThreadContext) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000271 return &ThreadContext->Prng;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000272}
273
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000274struct ScudoAllocator {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000275 static const uptr MaxAllowedMallocSize =
276 FIRST_32_SECOND_64(2UL << 30, 1ULL << 40);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000277
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000278 typedef ReturnNullOrDieOnFailure FailureHandler;
279
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000280 ScudoBackendAllocator BackendAllocator;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000281 ScudoQuarantine AllocatorQuarantine;
282
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000283 StaticSpinMutex GlobalPrngMutex;
284 ScudoPrng GlobalPrng;
285
Kostya Serebryany712fc982016-06-07 01:20:26 +0000286 // The fallback caches are used when the thread local caches have been
287 // 'detroyed' on thread tear-down. They are protected by a Mutex as they can
288 // be accessed by different threads.
289 StaticSpinMutex FallbackMutex;
290 AllocatorCache FallbackAllocatorCache;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000291 ScudoQuarantineCache FallbackQuarantineCache;
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000292 ScudoPrng FallbackPrng;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000293
294 bool DeallocationTypeMismatch;
295 bool ZeroContents;
296 bool DeleteSizeMismatch;
297
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000298 explicit ScudoAllocator(LinkerInitialized)
Kostya Serebryany712fc982016-06-07 01:20:26 +0000299 : AllocatorQuarantine(LINKER_INITIALIZED),
300 FallbackQuarantineCache(LINKER_INITIALIZED) {}
301
302 void init(const AllocatorOptions &Options) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000303 // Verify that the header offset field can hold the maximum offset. In the
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000304 // case of the Secondary allocator, it takes care of alignment and the
305 // offset will always be 0. In the case of the Primary, the worst case
306 // scenario happens in the last size class, when the backend allocation
307 // would already be aligned on the requested alignment, which would happen
308 // to be the maximum alignment that would fit in that size class. As a
309 // result, the maximum offset will be at most the maximum alignment for the
310 // last size class minus the header size, in multiples of MinAlignment.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000311 UnpackedHeader Header = {};
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000312 uptr MaxPrimaryAlignment =
313 1 << MostSignificantSetBitIndex(SizeClassMap::kMaxSize - MinAlignment);
314 uptr MaxOffset =
315 (MaxPrimaryAlignment - AlignedChunkHeaderSize) >> MinAlignmentLog;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000316 Header.Offset = MaxOffset;
317 if (Header.Offset != MaxOffset) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000318 dieWithMessage("ERROR: the maximum possible offset doesn't fit in the "
319 "header\n");
320 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000321 // Verify that we can fit the maximum size or amount of unused bytes in the
322 // header. Given that the Secondary fits the allocation to a page, the worst
323 // case scenario happens in the Primary. It will depend on the second to
324 // last and last class sizes, as well as the dynamic base for the Primary.
325 // The following is an over-approximation that works for our needs.
326 uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
327 Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
328 if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000329 dieWithMessage("ERROR: the maximum possible unused bytes doesn't fit in "
330 "the header\n");
331 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000332
333 DeallocationTypeMismatch = Options.DeallocationTypeMismatch;
334 DeleteSizeMismatch = Options.DeleteSizeMismatch;
335 ZeroContents = Options.ZeroContents;
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000336 SetAllocatorMayReturnNull(Options.MayReturnNull);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000337 BackendAllocator.init(Options.ReleaseToOSIntervalMs);
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000338 AllocatorQuarantine.Init(
339 static_cast<uptr>(Options.QuarantineSizeMb) << 20,
340 static_cast<uptr>(Options.ThreadLocalQuarantineSizeKb) << 10);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000341 GlobalPrng.init();
342 Cookie = GlobalPrng.getU64();
343 BackendAllocator.initCache(&FallbackAllocatorCache);
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000344 FallbackPrng.init();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000345 }
346
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000347 // Helper function that checks for a valid Scudo chunk. nullptr isn't.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000348 bool isValidPointer(const void *UserPtr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000349 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000350 if (UNLIKELY(!UserPtr))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000351 return false;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000352 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
353 if (!IsAligned(UserBeg, MinAlignment))
354 return false;
355 return getScudoChunk(UserBeg)->isValid();
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000356 }
357
Kostya Serebryany712fc982016-06-07 01:20:26 +0000358 // Allocates a chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000359 void *allocate(uptr Size, uptr Alignment, AllocType Type,
360 bool ForceZeroContents = false) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000361 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000362 if (UNLIKELY(Alignment > MaxAlignment))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000363 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000364 if (UNLIKELY(Alignment < MinAlignment))
Kostya Serebryany712fc982016-06-07 01:20:26 +0000365 Alignment = MinAlignment;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000366 if (UNLIKELY(Size >= MaxAllowedMallocSize))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000367 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000368 if (UNLIKELY(Size == 0))
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000369 Size = 1;
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000370
371 uptr NeededSize = RoundUpTo(Size, MinAlignment) + AlignedChunkHeaderSize;
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000372 uptr AlignedSize = (Alignment > MinAlignment) ?
373 NeededSize + (Alignment - AlignedChunkHeaderSize) : NeededSize;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000374 if (UNLIKELY(AlignedSize >= MaxAllowedMallocSize))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000375 return FailureHandler::OnBadRequest();
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000376
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000377 // Primary and Secondary backed allocations have a different treatment. We
378 // deal with alignment requirements of Primary serviced allocations here,
379 // but the Secondary will take care of its own alignment needs.
380 bool FromPrimary = PrimaryAllocator::CanAllocate(AlignedSize, MinAlignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000381
382 void *Ptr;
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000383 u8 Salt;
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000384 uptr AllocSize;
385 if (FromPrimary) {
386 AllocSize = AlignedSize;
387 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
388 if (LIKELY(ThreadContext)) {
389 Salt = getPrng(ThreadContext)->getU8();
390 Ptr = BackendAllocator.allocatePrimary(getAllocatorCache(ThreadContext),
391 AllocSize);
392 ThreadContext->unlock();
393 } else {
394 SpinMutexLock l(&FallbackMutex);
395 Salt = FallbackPrng.getU8();
396 Ptr = BackendAllocator.allocatePrimary(&FallbackAllocatorCache,
397 AllocSize);
398 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000399 } else {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000400 {
401 SpinMutexLock l(&GlobalPrngMutex);
402 Salt = GlobalPrng.getU8();
403 }
404 AllocSize = NeededSize;
405 Ptr = BackendAllocator.allocateSecondary(AllocSize, Alignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000406 }
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000407 if (UNLIKELY(!Ptr))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000408 return FailureHandler::OnOOM();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000409
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000410 // If requested, we will zero out the entire contents of the returned chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000411 if ((ForceZeroContents || ZeroContents) && FromPrimary)
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000412 memset(Ptr, 0, BackendAllocator.getActuallyAllocatedSize(
413 Ptr, /*FromPrimary=*/true));
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000414
Kostya Serebryany712fc982016-06-07 01:20:26 +0000415 UnpackedHeader Header = {};
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000416 uptr AllocBeg = reinterpret_cast<uptr>(Ptr);
417 uptr UserBeg = AllocBeg + AlignedChunkHeaderSize;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000418 if (UNLIKELY(!IsAligned(UserBeg, Alignment))) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000419 // Since the Secondary takes care of alignment, a non-aligned pointer
420 // means it is from the Primary. It is also the only case where the offset
421 // field of the header would be non-zero.
422 CHECK(FromPrimary);
423 UserBeg = RoundUpTo(UserBeg, Alignment);
424 uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg;
425 Header.Offset = Offset >> MinAlignmentLog;
426 }
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000427 CHECK_LE(UserBeg + Size, AllocBeg + AllocSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000428 Header.State = ChunkAllocated;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000429 Header.AllocType = Type;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000430 if (FromPrimary) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000431 Header.FromPrimary = 1;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000432 Header.SizeOrUnusedBytes = Size;
433 } else {
434 // The secondary fits the allocations to a page, so the amount of unused
435 // bytes is the difference between the end of the user allocation and the
436 // next page boundary.
437 uptr PageSize = GetPageSizeCached();
438 uptr TrailingBytes = (UserBeg + Size) & (PageSize - 1);
439 if (TrailingBytes)
440 Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
441 }
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000442 Header.Salt = Salt;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000443 getScudoChunk(UserBeg)->storeHeader(&Header);
444 void *UserPtr = reinterpret_cast<void *>(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000445 // if (&__sanitizer_malloc_hook) __sanitizer_malloc_hook(UserPtr, Size);
446 return UserPtr;
447 }
448
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000449 // Place a chunk in the quarantine. In the event of a zero-sized quarantine,
450 // we directly deallocate the chunk, otherwise the flow would lead to the
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000451 // chunk being loaded (and checked) twice, and stored (and checksummed) once,
452 // with no additional security value.
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000453 void quarantineOrDeallocateChunk(ScudoChunk *Chunk, UnpackedHeader *Header,
454 uptr Size) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000455 bool FromPrimary = Header->FromPrimary;
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000456 bool BypassQuarantine = (AllocatorQuarantine.GetCacheSize() == 0);
457 if (BypassQuarantine) {
458 Chunk->eraseHeader();
459 void *Ptr = Chunk->getAllocBeg(Header);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000460 if (FromPrimary) {
461 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
462 if (LIKELY(ThreadContext)) {
463 getBackendAllocator().deallocatePrimary(
464 getAllocatorCache(ThreadContext), Ptr);
465 ThreadContext->unlock();
466 } else {
467 SpinMutexLock Lock(&FallbackMutex);
468 getBackendAllocator().deallocatePrimary(&FallbackAllocatorCache, Ptr);
469 }
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000470 } else {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000471 getBackendAllocator().deallocateSecondary(Ptr);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000472 }
473 } else {
474 UnpackedHeader NewHeader = *Header;
475 NewHeader.State = ChunkQuarantine;
476 Chunk->compareExchangeHeader(&NewHeader, Header);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000477 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000478 if (LIKELY(ThreadContext)) {
479 AllocatorQuarantine.Put(getQuarantineCache(ThreadContext),
480 QuarantineCallback(
481 getAllocatorCache(ThreadContext)),
482 Chunk, Size);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000483 ThreadContext->unlock();
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000484 } else {
485 SpinMutexLock l(&FallbackMutex);
486 AllocatorQuarantine.Put(&FallbackQuarantineCache,
487 QuarantineCallback(&FallbackAllocatorCache),
488 Chunk, Size);
489 }
490 }
491 }
492
Kostya Serebryany712fc982016-06-07 01:20:26 +0000493 // Deallocates a Chunk, which means adding it to the delayed free list (or
494 // Quarantine).
495 void deallocate(void *UserPtr, uptr DeleteSize, AllocType Type) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000496 initThreadMaybe();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000497 // if (&__sanitizer_free_hook) __sanitizer_free_hook(UserPtr);
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000498 if (UNLIKELY(!UserPtr))
Kostya Serebryany712fc982016-06-07 01:20:26 +0000499 return;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000500 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
501 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000502 dieWithMessage("ERROR: attempted to deallocate a chunk not properly "
503 "aligned at address %p\n", UserPtr);
504 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000505 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000506 UnpackedHeader OldHeader;
507 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000508 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000509 dieWithMessage("ERROR: invalid chunk state when deallocating address "
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000510 "%p\n", UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000511 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000512 if (DeallocationTypeMismatch) {
513 // The deallocation type has to match the allocation one.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000514 if (OldHeader.AllocType != Type) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000515 // With the exception of memalign'd Chunks, that can be still be free'd.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000516 if (OldHeader.AllocType != FromMemalign || Type != FromMalloc) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000517 dieWithMessage("ERROR: allocation type mismatch on address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000518 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000519 }
520 }
521 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000522 uptr Size = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
523 Chunk->getUsableSize(&OldHeader) - OldHeader.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000524 if (DeleteSizeMismatch) {
525 if (DeleteSize && DeleteSize != Size) {
526 dieWithMessage("ERROR: invalid sized delete on chunk at address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000527 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000528 }
529 }
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000530
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000531 // If a small memory amount was allocated with a larger alignment, we want
532 // to take that into account. Otherwise the Quarantine would be filled with
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000533 // tiny chunks, taking a lot of VA memory. This is an approximation of the
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000534 // usable size, that allows us to not call GetActuallyAllocatedSize.
535 uptr LiableSize = Size + (OldHeader.Offset << MinAlignment);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000536 quarantineOrDeallocateChunk(Chunk, &OldHeader, LiableSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000537 }
538
Kostya Serebryany712fc982016-06-07 01:20:26 +0000539 // Reallocates a chunk. We can save on a new allocation if the new requested
540 // size still fits in the chunk.
541 void *reallocate(void *OldPtr, uptr NewSize) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000542 initThreadMaybe();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000543 uptr UserBeg = reinterpret_cast<uptr>(OldPtr);
544 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
545 dieWithMessage("ERROR: attempted to reallocate a chunk not properly "
546 "aligned at address %p\n", OldPtr);
547 }
548 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000549 UnpackedHeader OldHeader;
550 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000551 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000552 dieWithMessage("ERROR: invalid chunk state when reallocating address "
553 "%p\n", OldPtr);
554 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000555 if (UNLIKELY(OldHeader.AllocType != FromMalloc)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000556 dieWithMessage("ERROR: invalid chunk type when reallocating address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000557 OldPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000558 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000559 uptr UsableSize = Chunk->getUsableSize(&OldHeader);
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000560 // The new size still fits in the current chunk, and the size difference
561 // is reasonable.
562 if (NewSize <= UsableSize &&
563 (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000564 UnpackedHeader NewHeader = OldHeader;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000565 NewHeader.SizeOrUnusedBytes =
566 OldHeader.FromPrimary ? NewSize : UsableSize - NewSize;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000567 Chunk->compareExchangeHeader(&NewHeader, &OldHeader);
568 return OldPtr;
569 }
570 // Otherwise, we have to allocate a new chunk and copy the contents of the
571 // old one.
572 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
573 if (NewPtr) {
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000574 uptr OldSize = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
575 UsableSize - OldHeader.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000576 memcpy(NewPtr, OldPtr, Min(NewSize, OldSize));
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000577 quarantineOrDeallocateChunk(Chunk, &OldHeader, UsableSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000578 }
579 return NewPtr;
580 }
581
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000582 // Helper function that returns the actual usable size of a chunk.
583 uptr getUsableSize(const void *Ptr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000584 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000585 if (UNLIKELY(!Ptr))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000586 return 0;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000587 uptr UserBeg = reinterpret_cast<uptr>(Ptr);
588 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000589 UnpackedHeader Header;
590 Chunk->loadHeader(&Header);
591 // Getting the usable size of a chunk only makes sense if it's allocated.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000592 if (UNLIKELY(Header.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000593 dieWithMessage("ERROR: invalid chunk state when sizing address %p\n",
594 Ptr);
595 }
596 return Chunk->getUsableSize(&Header);
597 }
598
Kostya Serebryany712fc982016-06-07 01:20:26 +0000599 void *calloc(uptr NMemB, uptr Size) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000600 initThreadMaybe();
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000601 if (UNLIKELY(CheckForCallocOverflow(NMemB, Size)))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000602 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000603 return allocate(NMemB * Size, MinAlignment, FromMalloc, true);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000604 }
605
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000606 void commitBack(ScudoThreadContext *ThreadContext) {
607 AllocatorCache *Cache = getAllocatorCache(ThreadContext);
608 AllocatorQuarantine.Drain(getQuarantineCache(ThreadContext),
609 QuarantineCallback(Cache));
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000610 BackendAllocator.destroyCache(Cache);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000611 }
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000612
613 uptr getStats(AllocatorStat StatType) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000614 initThreadMaybe();
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000615 uptr stats[AllocatorStatCount];
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000616 BackendAllocator.getStats(stats);
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000617 return stats[StatType];
618 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000619};
620
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000621static ScudoAllocator Instance(LINKER_INITIALIZED);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000622
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000623static ScudoBackendAllocator &getBackendAllocator() {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000624 return Instance.BackendAllocator;
625}
626
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000627static void initScudoInternal(const AllocatorOptions &Options) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000628 Instance.init(Options);
629}
630
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000631void ScudoThreadContext::init() {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000632 getBackendAllocator().initCache(&Cache);
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000633 Prng.init();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000634 memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
635}
636
637void ScudoThreadContext::commitBack() {
638 Instance.commitBack(this);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000639}
640
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000641INLINE void *checkPtr(void *Ptr) {
642 if (UNLIKELY(!Ptr))
643 errno = errno_ENOMEM;
644 return Ptr;
645}
646
Kostya Serebryany712fc982016-06-07 01:20:26 +0000647void *scudoMalloc(uptr Size, AllocType Type) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000648 return checkPtr(Instance.allocate(Size, MinAlignment, Type));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000649}
650
651void scudoFree(void *Ptr, AllocType Type) {
652 Instance.deallocate(Ptr, 0, Type);
653}
654
655void scudoSizedFree(void *Ptr, uptr Size, AllocType Type) {
656 Instance.deallocate(Ptr, Size, Type);
657}
658
659void *scudoRealloc(void *Ptr, uptr Size) {
660 if (!Ptr)
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000661 return checkPtr(Instance.allocate(Size, MinAlignment, FromMalloc));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000662 if (Size == 0) {
663 Instance.deallocate(Ptr, 0, FromMalloc);
664 return nullptr;
665 }
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000666 return checkPtr(Instance.reallocate(Ptr, Size));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000667}
668
669void *scudoCalloc(uptr NMemB, uptr Size) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000670 return checkPtr(Instance.calloc(NMemB, Size));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000671}
672
673void *scudoValloc(uptr Size) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000674 return checkPtr(Instance.allocate(Size, GetPageSizeCached(), FromMemalign));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000675}
676
Kostya Serebryany712fc982016-06-07 01:20:26 +0000677void *scudoPvalloc(uptr Size) {
678 uptr PageSize = GetPageSizeCached();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000679 // pvalloc(0) should allocate one page.
680 Size = Size ? RoundUpTo(Size, PageSize) : PageSize;
681 return checkPtr(Instance.allocate(Size, PageSize, FromMemalign));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000682}
683
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000684void *scudoMemalign(uptr Alignment, uptr Size) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000685 if (UNLIKELY(!IsPowerOfTwo(Alignment))) {
686 errno = errno_EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000687 return ScudoAllocator::FailureHandler::OnBadRequest();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000688 }
689 return checkPtr(Instance.allocate(Size, Alignment, FromMemalign));
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000690}
691
Kostya Serebryany712fc982016-06-07 01:20:26 +0000692int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000693 if (UNLIKELY(!IsPowerOfTwo(Alignment) || (Alignment % sizeof(void *)) != 0)) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000694 ScudoAllocator::FailureHandler::OnBadRequest();
695 return errno_EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000696 }
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000697 void *Ptr = Instance.allocate(Size, Alignment, FromMemalign);
698 if (!Ptr)
699 return errno_ENOMEM;
700 *MemPtr = Ptr;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000701 return 0;
702}
703
704void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000705 // Alignment must be a power of 2, Size must be a multiple of Alignment.
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000706 if (UNLIKELY(!IsPowerOfTwo(Alignment) || (Size & (Alignment - 1)) != 0)) {
707 errno = errno_EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000708 return ScudoAllocator::FailureHandler::OnBadRequest();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000709 }
710 return checkPtr(Instance.allocate(Size, Alignment, FromMalloc));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000711}
712
713uptr scudoMallocUsableSize(void *Ptr) {
714 return Instance.getUsableSize(Ptr);
715}
716
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000717} // namespace __scudo
Kostya Serebryany712fc982016-06-07 01:20:26 +0000718
719using namespace __scudo;
720
721// MallocExtension helper functions
722
723uptr __sanitizer_get_current_allocated_bytes() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000724 return Instance.getStats(AllocatorStatAllocated);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000725}
726
727uptr __sanitizer_get_heap_size() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000728 return Instance.getStats(AllocatorStatMapped);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000729}
730
731uptr __sanitizer_get_free_bytes() {
732 return 1;
733}
734
735uptr __sanitizer_get_unmapped_bytes() {
736 return 1;
737}
738
739uptr __sanitizer_get_estimated_allocated_size(uptr size) {
740 return size;
741}
742
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000743int __sanitizer_get_ownership(const void *Ptr) {
744 return Instance.isValidPointer(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000745}
746
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000747uptr __sanitizer_get_allocated_size(const void *Ptr) {
748 return Instance.getUsableSize(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000749}